我正在为页面添加 map ,但 map 始终偏离给定坐标的中心。可能相关的一个有趣的额外信息是,距离越远(缩小),差异就越大。我已经围绕其他线程做了一些研究,并且发现许多建议使用 map.getCenter()
但这要么不是解决方案,要么是我误用了,因为它不起作用。
这是我正在使用的代码(无耻地使用了谷歌地图教程):
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: new google.maps.LatLng('lat', 'lng'),
zoom: 20,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
因为我在display:none
上创建 map div,我也在使用google.maps.event.trigger(map, 'resize');
在我的页面中修复“左上角”错误。请注意,我的问题与此无关,但我读到未对齐可能是由调整大小解决方案引起的,因此我认为它可能是相关的。
考虑到我正在尝试引用一个非常小的区域,因此 map 位于中心非常重要。我应该把map.getCenter()
放在哪里或者有更好的解决方案来解决这个问题吗?
感谢您提供的任何意见。
最佳答案
以下示例演示了如何在调整 map 大小时保留原始中心,当触发 idle
事件时设置 map 中心。
示例
function initialize() {
var centerLatLng = new google.maps.LatLng(60.169621, 24.952265);
var map = new google.maps.Map(document.getElementById('map'), {
center: centerLatLng,
zoom: 19
});
google.maps.event.addListener(map,'idle',function(event) {
map.setCenter(centerLatLng); //force to set original center position
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map" ></div>
关于javascript - Google map 的结果偏离中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32042213/