前言:mapbox 定位方法,可以使用flyTo 和panTo,但这两个方法是地图中心定位到某个点。有个场景,查看某个geojson(含几个面polygon)全局,那么如何实现呢
思路一:计算 geojson的中心点,然后使用 flyTo
// parkJson示例数据
this.parkJson =
{"type":"FeatureCollection","features":[
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[...]}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[...]}},
{"type":"Feature","geometry":{"type":"Polygon","coordinates":[...]}}
]
部分示例代码
...
// VUE
import { centerOfMass } from '@turf/turf';
// centerOfMass 计算面的质心
...
// this.parkJson 是几个polygon的featureCollection
const center = centerOfMass (this.parkJson);
// center 结果:
//{
// "type": "Feature",
// "properties": {},
// "geometry": {
// "type": "Point",
// "coordinates": [113.74013261, 22.7442798]
// }
//}
// map 是 mapboxgl.Map
map.flyTo({
center:center.geometry.coordinates,
zoom: 13.5,
});
注:该代码只是示例代码
不足:需要指定zoom级别,并且不一定可以将所有面都在地图框全局展示
思路二:计算geojson的bbox(矩形边界),然后使用 fitBounds
部分示例代码:
...
// VUE
import { bbox } from '@turf/turf';
...
// this.parkJson 是几个polygon的featureCollection
const bounds = bbox(this.parkJson);
if(!bounds || bounds.length < 4) {
return;
}
// map 是 mapboxgl.Map
map.fitBounds([[bounds[0], bounds[1]], [bounds[2], bounds[3]]], { animate: true, padding: 0 });
思路二,比较符合场景
最后的话:turf.js 是一个强大的 js 地理空间计算库,感兴趣的可以深入了解一下