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 = "directions";
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
Please go to your map and drag and drop your map to the position you wish. You can also zoom in your map a little bit with mouse wheel or zoom cotrols on the bottom right corner of the map. Please remember to save your map after any changes. Hope that helps.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With