Getting current location in google map and pass it

2019-03-06 18:16发布

问题:

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

      <script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var bne = new google.maps.LatLng(-27.572832, 153.065247);
  var mapOptions = {
    zoom:7,
    center: bne
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay.setMap(map);
}


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);
        }
      });
    }, 
    function (err) {
      alert('ERROR(' + err.code + '): ' + err.message);
    });
  }

google.maps.event.addDomListener(window, 'load', initialize);

    </script>

It seems that navigator.geolocation.getCurrentPosition() doesn't work for me, is there other ways to retrieve current location and pass it to start variable?

回答1:

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



回答2:

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.