Getting current location in google map and pass it to a variable in javascript

前端 未结 2 2063
借酒劲吻你
借酒劲吻你 2021-01-29 10:17

I want to display a direction in google map from current location to a known location. my code is shown below:

      

        
相关标签:
2条回答
  • 2021-01-29 10:37

    There could be 3 reasons:

    1. Your browser doesn't support geolocation.
    2. You have disabled geolocation tracking. In google chrome you can enable it looking in options, searching location in your settings.
    3. If you are working on a HTML file on your pc directly as file:/// geolocation is disabled for security reasons.
    0 讨论(0)
  • 2021-01-29 10:45

    Per the documentation, the getCurrentPosition function passes a Position object to its callback function (it is asynchronous so can't return anything), which is not a google.maps.LatLng object (but contains the information required to create one).

    function calcRoute() {
      navigator.geolocation.getCurrentPosition(function(pos) {
        var start = new google.maps.LatLng(pos.coords.latitiude,
                                           pos.coords.longitude);
    
        var end = 'sunnybank,brisbane';
        var request = {
          origin:start,
          destination:end,
          travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
          } else alert("Directions request failed: "+status);
        });
      }, function(err) {
        alert('ERROR(' + err.code + '): ' + err.message);
      });
    }
    

    proof of concept fiddle

    0 讨论(0)
提交回复
热议问题