MultiformeIngegno
MultiformeIngegno

Reputation: 7059

Google Maps API: Map width gets resized onclick but route is still loaded with original width

I have a map loaded via Google Maps API v3. I have a form which onclick performs 2 actions: 1) calls function to calculate the route via google transit, 2) reduces map width.

<form>
    <input type="text" id="start" name="start">
    <input type="button" onclick="reducemap();calcRoute();" value="Go">
</form>

function reducemap() {
document.getElementById("map-canvas").style.width="620px";
}

function calcRoute() {
    var start = document.getElementById('start').value;
      var end = "An Address in Rome";
      var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.TRANSIT
      };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
}

It works like a charm, with the only problem that route isn't centered because it's calculated with the original width (not the reduced one). You can see this live here (so you can take a look at the code: http://goo.gl/wr3qi).

Upvotes: 2

Views: 1425

Answers (1)

Michael Geary
Michael Geary

Reputation: 28870

When you change the size of the DIV that contains the map, you also need to notify the Maps API about this size change. So, assuming you have a map variable with a reference to the map, your reducemap() function should probably be:

function reducemap() {
    document.getElementById("map-canvas").style.width = "620px";
    google.maps.event.trigger( map, "resize" );
}

Upvotes: 2

Related Questions