我使用Google Maps API请求路线,之后路线会自动居中,因为我使用的选项是“preserveViewport:false”。现在我希望转移中心一点点。所以我通过以下代码尝试了它:
var overlay_1 = new google.maps.OverlayView();
overlay_1.draw = function () {};
overlay_1.setMap(map_1);
var point_1
point_1 = overlay_1.getProjection().fromLatLngToContainerPixel(map_1.getCenter());
point_1.x = point_1.x + 300;
map_1.setCenter(overlay_1.getProjection().fromContainerPixelToLatLng(point_1));
当我启动网页时,我收到以下错误:
未捕获的TypeError:无法读取属性'fromLatLngToContainerPixel' 未定义的
正如您在我的Printscreen中看到的那样,当我将它放入我的控制台时代码正常工作。
有没有人知道为什么我在加载网页时遇到错误?
答案 0 :(得分:1)
在projection_changed
方法返回有效结果之前,您必须等待覆盖重叠.getProjection
事件。
相关问题:Why getProjection() is not working in V3
var overlay_1 = new google.maps.OverlayView();
overlay_1.draw = function() {};
overlay_1.setMap(map_1);
var point_1;
google.maps.event.addListener(overlay_1, 'projection_changed', function() {
point_1 = overlay_1.getProjection().fromLatLngToContainerPixel(map_1.getCenter());
point_1.x = point_1.x + 300;
map_1.setCenter(overlay_1.getProjection().fromContainerPixelToLatLng(point_1));
});
代码段
function initialize() {
var map_1 = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var overlay_1 = new google.maps.OverlayView();
overlay_1.draw = function() {};
overlay_1.setMap(map_1);
var point_1;
google.maps.event.addListener(overlay_1, 'projection_changed', function() {
point_1 = overlay_1.getProjection().fromLatLngToContainerPixel(map_1.getCenter());
point_1.x = point_1.x + 300;
map_1.setCenter(overlay_1.getProjection().fromContainerPixelToLatLng(point_1));
});
}
google.maps.event.addDomListener(window, "load", initialize);

html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
&#13;