开发者

Center a V3 Google Map on route after directions are rendered

I have a V3 map loading and centering on a particular longitude/latitude by default. Once loaded, the user can enter their address to get directions to that point. When this happens, the map is resized to accomodate a directions box to its left. Because of this, the route is off-center in the map window. I tried the following code, which I thought should logically work, but to no avail.

New realization: If I resize the window in any way, it begins to work as expected.

Found the issue: I needed to trigger google.maps.event.trigger(map, 'resize') after I resize the map container.

directionsService.route(query, function(result,status) {
    if (status === google.maps.DirectionsStatus.OK) {
        // This sets the directions container to display:block and resizes the map
        document.getElementById('map-container').className = "directio开发者_高级运维ns";
        directions.setDirections(result);
        var bounds = result.routes[0].bounds;
        map.fitBounds(bounds);
        map.setCenter(bounds.getCenter());
    } else {
        alert("");
    }
});

UPDATE 2018-05-22

With a new renderer release in version 3.32 of Maps JavaScript API the resize event is no longer a part of Map class.

The documentation states

When the map is resized, the map center is fixed

  • The full-screen control now preserves center.

  • There is no longer any need to trigger the resize event manually.

source: https://developers.google.com/maps/documentation/javascript/new-renderer

google.maps.event.trigger(map, "resize"); doesn't have any effect starting from version 3.32


You've already found the answer I was coming to say. The resize event is very important to get right anytime you change the map container (or possibly its parent). In my case, I was flipping between two tabs (map and driving directions). At first the map would appear correctly in the map tab, but switching to the directions and back to the map caused display funkiness.

If your map is only showing a small tile in one corner (upper left in my case) with the rest blank chances are you need to fire the resize trigger.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜