mapbox-gl繪制經(jīng)緯網(wǎng)格(Graticule)
在mapbox-gl上實(shí)現(xiàn)經(jīng)緯網(wǎng)格,是按照經(jīng)度、緯度的一定間隔,將同經(jīng)度(緯度)的坐標(biāo)點(diǎn),連接成直線,實(shí)現(xiàn)繪制經(jīng)緯度網(wǎng)格的形式。
//緯線
function?makeMeridian(lng) {
lng = lngFix(lng);
const?coords = [];
for?(var?lat = -90; lat <=?90; lat +=?1) {
coords.push([lng, lat]);
}
return?coords;
}
//經(jīng)線
function?makeParallel(lat) {
const?coords = [];
for?(var?lng = -180; lng <=?180; lng +=?1) {
coords.push([lngFix(lng), lat]);
}
return?coords;
}
//創(chuàng)建geojson數(shù)據(jù)
function?makeFeature(coordinates, properties) {
return?{
type:?'Feature',
geometry: {
type:?'LineString',
coordinates
},
properties
};
}
//修整經(jīng)度,防止最大值溢出
function?lngFix(lng) {
if?(lng >=?180)?return?179.999999;
if?(lng <= -180)?return?-179.999999;
return?lng;
}
//主函數(shù)
function?graticule(interval) {
interval = +interval ||?20;
const?features = [];
for?(var?lng =?0; lng <=?180; lng += interval) {
features.push(makeFeature(makeMeridian(lng), {
name: (lng) ? lng.toString() +?"° E"?:?"本初子午線"
}));
if?(lng !==?0) {
features.push(makeFeature(makeMeridian(-lng), {
name: lng.toString() +?"° W"
}));
}
}
for?(var?lat =?0; lat <=?90; lat += interval) {
features.push(makeFeature(makeParallel(lat), {
name: (lat) ? lat.toString() +?"° N"?:?"赤道"
}));
if?(lat !==?0) {
features.push(makeFeature(makeParallel(-lat), {
"name": lat.toString() +?"° S"
}));
}
}
return?{
type:?'FeatureCollection',
features
};
}
//添加經(jīng)緯度圖層
const?_griddata = graticule(5);
map.addSource('gridline', {
'type':?'geojson',
'data': _griddata
});
map.addLayer({
'id':?'gridid',
'type':?'line',
'source':?'gridline',
'layout': {
'line-join':?'round',
'line-cap':?'round'
},
'paint': {
'line-color':?'#f00',
'line-width':?1
}
});
效果圖如下:
以上是5度為間隔畫的經(jīng)緯度網(wǎng)格,拉到最北邊和最南邊,會清楚的看到,只能顯示到+-85多的坐標(biāo)位置。

引用內(nèi)容:
https://github.com/turban/Leaflet.Graticule
https://github.com/dereklieu/cool-grid