I tried to look for exactly what I mentioned in the question, but I couldn't find such code example which can find/generate the directions from current location to specified destination using only latitude and longitude (of both entities) as core parameters.
I don't have any other parameter of any entity(either source or destination) that could assist in generating directions.
I have done this code so far and also previously:
<script>
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=[API_Key]&callback=initMap">
</script>
But this code requires the destination and source location's name like "st louis, mo" or "oklahoma city, ok", and I have only latitude and longitude of current location and destination.
Could anyone guide on this ?
DirectionsRequest take as parameters in
origin
anddestination
3 formats:LatLng:
var myLatLng = new google.maps.LatLng({lat: -34, lng: 151});
LatLngLiteral:
{lat: -34, lng: 151}
Place generally as a query "oklahoma city" but other formats can be accepted.
You should comply to this formats and it will work. I recommend
LatLng
format in your case.