JCHASE11
JCHASE11

Reputation: 3941

Recenter Google map after map canvas changes size API

I am using the Google Maps API v.3 to create a google map with directions very similar to this example by google.

The main difference is that on page load, the google map canvas is set to 100%, and when the user requests directions the map is reduced to 70% (to make room for the directions panel)

When the user gets directions, the directions are displayed as if the map canvas was at 100%, not 70%, essentially cutting off part of the directions. I need the map to reorient / recenter when the direction response is displayed.

You can demo this out here: http://j2designpartnership.com/directions/

When the user types in directions, this function is called: calcRoute()

function calcRoute() {

        if (document.getElementById("start").value != "") {
            activeSettings();
        }
        else{
            defaultSettings();
        }

        var start = document.getElementById("start").value;
        var end = document.getElementById("end").value;


        var request = {
            origin:start, 
            destination:end,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };

            //make the request for our directions
            directionsService.route(request, function(response, status) {

                if (status == google.maps.DirectionsStatus.OK) {

                    directionsDisplay.setDirections(response);
                }
            });

            var recenter = new google.maps.LatLng(40.440625,-79.995886);
            map.setCenter(recenter);
    }

The part to pay attention to here is the top conditional that basically changes the width of the map canvas if there is text in the input field.

How do I recenter the map now that the map canvas is smaller?

Upvotes: 0

Views: 1064

Answers (1)

geocodezip
geocodezip

Reputation: 161334

When the map div changes size trigger the resize event on the map as specified in the documentation

resize | None | Developers should trigger this event on the map when the div changes size: google.maps.event.trigger(map, 'resize') .

Upvotes: 1

Related Questions