通过网格拆分高德地图
因为爬虫需要,如大众点评通过距离获取商铺,以及高德poi获取有数量限制。就想到通过网格的方式,把高德地图拆分成一个一个的格子,获取对应的经纬度,然后通过对应的经纬度去爬取收据。
思路:
首先获取城市的边界范围,根据边界画出一个矩形。然后通过 new AMap.LngLat获取相应的点。但是考虑到绘制的会远大于该城市实际范围,在城市内部再绘制一个矩形。外围矩形每五公里拆分一次,内部矩形每公里拆分一次。
主要代码如下
var x1 = new AMap.LngLat(left_lng, left_lat) var x2 = new AMap.LngLat(right_lng, left_lat) var y = new AMap.LngLat(left_lng, right_lat) var center_x1 = new AMap.LngLat(center_left_lng, center_left_lat) var center_x2 = new AMap.LngLat(center_right_lng, center_left_lat) var center_y = new AMap.LngLat(center_left_lng, center_right_lat) var x_distance = x1.distance(x2); var y_distance = x1.distance(y); var center_x_distance = center_x1.distance(center_x2); var center_y_distance = center_x1.distance(center_y); console.log(x_distance, y_distance) console.log(center_x_distance, center_y_distance) drawGrad(x_distance, y_distance); function drawGrad(x, y) {//x,y代表的是距离 var x_total = Math.floor(x / km);//首尾,故点多1 var y_total = Math.floor(y / km); console.log(x_total, y_total) for (var i = 0; i < x_total + 1; i++) { for (var j = 0; j < y_total + 1; j++) { let point = southWest.offset(km * i, -km * j) //在内部矩形,则跳过 if ((center_left_lng <= point.lng && point.lng <= center_right_lng) && (center_right_lat <= point.lat && point.lat <= center_left_lat)) { continue } pointsObj[i + "_" + j] = point.lng + ',' + point.lat if (i > 0 && j > 0) { let last_point = pointsObj[(i - 1) + '_' + (j - 1)]; if(!last_point){ continue } arrList.push(last_point+ '|' + pointsObj[i + '_' + j]) } var bounds2 = new AMap.Bounds(southWest, point) var rectangle2 = new AMap.Rectangle({ bounds: bounds2, strokeColor: '#000', strokeWeight: 1, strokeStyle: 'dashed', fillColor: 'transparent', }) rectangle2.setMap(map) if (i == x_total && j == y_total) { // console.error(Date.parse(new Date())) console.log(arrList.length) console.log(JSON.stringify(arrList)) } } } }
完整代码已上传GitHub,并上传了辅助找边界的页面。https://github.com/c870275682/gaode_tool