Geolocation find closest coordinate match - javascript

I'm trying to create a Javascript function that can find the closest coordinate match in an array of coordinates.
My coordinates: 33.9321, 18.8602
These coordinates will vary, but the 4 locations listed below will stay the same.
Location1: 33.9143, 18.5701
Location2: 26.2041, 28.0473
Location3: 25.7479, 28.2293
Location4: 29.8587, 31.0218

try to run my code to see if it helps you.
I have used var home as your stargint point if browser didn't work for you.
Also I have saved all locations in var points so you can change that if you need.
Then I just look over each point and it will output in the console what is the distance to ref point. In your case it's the first point
var home = [ '33.9321', '18.8602' ];
var points = [
[ '33.9143', '18.5701' ],
[ '26.2041', '28.0473' ],
[ '25.7479', '28.2293' ],
[ '29.8587', '31.0218' ]
];
// loop over each point and output distance!
for( var i = 0; i < points.length; i++){
var diff = twoPointsDiff(home[0],home[1],points[i][0],points[i][1]);
console.log( 'distance from point' + (i+1) + ': ' + diff );
}
// helper fn to calc distance
function twoPointsDiff(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;
}
// helper fn to convert deg to radians
function deg2rad(deg) {
return deg * (Math.PI/180)
}

Related

Distance calculation gives strange output javascript

I need to calculate the distance between two latitude and longitude points. I found this javascript code which I suppose I want.
Here comes the problem. I add the two positions lat and lng values in, and sometimes it just gives random output. What happens is two points literally next to other are sometimes like 8000 meters away, but two other much furthest points return only 1500 meters for example.
function degreesToRadians(degrees) {
return degrees * Math.PI / 180;
}
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)
}
const distanceR = getDistanceFromLatLonInKm(userLat, userLng, solLat, solLng)
Lat: 68.00757101804007, lng: -49.306640625
to
lat: 73.26312194058698 lng: -23.535461425781254
is 1143 kilometres, but these two points are next to each other.
lat: 66.75724984139227, lng: -16.259765625000004
to
lat: 71.99597405683693 lng:-42.31933593750001
is 1161 metres and the points are much farther then the previus one.
Here I think it calculates fine, unlike the two previous lat and lng points.
I've tested the examples you provided and did a few on my own and I believe your implementation is working fine. I did however get different results using your examples and code.
The first example returns approx. 1102km, which seems close to the distance using a visualizer.
The second example returns 1161 kilometres which visualized again seems about right.
Please note: the images in the links were constructed using gpsvisualizer.com which uses a Vincenty formula to calculate distance, hence the slight variation in distance numbers.
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)
}
const e1 = {
lat1: 68.00757101804007,
lon1: -49.306640625,
lat2: 73.26312194058698,
lon2: -23.535461425781254
}
const e2 = {
lat1: 66.75724984139227,
lon1: -16.259765625000004,
lat2: 71.99597405683693,
lon2: -42.31933593750001
}
const dist1 = getDistanceFromLatLonInKm(e1.lat1, e1.lon1, e1.lat2, e1.lon2);
const dist2 = getDistanceFromLatLonInKm(e2.lat1, e2.lon1, e2.lat2, e2.lon2);
console.log(`Example 1 distance: ${dist1}km. Example 2 distance: ${dist2}km`);
I can not reproduce the issue you are having so I believe your error lies in your visualization of coordinates.

sort locations through ajax

I have a JSON object of latitude and longitude locations. I want to list them in the order they are closest to my current lat and long. Is there a way to query using AJAX to get an array of locations in the order of their proximity to my current location. If not, what the best approach I can use.
You can enumerate yours array of coordinates with this function (from this answer):
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)
}
Or you can divide yours coordinates array per sector like:
if lat1 is greater than 70.000 and lesser than 75.000 then this is sector A and so on.
Finally, when you have these sectors you can search in specific one to avoid long calculations.

get all the users within X KM range from a user

I have an array of users and their gps coordinates.
what formula can I use to get all the users that are within X KM range
from a user?
I need to avoid heavy calculations.
I was thinking about sorting the array, but I realized that it isn't a good idea, because I would have to set a sorted array for each user.
Use the Haversine formula to find the users that are within a specified distance from a specified point:
function getNearbyUsers(lat, lng, distanceInKm, users) {
var R = 6373;
var latRad = lat * Math.PI/180;
var lngRad = lng * Math.PI/180;
var returnUsers = [];
for (var i = 0; i < users.length; i++) {
var lat2Rad = users[i].lat * Math.PI/180;
var lng2Rad = users[i].lng * Math.PI/180;
var dlat = lat2Rad - latRad;
var dlng = lng2Rad - lngRad;
var a = Math.pow(Math.sin(dlat/2),2) + Math.cos(latRad) * Math.cos(lat2Rad) * Math.pow(Math.sin(dlng/2),2);
var c = 2 * Math.atan2(Math.sqrt(a),Math.sqrt(1-a)); // great circle distance in radians
var d = c * R; // Distance from user in km
if (d < distanceInKm) returnUsers.push(users[i]);
}
return returnUsers;
}

Google Maps Two Circles Intersection Points

Is there an easy way to get the lat/lng of the intersection points (if available) of two circles in Google Maps API V3? Or should I go with the hard way?
EDIT : In my problem, circles always have the same radius, in case that makes the solution easier.
Yes, for equal circles rather simple solution could be elaborated:
Let's first circle center is A point, second circle center is F, midpoint is C, and intersection points are B,D. ABC is right-angle spherical triangle with right angle C.
We want to find angle A - this is deviation angle from A-F direction. Spherical trigonometry (Napier's rules for right spherical triangles) gives us formula:
cos(A)= tg(AC) * ctg(AB)
where one symbol denote spherical angle, double symbols denote great circle arcs' angles (AB, AC). We can see that AB = circle radius (in radians, of course), AC = half-distance between A and F on the great circle arc.
To find AC (and other values) - I'll use code from this excellent page
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
and our
AC = c/2
If circle radius Rd is given is kilometers, then
AB = Rd / R = Rd / 6371
Now we can find angle
A = arccos(tg(AC) * ctg(AB))
Starting bearing (AF direction):
var y = Math.sin(dLon) * Math.cos(lat2);
var x = Math.cos(lat1)*Math.sin(lat2) -
Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
var brng = Math.atan2(y, x);
Intersection points' bearings:
B_bearing = brng - A
D_bearing = brng + A
Intersection points' coordinates:
var latB = Math.asin( Math.sin(lat1)*Math.cos(Rd/R) +
Math.cos(lat1)*Math.sin(Rd/R)*Math.cos(B_bearing) );
var lonB = lon1.toRad() + Math.atan2(Math.sin(B_bearing)*Math.sin(Rd/R)*Math.cos(lat1),
Math.cos(Rd/R)-Math.sin(lat1)*Math.sin(lat2));
and the same for D_bearing
latB, lonB are in radians
The computation the "hard" way can be simplified for the case r1 = r2 =: r. We still first have to convert the circle centers P1,P2 from (lat,lng) to Cartesian coordinates (x,y,z).
var DEG2RAD = Math.PI/180;
function LatLng2Cartesian(lat_deg,lng_deg)
{
var lat_rad = lat_deg*DEG2RAD;
var lng_rad = lng_deg*DEG2RAD;
var cos_lat = Math.cos(lat_rad);
return {x: Math.cos(lng_rad)*cos_lat,
y: Math.sin(lng_rad)*cos_lat,
z: Math.sin(lat_rad)};
}
var P1 = LatLng2Cartesian(lat1, lng1);
var P2 = LatLng2Cartesian(lat2, lng2);
But the intersection line of the planes holding the circles can be computed more easily. Let d be the distance of the actual circle center (in the plane) to the corresponding point P1 or P2 on the surface. A simple derivation shows (with R the earth's radius):
var R = 6371; // earth radius in km
var r = 100; // the direct distance (in km) of the given points to the intersections points
// if the value rs for the distance along the surface is known, it has to be converted:
// var r = 2*R*Math.sin(rs/(2*R*Math.PI));
var d = r*r/(2*R);
Now let S1 and S2 be the intersections points and S their mid-point. With s = |OS| and t = |SS1| = |SS2| (where O = (0,0,0) is the earth's center) we get from simple derivations:
var a = Math.acos(P1.x*P2.x + P1.y*P2.y + P1.z*P2.z); // the angle P1OP2
var s = (R-d)/Math.cos(a/2);
var t = Math.sqrt(R*R - s*s);
Now since r1 = r2 the points S, S1, S2 are in the mid-plane between P1 and P2. For v_s = OS we get:
function vecLen(v)
{ return Math.sqrt(v.x*v.x + v.y*v.y + v.z*v.z); }
function vecScale(scale,v)
{ return {x: scale*v.x, y: scale*v.y, z: scale*v.z}; }
var v = {x: P1.x+P2.x, y: P1.y+P2.y, z:P1.z+P2.z}; // P1+P2 is in the middle of OP1 and OP2
var S = vecScale(s/vecLen(v), v);
function crossProd(v1,v2)
{
return {x: v1.y*v2.z - v1.z*v2.y,
y: v1.z*v2.x - v1.x*v2.z,
z: v1.x*v2.y - v1.y*v2.x};
}
var n = crossProd(P1,P2); // normal vector to plane OP1P2 = vector along S1S2
var SS1 = vecScale(t/vecLen(n),n);
var S1 = {x: S.x+SS1.x, y: S.y+SS1.y, z: S.z+SS1.z}; // S + SS1
var S2 = {x: S.x-SS1.x, y: S.y-SS2.y, z: S.z-SS1.z}; // S - SS1
Finally we have to convert back to (lat,lng):
function Cartesian2LatLng(P)
{
var P_xy = {x: P.x, y:P.y, z:0}
return {lat: Math.atan2(P.y,P.x)/DEG2RAD, lng: Math.atan2(P.z,vecLen(P_xy))/DEG2RAD};
}
var S1_latlng = Cartesian2LatLng(S1);
var S2_latlng = Cartesian2LatLng(S2);
Yazanpro, sorry for the late response on this.
You may be interested in a concise variant of MBo's approach, which simplifies in two respects :
firstly by exploiting some of the built in features of the google.maps API to avoid much of the hard math.
secondly by using a 2D model for the calculation of the included angle, in place of MBo's spherical model. I was initially uncertain about the validity of this simplification but satisfied myself with tests in a fork of MBo's fiddle that the errors are minor at all but the largest of circles with respect to the size of the Earth (eg at low zoom levels).
Here's the function :
function getIntersections(circleA, circleB) {
/*
* Find the points of intersection of two google maps circles or equal radius
* circleA: a google.maps.Circle object
* circleB: a google.maps.Circle object
* returns: null if
* the two radii are not equal
* the two circles are coincident
* the two circles don't intersect
* otherwise returns: array containing the two points of intersection of circleA and circleB
*/
var R, centerA, centerB, D, h, h_;
try {
R = circleA.getRadius();
centerA = circleA.getCenter();
centerB = circleB.getCenter();
if(R !== circleB.getRadius()) {
throw( new Error("Radii are not equal.") );
}
if(centerA.equals(centerB)) {
throw( new Error("Circle centres are coincident.") );
}
D = google.maps.geometry.spherical.computeDistanceBetween(centerA, centerB); //Distance between the two centres (in meters)
// Check that the two circles intersect
if(D > (2 * R)) {
throw( new Error("Circles do not intersect.") );
}
h = google.maps.geometry.spherical.computeHeading(centerA, centerB); //Heading from centre of circle A to centre of circle B. (in degrees)
h_ = Math.acos(D / 2 / R) * 180 / Math.PI; //Included angle between the intersections (for either of the two circles) (in degrees). This is trivial only because the two radii are equal.
//Return an array containing the two points of intersection as google.maps.latLng objects
return [
google.maps.geometry.spherical.computeOffset(centerA, R, h + h_),
google.maps.geometry.spherical.computeOffset(centerA, R, h - h_)
];
}
catch(e) {
console.error("getIntersections() :: " + e.message);
return null;
}
}
No disrespect to MBo by the way - it's an excellent answer.

The shortest distance between multiple points

So i want to calculate distance between my start point and multiple points, than display the shortest route to this point,but it show me always the last point. this is my distanceCal function it works fine :
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)
}
and this is my points latt/long :
var dist = [
[35.733972, -5.881999],
[ 35.734077, -5.881033],
[ 35.736898, -5.877771],
[35.738396, -5.875154]
];
then my script to display directions :
function calcRoute() {
var start = new google.maps.LatLng(35.728329, -5.882750);
for (var i = 0; i < dist.length; i++)
{
var dis = dist[i];
//here i need something to choose the shortest route
var min = Math.min(getDistanceFromLatLonInKm(35.728329, -5.882750, dis[0], dis[1]));
var end = new google.maps.LatLng(dis[0], dis[1]);
}
var request = {
origin: start,
destination: end,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', getMap);
so please if someone have any idea or solution i will be very appreciate.
The following code uses Googles geometry library to calculate distances between points.The distances are stored in an array and then parsed to find minimum distance .
I have changed the array from dist[] to coords[] as we need an array to hold distances dist[].
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">
var coords = [
[35.733972, -5.881999],
[35.734077, -5.881033],
[35.736898, -5.877771],
[35.738396, -5.875154]
];
var dist = [];//Array to hold distances
function calcRoute() { {
var start = new google.maps.LatLng(35.728329, -5.882750);
for (var i = 0; i < coords.length; i++){
var point = new google.maps.LatLng(coords[i][0],coords[i][1]);
var distance = google.maps.geometry.spherical.computeDistanceBetween(start, point);
dist.push(distance);
}
var test = dist[0];
var index = 0;
for (var i = 1; i < dist.length; i++){
if(dist[i] < test){
test = dist[i];
index = i;
}
}
var end = new google.maps.LatLng(coords[index][0],coords[index][1]);
// Apply the rest of your code here
It sounds like you want to use optimizeWaypoints:true in your DirectionsServiceRequest:
optimizeWaypoints | boolean | If set to true, the DirectionService will attempt to re-order the supplied intermediate waypoints to minimize overall cost of the route. If waypoints are optimized, inspect DirectionsRoute.waypoint_order in the response to determine the new ordering.
The DirectionsResult
Each leg of each route returned includes distance and duration information.

Categories

Resources