Get directions to predefined destination from current location (Geolocation)

前端 未结 1 788
梦如初夏
梦如初夏 2021-01-17 02:42

Nog I have following page with directions to the predefined destination: example directions

This is working perfect with following code:

    

        
相关标签:
1条回答
  • 2021-01-17 03:10

    Your current position is declared inside another fuction, so it's basically invisible to every other functions.

       navigator.geolocation.getCurrentPosition(function(position) {
          var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
    
        }, function() {
          handleLocationError(true, markerme);
        });
    

    I'd suggest calculating your position inside initMap and then passing your current position as a parameter to calculateAndDisplayRoute.

    function initMap() {
        ...
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: JSON.parse(zoomtp),
          center: tp
        });
        directionsDisplay.setMap(map);
    
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            calculateAndDisplayRoute(directionsService, directionsDisplay, pos);
    
          }, function() {
            handleLocationError(true, markerme);
           });
        } else {
         // Browser doesn't support Geolocation
         window.alert('Geolocation is not supported');
        }
    
    
     }
    
    function calculateAndDisplayRoute(directionsService, directionsDisplay, pos) {
        var latrest = <?php echo json_encode($latrest);?>;
        var lngrest = <?php echo json_encode($lngrest);?>;
        var rest = {lat: JSON.parse(latrest), lng: JSON.parse(lngrest)};
    
        //var selectedMode = "WALKING";
        directionsService.route({
          origin: pos,  // current position.
          destination: rest,  // restaurant.
          // Note that Javascript allows us to access the constant
          // using square brackets and a string value as its
          // "property."
          travelMode: google.maps.TravelMode.WALKING
        }, function(response, status) {
          if (status == 'OK') {
            directionsDisplay.setDirections(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
    }
    
    0 讨论(0)
提交回复
热议问题