Mapbox GL JS 根據指定的點在地圖上標記一個指定半徑(KM)的圓形區域
阿新 • • 發佈:2018-12-18
需求描述:
小明在使用mapbox-gl進行開發時,需要實現使用者指定地圖上的一個點,然後根據這個點,突出顯示以其為中心的一定半徑的圓形區域。半徑可以為小明指定的千米數。
具體實現點選產生點的功能就不描述了,這裡主要描述產生圓形區域的方法。
1. 建構函式:輸入中心點經緯度,和半徑大小(KM),以及點數。
var createGeoJSONCircle = function(center, radiusInKm, points) {
if(!points) points = 64;
var coords = {
latitude: center[1],
longitude: center[0]
};
var km = radiusInKm;
var ret = [];
var distanceX = km/(111.320*Math.cos(coords.latitude*Math.PI/180));
var distanceY = km/110.574;
var theta, x, y;
for(var i=0; i<points; i++) {
theta = (i/points)*(2*Math.PI);
x = distanceX*Math.cos(theta);
y = distanceY*Math.sin(theta);
ret.push([coords.longitude+x, coords.latitude+y]);
}
ret.push(ret[0]);
return {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry" : {
"type": "Polygon",
"coordinates": [ret]
}
}]
}
};
};
2. 你可以這樣使用它:
map.addSource("polygon", createGeoJSONCircle([-93.6248586, 41.58527859], 0.5));
map.addLayer({
"id": "polygon",
"type": "fill",
"source": "polygon",
"layout": {},
"paint": {
"fill-color": "blue",
"fill-opacity": 0.6
}
});
3. 或者後面在某個函式中又更新這個圓形區域,則使用下面的程式碼來更新source:
map.getSource('polygon').setData(createGeoJSONCircle([-93.6248586, 41.58527859], 1).data);
4. 示例
連結: link.
圖片: