Javascript 如何移动谷歌地图的中心位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14305876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to move the center position of google map
提问by MD Sayem Ahmed
I am creating a google map in a script with the following code -
我正在使用以下代码在脚本中创建谷歌地图 -
var mapElement,
parent,
mapOptions,
map,
marker,
latLong,
openMarker;
parent = document.getElementsByClassName('parent')[0];
mapElement = document.createElement('div');
latLong = new google.maps.LatLng(some_lat_from_db, some_long_from_db);
mapOptions = {
center: latLong,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(mapElement, mapOptions);
marker = new google.maps.Marker({
position: latLong,
map: map,
title: 'some title'
});
openMarker = function () {
var infowindow = new google.maps.InfoWindow();
infowindow.setContent('Some Content');
infowindow.open(map, marker);
};
google.maps.event.addListener(marker, 'click', openMarker);
parent.appendChild(mapElement);
openMarker();
When using this code, the infowindow that opens up by default goes outside the map viewport, so it's not visible. I first tried to reduce the size of the info window but that didn't work out. So I thought to move the center of the map a bit so that the info window remains in the viewport.
使用此代码时,默认情况下打开的信息窗口位于地图视口之外,因此不可见。我首先尝试减小信息窗口的大小,但没有成功。所以我想稍微移动地图的中心,以便信息窗口保留在视口中。
So, how can I move the center by some pixels so that the info window remains in the viewport?
那么,如何将中心移动一些像素,以便信息窗口保留在视口中?
回答by Andreas
You can use .setCenter()to move the center of the map
您可以使用.setCenter()移动地图的中心
map.setCenter(marker.getPosition());
Update
更新
Convert the LatLngwith .fromLatLngToDivPixel()into a Pointadd an offset and convert it back into a LatLngwith .fromDivPixelToLatLng()
将LatLngwith .fromLatLngToDivPixel()转换为Point添加偏移量并将其转换回LatLngwith .fromDivPixelToLatLng()
回答by Nelles
forget all that crap this is what works if you want to reuse a google map marker or move a google map marker, or recenter a google map marker.
忘记所有这些废话,如果您想重用谷歌地图标记或移动谷歌地图标记,或重新定位谷歌地图标记,这就是有效的。
var lo = <yourval>;
var la = <yourval>;
var midpoint = {lat:la, lng:lo };
marker.setPosition(midpoint);
if you want to destroy a google maps marker or delete a google maps marker
如果您想销毁谷歌地图标记或删除谷歌地图标记
marker.setMap(null);

