要实现你想要的,你需要在正确的轴上旋转地图,找到地图中心的位置,最后center地图在正确的位置。
1 - 旋转地图
在您的情况下(我假设您希望汽车始终面向用户位置前方的道路)您需要在居中之前旋转地图,否则地图始终朝向北方,并且当汽车向其他方向移动(例如向南)。在这种情况下,视点方向错误,用户看不到即将到来的道路。
您可以在文档中找到示例 here。基本上你需要使用setHeading() 方法。 gmap 上的旋转并不容易(见this post)。
2 - 找到地图的中心
要查找地图中心的更新位置,您需要检索始终位于标记固定位置上方相同距离(以地图容器的像素为单位)的点的 latLng 位置。使用方法fromLatLngToPoint() 和fromPointToLatLng() 将位置从地图检索到现实世界,反之亦然(有关详细信息,请参阅getProjection())。
示例:
您的地图以 1000*1000 像素显示,您选择的标记的底部位置位于左侧 500 像素和顶部 950 像素处。如果要在不改变标记位置的情况下移动地图中心,则需要在标记上方 450px 处找到点的 latLng 位置。
function findMapCenter(map, markerLatLng) {
// need this to adjust from the actual zoom on the map
let scale = Math.pow(2, map.getZoom());
// position in pixel x.y from the container
let markerWorldCoordinate = map.getProjection().fromLatLngToPoint(markerLatLng);
// calcul of the position of the center
let centerWorldCoordinate = new google.maps.Point(
markerWorldCoordinate.x,
markerWorldCoordinate.y + (450/scale) // 450 because in my exemple is from 450px at the top of the marker
);
// return latLng of the center point of the map
return map.getProjection().fromPointToLatLng(centerWorldCoordinate);
}
3 - 将地图设置在正确的位置
使用setCenter() 方法将地图居中于选定的纬度位置。
let marker; // = config of your marker
let gMap = new google.maps.Map(document.getElementById('map'));
update({lat:MARKER_LATITUDE, lng:MARKER_LONGITUDE});
// call this every time you want to update
function update(markerNewLatLng){
// ... first step : rotate the map if you need to
// then update marker position
marker.setPosition(markerNewLatLng);
// center the map
gMap.setCenter(findMapCenter(gmap, markerNewLatLng));
}