最近遇到一个需求:前端在地图上绘制货车导航路线,调研后发现腾讯地图最便宜,公司采用了这个。
问题:
每次在页面查询获取最新路线,不会定位到当前路线的位置,官方api提供了fitBounds方法,大概就是根据所有点的位置找到所在的范围,然后适应它。
第一版方案:
传入起点、终点
const markerArr = [
{
id: 'start',
styleId: 'start',
position: from,//起点坐标 new TMap.LatLng(lat, lon)
properties: {
title: 'marker1',
},
},
{
id: 'end',
styleId: 'end',
position: to,,//终点坐标 new TMap.LatLng(lat, lon)
properties: {
title: 'marker2',
},
},
];
let bounds = new TMap.LatLngBounds();
markerArr.forEach((item) => {
if (bounds.isEmpty() || !bounds.contains(item.position)) {
bounds.extend(item.position);
}
});
// 设置地图可是范围
map.fitBounds(bounds, {
padding: 100, //自适应边距
});
发现这招不好使,因为路线的起点和终点可能离得很近,其实整个路线过程行驶的非常长,就会导致视图是定位到两个点,但是无法观察整个路线情况。
第二版
把上面传入的点换成路线上所有点就可以啦
//path是所有点经纬度的集合,一维数组
const markerArr = path.map((it, index) => {
return {
id: index,
styleId: 'start',
position: it,
properties: {
title: `marker${index}`,
},
};
});