How do I get multiple elevations using google api? - javascript

I'm trying to get multiple elevations using Google API, but it usually it does not work.
Here is my code:
var axios = require('axios');
var fs = require('fs');
const util = require('util');
var config = {
method: 'get',
url: 'https://maps.googleapis.com/maps/api/elevation/json?key=<MY_API_KEY>&locations=',
headers: { }
};
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getElevationsWithAPI(config) {
console.log('in getElevationsWithAPI()');
console.log(config);
console.log('method = ' + config.method);
let queryResult = [];
let res = await axios(config); // comment 1
console.log('status = ' + res.status);
console.log('location = ' + res.data.results[0].location.lat + ', ' + res.data.results[0].location.lng);
console.log('elevation = ' + res.data.results[0].elevation);
let results = res.data.results;
for (i = 0; i < results.length; i++) {
let entry = results[i];
queryResult.push({[entry.location.lat + ',' + entry.location.lng]: entry.elevation});
}
const json = JSON.stringify(queryResult);
//console.log('json = ' + json);
return queryResult;
}
function getDistance(lat1, lng1, lat2, lng2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lng2-lng1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2) ;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180);
}
async function getElevationsExported(fileName, lat1, lng1, lat2, lng2) {
console.log('in getElevationsExported(), fileName = ' + fileName);
console.log(`lat1 = ${lat1}, lat2 = ${lat2}, lng1 = ${lng1}, lng2 = ${lng2}`);
console.log('lat distance: ' + getDistance(lat1, lng1, lat2, lng1));
console.log('lng distance: ' + getDistance(lat1, lng1, lat1, lng2));
console.log('point distance: ' + getDistance(lat1, lng1, lat2, lng2));
var url = config.url;
var res = [];
let counter = 0;
console.log('before for');
try {
// Calculate number of rows
for (i = lat1; i <= lat2 + 0.00026; i += 0.00026) {
counter++;
}
console.log('counter = ' + counter);
// Send the location data to google elevation API
let k = 1;
for (i = lat1; i <= lat2 + 0.00026; i += 0.00026) {
console.log(`${k++}: i = ${i}`);
var locations = '';
let jArr = [];
for (j = lng1; j <= lng2; j += 0.00032) {
jArr.push(j);
locations += i.toFixed(5) + '%2C' + j.toFixed(5) + '%7C';
}
locations = locations.slice(0, -3); // remove the last %7C character
config.url = url + locations;
//console.log('config.url = ' + config.url);
try {
await sleep(10); // comment 2
var elevationRes = getElevationsWithAPI(config);
elevationRes.then(function(result) {
//console.log(result);
counter--;
res.push(...result);
console.log('after --, counter = ' + counter);
if (counter === 0) { // comment 3
console.log('finished getting data');
// Write the new elevations file
fs.writeFile(consts.ElevationDirFullPath + fileName, JSON.stringify(res), (err) => {
if (err) {
console.log(err);
throw err;
}
console.log('The file has been saved');
});
}
});
} catch(error) {
console.log(error);
throw error;
}
}
console.log('exited for loop');
} catch (error2) {
console.log('error2 = ' + error2);
}
}
module.exports.getDistance = getDistance;
module.exports.getElevationsExported = getElevationsExported;
The problem is when I call Google API through axios (see comment 1). Sometimes it succeeds and sometimes it fails. I also tried to add timeout between calls (see comment 2), but then not all calls to getElevationsWithAPI() are called.
Also I usually don't reach the end condition (comment 3).
How can I fix all these problems?

Related

Uncaught TypeError: Cannot read property '0' of undefined - OpenWeatherMap API

I keep getting this Uncaught TypeError: Cannot read property '0' of undefined
The code works perfectly fine with no errors in the console or anything, but everything now and then this error pops up then just disappears. Does anyone know why?
var temp, loc, icon, hum, wind, dir;
var APPID = "56a4fe4f1240df2a9fe267b687a5d191";
function update (weather) {
temp.innerHTML += weather.temp;
loc.innerHTML += weather.loc;
hum.innerHTML += weather.hum;
wind.innerHTML += weather.wind;
dir.innerHTML += weather.dir;
sUp.innerHTML += weather.sUp;
sDown.innerHTML += weather.sDown
icon.src = "//openweathermap.org/img/w/" + weather.icon + ".png";
}
window.onload = function () {
temp = document.getElementById ("t");
loc = document.getElementById ("l");
icon = document.getElementById ("i");
hum = document.getElementById ("h");
wind = document.getElementById ("w");
dir = document.getElementById ("d");
sUp = document.getElementById ("sU");
sDown = document.getElementById ("sD");
if (navigator.geolocation) {
var showPos = function (pos) {
updateLoc (pos.coords.latitude, pos.coords.longitude);
}
navigator.geolocation.getCurrentPosition (showPos);
} else {
var zip = window.prompt("Your location could not be found, please enter your post/zip code.");
updateByZip(zip);
}
}
function updateLoc (lat, long) {
var url = "http://api.openweathermap.org/data/2.5/weather?" +
"lat=" + lat +
"&lon=" + long +
"&APPID=" + APPID;
sendRequest (url);
}
function updateByZip(zip){
var url = "http://api.openweathermap.org/data/2.5/weather?" +
"zip=" + zip +
"&APPID=" + APPID;
sendRequest(url);
}
function sendRequest (url) {
var xmlhttp = new XMLHttpRequest ();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse (xmlhttp.responseText);
var weather = {};
weather.icon = data.weather[0].icon;
weather.dir = direction (data.wind.deg);
weather.wind = mph (data.wind.speed) + "mph";
weather.temp = K2C (data.main.temp) + "°C";
weather.loc = data.name;
weather.hum = data.main.humidity + "%";
weather.sUp = formatDate (data.sys.sunrise);
weather.sDown = formatDate (data.sys.sunset);
update (weather);
}
};
xmlhttp.open ("GET", url, true);
xmlhttp.send ();
}
function K2F (k) {
return Math.round(k * (9 / 5) - 459.67);
}
function K2C (k) {
return Math.round (k - 273.15);
}
function mph (ms) {
return Math.round (ms / 0.44704);
}
function kmph (ms) {
return Math.round (ms * 3.6);
}
function formatDate (t) {
var date = new Date (t * 1000);
var h = date.getHours ();
var m = "0" + date.getMinutes ();
var s = "0" + date.getSeconds ();
return h + ":" + m.substr(-2) + ":" + s.substr(-2);
}
function direction (deg) {
var range = 360 / 16;
var low = 360 - (range / 2);
var high = (low + range) % 360;
var angles = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
for (var i in angles) {
if (deg >= low && deg < high) {
return angles[i]
}
low = (low + range) % 360;
high = (high + range) % 360;
}
return "N";
}

Phonegap geolocation distance between coordinates

I tried to calculate the distance between two coordinates in javascript.
More specifically the distance between one set of static coordinates and my current position taken from the geolocation cordova plugin.
Here's my code:
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
var onSuccess = function(position) {
document.getElementById("content").innerHTML = 'Success, attempting calculation...';
var lla = position.coords.latitude;
var llo = position.coords.longitude;
document.getElementById("content").innerHTML =
'GPS Position: ' + calcTheDistance(lla, llo).d + 'Metres';
};
var onError = function(error) {
document.getElementById("content").innerHTML =
'code: ' + error.code + '\n' +
'message: ' + error.message + '\n';
};
function refrGps() {
document.getElementById("content").innerHTML = 'Loading...';
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
function calcTheDistance(lati1, long1) {
var r = 6371000; //Meters
var joschLat = 50.1109221;
var joschLon = 8.6821267;
var la1 = lati1;
var la2 = joschLat;
var lat1 = lati1.toRadians();
var lat2 = joschLat.toRadians();
var lo1 = long1;
var lo2 = joschLon;
var la2minla1 = (la2-la1).toRadians();
var lo2minlo1 = (lo2-lo1).toRadians();
var cal = Math.sin(la2minla1 / 2) * Math.sin(la2minla1 / 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(lo2minlo1/2) * Math.sin(lo2minlo1/2);
var c = 2* Math.atan2(Math.sqrt(cal), Math.sqrt(1-cal));
d = r * c;
};
I tried to rewrite it several times with no luck.
For the calculation I referred to this: http://www.movable-type.co.uk/scripts/latlong.html
The page you referenced contains a library of functions already implemented in Javascript. If you include these in your app, the calculation becomes trivial:
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
var onSuccess = function(position) {
document.getElementById("content").innerHTML = 'Success, attempting calculation...';
var sourceLl = new LatLon(position.coords.latitude, position.coords.longitude);
document.getElementById("content").innerHTML =
'GPS Position: ' + calcTheDistance(sourceLl) + 'Metres';
};
var onError = function(error) {
document.getElementById("content").innerHTML =
'code: ' + error.code + '\n' +
'message: ' + error.message + '\n';
};
function refrGps() {
document.getElementById("content").innerHTML = 'Loading...';
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
function calcTheDistance(sourceLl) {
var joschLat = 50.1109221;
var joschLon = 8.6821267;
var joschLl = new LatLon(joschLat, joschLon);
return joschLl.distanceTo(sourceLl);
};
So I figured it out after reading #DaveAlden 's Answer, thanks by the way!
toRadians(); is not a standard Javascript function, so after I added this and rewrote my code a bit, it worked fine.
Here's the working code
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
var onSuccess = function(position) {
document.getElementById("content").innerHTML = 'Success, attempting calculation...';
var lla = position.coords.latitude;
var llo = position.coords.longitude;
var dst = 'Distance: ' + calcTheDistance(lla, llo) + ' Metres';
document.getElementById("content").innerHTML = dst;
};
var onError = function(error) {
document.getElementById("content").innerHTML =
'code: ' + error.code + '\n' +
'message: ' + error.message + '\n';
};
function refrGps() {
document.getElementById("content").innerHTML = 'Loading...';
navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
function toRadians(num) {
return num * Math.PI / 180;
};
function calcTheDistance(lati1, long1) {
var r = 6371000; //metres
var joschLat = 50.1109221;
var joschLon = 8.6821267;
var la1 = lati1;
var la2 = joschLat;
var lat1 = toRadians(lati1);
var lat2 = toRadians(joschLat);
var lo1 = long1;
var lo2 = joschLon;
var la2minla1 = toRadians(la2-la1);
var lo2minlo1 = toRadians(lo2-lo1);
var cal = Math.sin(la2minla1 / 2) * Math.sin(la2minla1 / 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(lo2minlo1/2) * Math.sin(lo2minlo1/2);
var c = 2* Math.atan2(Math.sqrt(cal), Math.sqrt(1-cal));
var d = r * c;
return Math.round(d);
};

Stuck with migrating to youtube api v3

so im trying to make a script for youtube in my psp and when i try to play it crashes.
var YouTube = new Object();
YouTube.rev = 4;
YouTube.SearchDesc = "YouTube by NT and JCRV";
YouTube.Name = "YouTube";
YouTube.Search = function(keyword, page) {
var result = new Object();
result.bypage = 20;
result.start = (page - 1) * result.bypage + 1;
var sortBy = "relevance";
var catSpecified = false;
if (keyword.charAt(0) == '$')
{
var keywordBu = keyword;
var kpos = keyword.indexOf(" ");
var category = keyword.substring(1, kpos);
keyword = keyword.substring(kpos + 1);
catSpecified = true;
}
if (keyword.charAt(0) == '#')
{
sortBy = "published";
}
if (catSpecified == false)
{
c = GetContents('https://www.googleapis.com/youtube/v3/search?q=' + escape(keyword) + '&maxResults=' + result.bypage + '&order=' + sortBy + '&part=snippet&key=AIzaSyD6Bdt4uJP0ewhNtgagGbSszfrYqcx6ydU');
}
else
{
c = GetContents('https://www.googleapis.com/youtube/v3/search?q=' + escape(keyword) + '&maxResults=' + result.bypage + '&order=' + sortBy + '&part=snippet&key=AIzaSyD6Bdt4uJP0ewhNtgagGbSszfrYqcx6ydU');
}
result.total = ext("<openSearch:totalResults>");
result.VideoInfo = new Array();
v = {attr: 2};
v.id = 0;
v.Title = "YouTube Search Help";
v.Description = "#query = search by upload date\n$category query = search in a category";
v.URL = '';
p = 0;
result.VideoInfo.push(v);
while (p = c.indexOf("<entry", p) + 1) {
v = {attr: 2};//neither IDA|npp find this string ...0=RD 1= 2=SRD 3=S
v.id = ext("https://www.googleapis.com/youtube/v3/videos?id=", "&key=AIzaSyD6Bdt4uJP0ewhNtgagGbSszfrYqcx6ydU&part=snippet,contentDetails,statistics,status&forMine=true&type=video");
v.Title = ext("<title type='text'>");
v.Description = ext("content type='text'>") + '\nUploader:' + ext("<name>");
v.CommentCount = ext("statistics.commentCount='") * 1;
v.Tags = ext("keywords>").replace(/,/g, "");
v.LengthSeconds = ext("contentDetails.duration='") * 1;
v.RatingAvg = ext("contentDetails.contentRating='") * 1;
v.RatingCount = ext("statistics.likeCount='") * 1;
v.MylistCount = ext("statistics.favoriteCount='") * 1;
v.ViewCount = ext("statistics.viewCount='") * 1;
v.ThumbnailURL = 'http://i.ytimg.com/vi/' + v.id + '/default.jpg';
v.SaveFilename = v.id + ".flv";
v.URL = 'YouTube.play("' + v.id + '")';
result.VideoInfo.push(v);
}
result.end = result.start - 1 + result.VideoInfo.length;
return result;
}
YouTube.play = function(id) {
var pos;
c = GetContents("http://www.youtube.com/get_video_info?html5=1&video_id=" + id);
//PSPTube.log("\n" + c + "\n");
pos = c.indexOf("url_encoded_fmt_stream_map");
if (pos == -1) {
alert("Can not be played");
return "";
}
c = ext('url_encoded_fmt_stream_map', "&");
p = 0;
c = unescape(c);
var url = c.match(/url=(.+?itag%3D5.*?)[&,]/);
//PSPTube.log("\n" + url + "\n");
url = url[1];
//PSPTube.log("\n" + url + "\n");
pos = url.lastIndexOf("http");
url = url.substr(pos);
url = unescape(url);
//PSPTube.log("\n" + url + "\n");
return url;
}
SiteList.push(YouTube);

Nodejs Javascript TypedArray to Buffer to String and Back Again

I'm trying to implement a serialization and deserialization of a repeating set of floats, using TypedArray to string (for saving across wire/disk), But it's not making it round trip
I got it working by using the ArrayBuffer to Buffer methods provided on the linked issue, the issue is I think I was treating them as arbitrary Typed Arrays rather than the native Uint8Array that I guess Buffers use. Here's the working version.
var recordsPerWrite = 1;
var ab = new ArrayBuffer(8 + 8 + 8 * recordsPerWrite);
var f64ry = new Float64Array(ab);
var records_added = 1;
var i1 = records_added * 0;
var i2 = records_added * 1;
var i3 = records_added * 2;
////////////////////////////
var timestamp = 1.1;
var price = 2.2;
var amount = 3.3;
f64ry[i1] = timestamp;
f64ry[i2] = price;
f64ry[i3] = amount;
console.log(f64ry[i1], f64ry[i2],f64ry[i3]);
var buffer = toBuffer(ab);
var st = buffer.toString('base64');
console.log("ST '" + st + "'");
var buffer2 = new Buffer(st, 'base64');
var ab2 = toArrayBuffer(buffer2);
var f64ry2 = new Float64Array(ab2);
function toArrayBuffer(buffer) {
var ab = new ArrayBuffer(buffer.length);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
view[i] = buffer[i];
}
return ab;
}
function toBuffer(ab) {
var buffer = new Buffer(ab.byteLength);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
return buffer;
}
timestamp2 = f64ry2[i1];
price2 = f64ry2[i2];
amount2 = f64ry2[i3];
console.log("IN " + timestamp, price, amount);
console.log("OUT " + timestamp2, price2, amount2);
OUTPUT
SOURCE: 1.1 2.2 3.3
CLONE: undefined undefined undefined //expected 1.1 2.2 3.3
I am using the approach linked here: Convert a binary NodeJS Buffer to JavaScript ArrayBuffer
var ab = new ArrayBuffer(8 + 8 + 8);
var f64ry = new Float64Array(ab);
var records_added = 1;
var i1 = records_added * 0;
var i2 = records_added * 1;
var i3 = records_added * 2;
////////////////////////////
var timestamp = 1.1;
var price = 2.2;
var amount = 3.3;
f64ry[i1] = timestamp;
f64ry[i2] = price;
f64ry[i3] = amount;
console.log(f64ry[i1], f64ry[i2],f64ry[i3]); //shows correctly
var buffer = new Buffer(ab.byteLength);
for (var i = 0; i < f64ry.length; ++i) {
// console.log(i + " " +f64ry[i]);
buffer[i] = f64ry[i];
}
console.log("buffer '" + buffer + "'");
var st = buffer.toString('hex');
console.log("ST '" + st + "'");
//var ab = buffer.toArrayBuffer(); //doesn't work in Node v.10
var buffer2 = new Buffer(st, 'hex');
console.log("buffer2 '" + buffer2 + "'");
var ab2 = new ArrayBuffer(buffer2.byteLength);
var f64ry2 = new Float64Array(ab2);
for (var i = 0; i < buffer2.length; ++i) {
console.log(i + " " +buffer2[i]);
f64ry2[i] = buffer2[i];
}
}
timestamp2 = f64ry2[i1];
price2 = f64ry2[i2];
amount2 = f64ry2[i3];
console.log(timestamp, price, amount);
console.log(timestamp2, price2, amount2);
Similarly this alternate approach didn't work either:
OUTPUT
>1.1 2.2 3.3
>buffer ''
>ST '010203'
>buffer2 ''
>1.1 2.2 3.3
>undefined undefined undefined
CODE
var f64ry = new Float64Array(3);
var records_added = 1;
var i1 = records_added * 0;
var i2 = records_added * 1;
var i3 = records_added * 2;
////////////////////////////
var timestamp = 1.1;
var price = 2.2;
var amount = 3.3;
var ary = [timestamp,price,amount];
f64ry.set(ary,0);
console.log(f64ry[i1], f64ry[i2],f64ry[i3]);
var buffer = new Buffer(f64ry);
console.log("buffer '" + buffer + "'");
var st = buffer.toString('hex');
console.log("ST '" + st + "'");
//var ab = buffer.toArrayBuffer();
var buffer2 = new Buffer(st, 'hex');
console.log("buffer2 '" + buffer2 + "'");
var ab2 = new ArrayBuffer(buffer2);
var f64ry2 = new Float64Array(ab2);
timestamp2 = f64ry2[i1];
price2 = f64ry2[i2];
amount2 = f64ry2[i3];
console.log(timestamp, price, amount);
console.log(timestamp2, price2, amount2);

Google maps api v2 to v3

I've been trying to convert a v2 to v3 map application that calculates the distance between and address entered and a stored lat/Lon. Not having any luck with getting this up and running. Would really appreciate some help.
<script type="text/javascript" src="js/addHTMLControls2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#order").validate();
addInput();
});
</script>
<script type="text/javascript">
var geocoder, location1, location2;
function initialize() {
geocoder = new google.maps.Geocoder();
}
function showLocation() {
document.getElementById('address').value= document.getElementById('address2').value;
/*coordinate system*/
geocoder.geocode(document.forms[0].address1.value,
function (response) {
if (!response || response.Status.code != 200)
{alert("Sorry, we were unable to geocode the first address");}
else
{location1 =
{lat: response.Placemark[0].Point.coordinates[1],
lon: response.Placemark[0].Point.coordinates[0],
address: response.Placemark[0].address
};
geocoder.geocode(document.forms[0].address2.value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the second address");
}
else
{
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
calculateDistance();
}
});
}
});
}
function calculateDistance()
{
try
{
var map;
var directionsPanel;
var directions;
var glatlng1 = new google.maps.LatLng(location1.lat, location1.lon);
var glatlng2 = new google.maps.LatLng(location2.lat, location2.lon);
var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
var kmdistance = (miledistance * 1.609344).toFixed(1);
map = new google.maps.Map(document.getElementById("map_canvas"));
map.setCenter(new google.maps.LatLng(location1.lat, location1.lon), 15);
directionsPanel = document.getElementById("route");
directions = new GDirections(map, directionsPanel);
document.getElementById('route').innerHTML='';
document.getElementById('map_canvas').innerHTML='';
/* location1.address+ */
//alert(document.getElementById('hdnLat').value);
document.getElementById('distance').value = directions.load("from:"+ document.getElementById('hdnLat').value +"," + document.getElementById('hdnLan').value + " to: "+location2.address, {travelMode:G_TRAVEL_MODE_DRIVING});
/* document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)';*/
setTimeout('adjustdistance(document.getElementById("route").innerHTML)', 8000);
;
document.getElementById('distance').value= 'calculating...';
}
catch (error)
{
alert(error);
}
}
function adjustdistance(htmlcode)
{
var ht1;
ht1 = htmlcode;
var tyu;
tyu= parseReturnedXML(ht1,'$Route.summaryHtml','table jstcache');
document.getElementById('distance').value=tyu;
}
function parseReturnedXML(strToParse, strStart, strFinish)
{
var str;
str=strToParse;
var str1;
var str2;
str = str.replace(strStart,'~');
str = str.replace(strFinish,'~');
str=str.replace(/(<([^>]+)>)/ig,"");
str = str.replace(',','');
str = str.replace(' ','');
str1= str.indexOf('km (');
str2=" km(s)";
if(str1=='-1')
{
str1=str.indexOf('mi (');
str2=" miles";
}
var str4;
var str5;
str4 = parseInt(str1) - 8;
str5 = parseInt(str1) + 2;
str = str.substring(str4,str5);
str = str.replace(/[a-zA-Z]/g,"");
str = str.replace(/^\s+/,"");
str = str+str2;
return str;
}
</script>
I've updated the various v3 changes but its simply not returning a distance for me.
Thanks
Alan
Please refer the link. http://jsfiddle.net/xJ26V/1/
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}

Categories

Resources