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

萝らか妹 提交于 2019-12-02 13:00:51

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

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!