Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change zoom after directionsService.route?

Tags:

google-maps

My code :

directionsService.route(request, function (response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);

        map.setZoom(2);
    }
});

but the setZoom(2) won't works. Seems that .setDirections is asynch. Can't set zoom after tracing the route?

Tried also with :

google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
    map.setZoom(2);
});

but the map won't zoom...

like image 529
markzzz Avatar asked Feb 20 '23 00:02

markzzz


1 Answers

The DirectionsService does not change the zoom, the DirectionsDisplay (AKA DirectionsRenderer) does.

The DirectionsRenderer has an option preserveViewport, which if included and set to true, will prevent it from changing the zoom (and center) of the map.

If you want to set the the center based on the results of the directionsService, see my answer to this similar question:

google map zoom after directions

If you want the center the DirectionsRenderer would have set, use the bounds of the DirectionsResult.

You can also listen for the directions_changed event, and set the zoom when it fires, not sure if that will work or not.

example from the documentation using the zoom_changed event

like image 126
geocodezip Avatar answered Feb 27 '23 10:02

geocodezip