Suppose a single page application that consumes rest services is loaded in Singapore and there are two possible locations hosting the REST / edge services that the application consumes, one in New York and one in Singapore. Anyone know of a javascript framework that would allow the app to select the closest data center (In this case it would be Singapore)?
Onload of application get data centers lat lon in http rest call.
Get your current device lat lon position by Cordova geolocation or any other plugin
Use this algorithm to calculate distance in your device itself between all the list of data centers and device current location then shortlist the distance and pick shortest
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;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
Related
I am having trouble starting with this new feature that I have to implement on an application that I am working on. So the application works like this; A user inputs a point on the map by pressing a button and gets a latlng for source. Another modal opens and then they have to do the same for destination. What I want to do is to calculate the distance between two points and show a route on the map. I have been trying to find tutorials on this but have had no luck. Anyone knows how to do this or have any working example repo that I can have a look at it? Would be of great help. Thanks!
Have you seen this:
https://stackoverflow.com/a/27943/52160
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;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
}
im not sure what approach to take next with this, currently I have this below code which calculates the distance in miles between any 2 given locations (using long and lat), however its a straight line, and roads aren't straight... so what I want to do is calculate a distance as google maps would, for example here are some random co-ordinates:
lat1: 53.015036674593500
lat2: -2.244633982337860
long1: 52.363731052413800
long2: -1.307122733526320
and when cast into this code (JavaScript)
function distance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1 / 180
var radlat2 = Math.PI * lat2 / 180
var radlon1 = Math.PI * lon1 / 180
var radlon2 = Math.PI * lon2 / 180
var theta = lon1 - lon2
var radtheta = Math.PI * theta / 180
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180 / Math.PI
dist = dist * 60 * 1.1515
if (unit == "K") { dist = dist * 1.609344 }
if (unit == "N") { dist = dist * 0.8684 }
return dist
}
var dist = distance(lata, longa, latb, longb, unit).toFixed(2);
window.alert(dist + " miles");
the value returned is 59.83 miles or there abouts... where if i was to do this in google maps:
https://www.google.co.uk/maps/dir/1+Creswell+Pl,+Cawston,+Rugby+CV22+7GZ,+UK/1+Ironbridge+Dr,+Newcastle+ST5+6ER,+UK/#52.6863234,-2.0253047,10z/data=!3m1!4b1!4m13!4m12!1m5!1m1!1s0x487747659759ff6f:0x2ae7f451f320ca80!2m2!1d-1.3071227!2d52.3637323!1m5!1m1!1s0x487a67f1ebd6bdaf:0x89c3b0d334683e52!2m2!1d-2.2446339!2d53.0150378
the values range between 77.1 miles and 76.5 miles
The Question
I have the BELOW function PARTLY working to get the travel time and distance, however it randomly returns "UNDEFINED" in the alert box at the bottom, or has this error message
"Object doesn't support this action"
when using the console.log it returns this message:
"google.maps.DistanceMatrixService is not a function"
code:
var siteP = postcodearray.indexOf(screen.sitePostcode);
var StaffP = postcodearray.indexOf(screen.engineerPostcode);
sitelat = latarray[siteP];
sitelong = longarray[siteP];
stafflat = latarray[StaffP];
stafflong = longarray[StaffP];
var site = sitelat + ", " + sitelong;
var staff = stafflat + ", " + stafflong;
var distance;
var duration;
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [staff],
destinations: [site],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
distance = response.rows[0].elements[0].distance.text;
duration = response.rows[0].elements[0].duration.text;
//var dvDistance = document.getElementById("dvDistance");
//dvDistance.innerHTML = "";
//dvDistance.innerHTML += "Distance: " + distance + "<br />";
//dvDistance.innerHTML += "Duration:" + duration;
} else {
alert("Unable to find the distance via road.");
}
});
window.alert(distance); //UNDEFINED
Please can someone point out what I have done/am doing wrong here as im so close to getting the 2 values I need
You can find an example of using the Bing Maps REST services to calculate a route between to locations in JavaScript here: https://msdn.microsoft.com/en-us/library/gg427607.aspx
I recommend adding the routeAttributes parameter and setting it to routeSummariesOnly. This will make the response really small. https://msdn.microsoft.com/en-us/library/ff701717.aspx
Alternatively, if you are using JavaScript and want to load a map, then use the Bing Maps JavaScript control and the directions module: https://msdn.microsoft.com/en-us/library/hh312802.aspx
You can also find an interactive SDK for the Bing Maps control here: https://www.bingmapsportal.com/ISDK/AjaxV7#CreateMap1
You will need a Bing Maps key to access the service, but it doesn't have to be tied to a refer. I recommend signing up for a free Bing Maps key here: https://azure.microsoft.com/en-us/marketplace/partners/bingmaps/mapapis/
Using JavaScript in the browser, how can I determine the distance from my current location to another location for which I have the latitude and longitude?
If your code runs in a browser, you can use the HTML5 geolocation API:
window.navigator.geolocation.getCurrentPosition(function(pos) {
console.log(pos);
var lat = pos.coords.latitude;
var lon = pos.coords.longitude;
})
Once you know the current position and the position of your "target", you can calculate the distance between them in the way documented in this question: Calculate distance between two latitude-longitude points? (Haversine formula).
So the complete script becomes:
function distance(lon1, lat1, lon2, lat2) {
var R = 6371; // Radius of the earth in km
var dLat = (lat2-lat1).toRad(); // Javascript functions in radians
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
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;
}
/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
window.navigator.geolocation.getCurrentPosition(function(pos) {
console.log(pos);
console.log(
distance(pos.coords.longitude, pos.coords.latitude, 42.37, 71.03)
);
});
Apparently I am 6643 meters from the center of Boston, MA right now (that's the hard-coded second location).
See these links for more information:
http://html5demos.com/geo
http://diveintohtml5.info/geolocation.html
Calculate distance between two latitude-longitude points? (Haversine formula)
toRad() Javascript function throwing error
Assume I have 3 locations namely Kallang(A), Paya Lebar(B) and Bedok(C). I try to do a A->B + B->C but the distance always return me A->C. Why is this so ??
kallang to paya lebar(A-B) -> 2.5914199062350742 km
paya lebar to bedok(B-C) -> 4.4403012109180775 km
total (A-B-C) -> 7.03 km
kallang to bedok (A-C) -> 6.88 km
below are my codes:
var R = 6371;
var dLat = toRad(location3.lat()-location2.lat()) + toRad(location2.lat()-location1.lat());
var dLon = toRad(location3.lng()-location2.lng()) + toRad(location2.lng()-location1.lng());
var dLat1 = toRad(location1.lat());
var dLat2 = toRad(location2.lat());
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(dLat1) * Math.cos(dLat1) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
document.getElementById("distance_direct").innerHTML = "<br/><br/><br/>The distance between the five points (in a straight line) is: "+d +" km.";
}
function toRad(deg)
{
return deg * Math.PI/180;
}
Is it something wrong with my adding and subtracting calculation statement ??? Thanks
You can just use the built in computeDistanceBetween method from the geometry library
Yep, the problem is with adding and substracting the same thing. Since toRad() is just a multiplication, it's associative respective to + and - and therefore
var dLat = toRad(location3.lat()-location2.lat())
+ toRad(location2.lat()-location1.lat());
is exactly the same as
var dLat = toRad(location3.lat()-location1.lat());
so you end up calculating the straight distance between the first and last point.
If you are using the Google Maps JavaScript API V3, you can just load the Geometry Library and do this:
var indirect_distance =
google.maps.geometry.spherical.computeDistanceBetween(location1, location2)
+ google.maps.geometry.spherical.computeDistanceBetween(location2, location3);
Is there any way to calculate distance and duration in google maps v3 synchronously? I want to make a function which will take 2 parameter (latLng, latLng) and return the distance (not in straight line but through roads) between them (or the duration).
You don't need Google. You need the Haversine formula:
R = earth’s radius (mean radius = 6,371km)
Δlat = lat2 − lat1
Δlong = long2 − long1
a = sin²(Δlat/2) + cos(lat1) * cos(lat2) * sin²(Δlong/2)
c = 2 * atan2(√a, √(1−a))
d = R * c