Reputation: 19
I am trying to get a distance between two locations with Google API, coding in node.js. I would like to store the value in a variable, how do I do this?
Upvotes: 1
Views: 268
Reputation: 496
If you know their names,You can try the following example which requests the distance matrix data between Washington, DC and New York City, NY, in JSON format
var request = require('request');
request.get('https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Washington,DC&destinations=New+York+City,NY&key=YOUR_API_KEY'
, function (error, response) {
if(error){
//Error handling
}else{
/*
the response will be in a "JSON" format, you can see it in
details by entering the previous URL into your web browser
(be sure to replace YOUR_API_KEY with your actual API key)
*/
}
})
or you can use this module node-googlemaps which wrap the apis.
if you know their longitudes and latitudes, i think there are no npm packages include the needed google libraries needed for that so i suggest you to calculate the distance by Haversine formula by using this npm module Haversine formula and this is a simple example:
var haversine = require('haversine-distance')
var a = { latitude: 37.8136, longitude: 144.9631 }
var b = { latitude: 33.8650, longitude: 151.2094 }
// 714504.18 (in meters)
console.log(haversine(a, b))
Upvotes: 1