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?
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).
proof of concept fiddle
There could be 3 reasons: