mapbox-gl開發(fā):畫圓的一些問題
mapbox-gl提供了一個畫圓的圖層方式,圖層的類型設(shè)置成circle,通過設(shè)置circle-radius,實(shí)現(xiàn)圓的大小設(shè)置,不過這個參數(shù)的單位是像素,在地圖縮放的時候,圓的大小并不變,根據(jù)地圖上一定距離的效果,這個并不滿足要求。
所以,在實(shí)現(xiàn)地圖上按照一定距離(米)的圓范圍,需要進(jìn)行一定的變換,在mapbox-gl的討論話題中,找到一種按照地理距離實(shí)現(xiàn)畫圓的方式,同時,能夠在地圖縮放時,隨著地圖變化。
根據(jù)下列函數(shù),傳入圓的地理距離和圓中心點(diǎn)所在的緯度坐標(biāo),計算地圖縮放到20級時,圓在屏幕上的像素尺寸:
function metersToPixelsAtMaxZoom(meters, latitude) {
return meters / 0.075 / Math.cos(latitude * Math.PI / 180)
}
在地圖上添加圓的時候,根據(jù)計算的像素尺寸,通過mapbox-gl的expression表達(dá)式設(shè)置,實(shí)現(xiàn)隨著地圖縮放,圓的尺寸變化:
//添加數(shù)據(jù)源
map.addSource("circle_source", {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [110.132, 21.768]
}?
}]
}
});
//添加圓的圖層
map.addLayer({
"id": "circle_layer",
//類型設(shè)置
"type": "circle",
//數(shù)據(jù)源id設(shè)置
"source": "circle_source",
"paint": {
? ?//關(guān)鍵處,設(shè)置圓的半徑隨地圖縮放而變化
"circle-radius": {
stops: [
? ? ? ? ? ? ? ? ? ? ? ? [0, 0],
[20, _pixelRadius]],
base: 2
},
?? ? ? ? ? ? ? ? ? ?//設(shè)置圓的其他屬性
"circle-opacity": 0.5,
"circle-stroke-width": 1,
"circle-color": "#00f",
"circle-pitch-alignment": "map"
}
});
添加的圓圖層就能根據(jù)地圖縮放而變化:
