How to find nearest location using latitude and longitude from a json data
To calculate distance between two co-ordinates, you can't just subtract the values. That's fine but it gives you the co-ordinates that are within a square. This may be suitable but mostly people do tend to want to search locations by radius. This function will do that...
function distance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1/180
var radlat2 = Math.PI * lat2/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);
if (dist > 1) {
dist = 1;
}
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
}
It's a common piece of code which I copied from here...
https://www.geodatasource.com/developers/javascript
And here it is, used in your example...
function distance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1/180
var radlat2 = Math.PI * lat2/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);
if (dist > 1) {
dist = 1;
}
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 data = [{
"code": "0001",
"lat": "1.28210155945393",
"lng": "103.81722480263163",
"location": "Stop 1"
}, {
"code": "0003",
"lat": "1.2777380589964",
"lng": "103.83749709165197",
"location": "Stop 2"
}, {
"code": "0002",
"lat": "1.27832046633393",
"lng": "103.83762574759974",
"location": "Stop 3"
}];
var html = "";
var poslat = 1.28210155945393;
var poslng = 103.81722480263163;
for (var i = 0; i < data.length; i++) {
// if this location is within 0.1KM of the user, add it to the list
if (distance(poslat, poslng, data[i].lat, data[i].lng, "K") <= 0.1) {
html += '<p>' + data[i].location + ' - ' + data[i].code + '</p>';
}
}
$('#nearbystops').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="nearbystops"></div>
Given a lat/long, find the nearest location based on a json list of lat/long
You could simply define a function to calculate the distance and use it to sort bus stops with the key
argument:
from math import cos, sqrt, pi
R = 6371000 #radius of the Earth in m
def distance(lon1, lat1, lon2, lat2):
x = (lon2 - lon1) * cos(0.5*(lat2+lat1))
y = (lat2 - lat1)
return (2*pi*R/360) * sqrt( x*x + y*y )
bustops = [{"BusStopCode": "00481", "RoadName": "Woodlands Rd", "Description": "BT PANJANG TEMP BUS PK", "Latitude": 1.383764, "Longitude": 103.7583},
{"BusStopCode": "01012", "RoadName": "Victoria St", "Description": "Hotel Grand Pacific", "Latitude": 1.29684825487647, "Longitude": 103.85253591654006}]
print(sorted(bustops, key= lambda d: distance(d["Longitude"], d["Latitude"], 103.5, 1.2)))
# [{'BusStopCode': '01012', 'RoadName': 'Victoria St', 'Description': 'Hotel Grand Pacific', 'Latitude': 1.29684825487647, 'Longitude': 103.85253591654006}, {'BusStopCode': '00481', 'RoadName': 'Woodlands Rd', 'Description': 'BT PANJANG TEMP BUS PK', 'Latitude': 1.383764, 'Longitude': 103.7583}]
Once this list is sorted, you can simply extract the 5 closest bus stops with [:5]
.
It should be fast enough, even with 5000 bus stops.
Note that if you don't care about the specific distance but only want to sort bus stops, you could use this function as key:
def distance2(lon1, lat1, lon2, lat2):
x = (lon2 - lon1) * cos(0.5*(lat2+lat1))
y = (lat2 - lat1)
return x*x + y*y
How to find nearest latitude/longitude from big json array of lat/lng
In case anyone comes here looking for a solution, how I solved it is by the following code:
for (let i = 0; i < json.length; i++) {
if ((Math.abs(json[i].coordinates[1] - start.lat)) + ((Math.abs(json.[i].coordinates[0] - start.lng))) < sumLatLng) {
closest = json[i];
sumLatLng = (Math.abs(json.[i].coordinates[1] - start.lat)) + ((Math.abs(json.[i].coordinates[0] - start.lng)))
} else {
console.log("error");
}
}
Basically what I do is take the sum of the starting lat & lng, subtract the lat & lng of each record from the API and take the absolute of the result. If the result is smaller than the previous result, that means that its closer.
JSON longitude latitude nearest location
My solution just creates an array of objects out of the locations and distances, sorts them, then spits them out. I've kept everything as meters instead of kilometers but it will be easy to tweak. Enjoy!
While looping:
distanceObj[i] = {
distance: hesapla(9.9608999, 49.7222842, b.Position.Longitude, b.Position.Latitude),
location: a
};
++i;
Then sort:
distanceObj.sort(function(a,b) {
return parseInt(a.distance) - parseInt(b.distance)
});
This will explain better: http://jsfiddle.net/mitchmalone/Wf6qy/1/
Nearest location from JSON column
If you have PostGIS installed on your Postgres server, you could try something like this
SELECT j.*,
ST_DISTANCE(
ST_GeogFromText('POINT(' || lng || ' ' || lat || ')'),
ST_GeogFromText('POINT(31.08 30.025)')
) AS dist
FROM YourTable AS t
CROSS JOIN jsonb_to_recordset(t.data->'locations') AS j(lat int, lng int)
ORDER BY
dist;
I strongly suggest you store geodetic information in an actual geography
column.
At the very least you should normalize this JSON out to another table if you are querying it often.
How to display the nearest latitude and longitude to my location using javascript?
Javascript function to calculate distance
$nearest=1; //Limit within 1 KM.
$("#jobnews").html("<h2>Results:</h2>");
$.each(info.companies.company, function(index, job)
{
var lat = list.location.lat;
var lng = list.location.lng;
var nam = current.location.lat;
var cou = current.location.lng;
//In below line we will get the distance between current and given coordinates.
var d=distance(nam, cou, lat, lng, "K");
//Check the d is within 1 KM, If so then add it to map.
if(nearest>d)
{
var map = "</p><img src='maps.google.com/maps/api/staticmap?center="; + lat + "," +lng +"&zoom=17&size=400x300&key="+key+"&maptype=roadmap&visual_refresh=true&markers=color:red|"+lat+","+lng+"&sensor=true'width='300' height='280'alt='Map of your location.'/>";
var nearestList = "<div><h3>DISPLAY INFO: "+lis.name+link+nam+lat+lng+cou+map+"</div>";
}
}
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
}
Passed to function:
lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees)
lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees)
unit = the unit you desire for results
where: 'M' is statute miles
'K' is kilometers (default)
'N' is nautical miles
How to find nearest location using latitude and longitude from SQL database?
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;
How can find nearest place from current location from given data.
You have your current location latitude an longitude so just find out distance between your current location and list of location address geopoints using this formula and display address with shortest distance.
private double distance(double lat1, double lon1, double lat2, double lon2) {
// haversine great circle distance approximation, returns meters
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60; // 60 nautical miles per degree of seperation
dist = dist * 1852; // 1852 meters per nautical mile
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
Related Topics
How to Look for Changes in Localstorage in Angular 4
Export Array of Objects into Excel Using JavaScript
Handle File Download from Ajax Post
Violation Long Running JavaScript Task Took Xx Ms
Add Parameters to Url Without Refresh
Different Color for Each Bar in a Bar Chart; Chartjs
How to Wait Until All JavaScript Files Are Loaded Before Executing JavaScript Code
Detecting When User Scrolls to Bottom of Div With React Js
Reactjs: Uncaught Referenceerror: Require Is Not Defined
Node.Js Check If User Already Exists
How to Simulate Mouse Click Along With Mouse Move Using JavaScript
How to Scroll Left or Right Inside a Div Using Pure JavaScript Function and No Jquery
React Js - How to Get Click Event Values from Child Component to Parent Component
Cannot Open Local File - Chrome: Not Allowed to Load Local Resource
How to Convert Uint8 Array to Base64 Encoded String
How to Redirect to Another Component Onsubmit Search