I have the following function, which checks if the browser supports geolocation, and then it gets the geographic location of users and centers it on the map.
What do I need to add so that I can tell users the direction to a fixed location (this will not change) from the users geolocation?
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var coords = new google.maps.LatLng(latitude, longitude); var directionsDisplay; var directionsService = new google.maps.DirectionsService(); var mapOptions = { zoom: 15, center: coords, mapTypeControl: true, navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL }, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions); var marker = new google.maps.Marker( { position: coords, map: map, }); }); } else { alert("Geolocation API is not supported in your browser.");
I added this function to my code:
function calcRoute() { var start = position; var end = "London"; var request = { origin: start, destination: end, travelMode: google.maps.TravelMode.DRIVING }; directionsService.route(request, function (result, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(result); } }); }
HTML: <div id="mapContainer" onload="calcRoute()"></div>
But it still does not work.
source share