简体   繁体   中英

google map auto update location but not user set zoom

I am auto updating google maps every x seconds in jquery/javascript.

When location is changed map changes the zoom level (expected).

But i want to achieve this:

If user has manually changed zoom level, then the map should keep/persist the user-set zoom level.

Code looks similar to this:

  function calcRoute(user) {
     if(user)
     {
        start = document.getElementById("start_location").value;
     }
     end = document.getElementById("end_location").value;
     var request = {
        origin:start, 
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.WALKING
    };

    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
        $('#txt_dur').text(response.routes[0].legs[0].duration.text);
        $('#txt_dist').text(response.routes[0].legs[0].distance.text);      

      }
    });
    //if(userZoom==true)
    //    map.setZoom(current_zoom);

  }

      function autoUpdate() {
         navigator.geolocation.getCurrentPosition(function(position) {
         var newPoint = new google.maps.LatLng(position.coords.latitude,
                                          position.coords.longitude);

         start = newPoint.toString();
         calcRoute(false);
      });

    setTimeout(autoUpdate, 5000);
   }

    autoUpdate();

I will prefer standard google map events like zoom_changed instead of creating custom events for user zoom.

Any directions on this subject?

Try like this:

if (status == google.maps.DirectionsStatus.OK) {
    var tmpZoom = map.getZoom();   //added line
    directionsDisplay.setDirections(response);
    map.setZoom( tmpZoom );        //added line

    $('#txt_dur').text(response.routes[0].legs[0].duration.text);
    $('#txt_dist').text(response.routes[0].legs[0].distance.text);
}

where map is your google.maps.Map object.

PS : For preventing both center and zoom from being changed by setDirections method, you can specify preserveViewport=true of google.maps.DirectionsRendererOptions object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM