Last active
February 23, 2018 18:56
-
-
Save accessomnath/84aa7381668705655d6cad4f9f406111 to your computer and use it in GitHub Desktop.
Road distance distance in two point in google maps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript" | |
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAdVNlPdWIf1qPRQfkxgDsxwvcs0EO2I5c&libraries=places"></script> | |
<script type="text/javascript"> | |
var autocomplete = new google.maps.places.Autocomplete($("#map")[0], {}); | |
var autocompleteSecond = new google.maps.places.Autocomplete($("#map2")[0], {}); | |
var autocompletethird = new google.maps.places.Autocomplete($("#map3")[0], {}); | |
function initialize() { | |
google.maps.event.addListener(autocomplete, 'place_changed', function () { | |
fillInAddress(); | |
}); | |
google.maps.event.addListener(autocompleteSecond, 'place_changed', function () { | |
fillInAddress(); | |
}); | |
google.maps.event.addListener(autocompletethird, 'place_changed', function () { | |
var place = autocompletethird.getPlace(); | |
}); | |
} | |
function fillInAddress() { | |
var placeOne = autocomplete.getPlace(); | |
var placeTwo = autocompleteSecond.getPlace(); | |
var placeone = placeOne.formatted_address; | |
var placetwo = placeTwo.formatted_address; | |
var directionsService = new google.maps.DirectionsService(); | |
var request = { | |
origin: placeone, // a city, full address, landmark etc | |
destination: placetwo, | |
travelMode: google.maps.DirectionsTravelMode.DRIVING | |
}; | |
directionsService.route(request, function (response, status) { | |
if (status == google.maps.DirectionsStatus.OK) { | |
var meter = response.routes[0].legs[0].distance.value; // the distance in metres | |
var km = meter / 1000; // the total distance in kilometres | |
console.log(km); | |
} | |
else { | |
// oops, there's no route between these two locations | |
// every time this happens, a kitten dies | |
// so please, ensure your address is formatted properly | |
} | |
}); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment