Javascript google maps api for distance calculator between two lat long

To calculate the distance between two locations using the Google Maps API in JavaScript, you can use the google.maps.DistanceMatrixService class. Here is an example code snippet that demonstrates how to do this:

javascript

// Set up the Distance Matrix service
var service = new google.maps.DistanceMatrixService();

// Define the two locations
var origin = new google.maps.LatLng(37.7749, -122.4194); // San Francisco
var destination = new google.maps.LatLng(40.7128, -74.0060); // New York

// Define the Distance Matrix request parameters
var request = {
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL // or google.maps.UnitSystem.METRIC
};

// Send the Distance Matrix request
service.getDistanceMatrix(request, function(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
console.log("The distance between San Francisco and New York is " + distance + " and the travel time is " + duration);
} else {
console.log("Error: " + status);
}
});

In this example, the distance is calculated between San Francisco and New York. You can modify the origin and destination variables to use your own latitude and longitude values. The unitSystem parameter can be set to either google.maps.UnitSystem.IMPERIAL or google.maps.UnitSystem.METRIC depending on your preference for miles or kilometers. The response from the Distance Matrix service is returned in the response parameter, and the distance and duration are extracted from the response and printed to the console.

Leave a comment

Your email address will not be published.