Good question, Let's think we have following three value in DB:
var dataFromDb = [{
"location": "First location",
"lat": "1.28210155945393",
"lng": "103.81722480263163",
}, {
"location": "Second location",
"lat": "1.2777380589964",
"lng": "103.83749709165197",
"location": "Stop 2"
}, {
"location": "Third Location",
"lat": "1.27832046633393",
"lng": "103.83762574759974",
}];
Create a function for the distance between two places:
function distanceBetweenTwoPlace(firstLat, firstLon, secondLat, secondLon, unit) {
var firstRadlat = Math.PI * firstLat/180
var secondRadlat = Math.PI * secondLat/180
var theta = firstLon-secondLon;
var radtheta = Math.PI * theta/180
var distance = Math.sin(firstRadlat) * Math.sin(secondRadlat) + Math.cos(firstRadlat) * Math.cos(secondRadlat) * Math.cos(radtheta);
if (distance > 1) {
distance = 1;
}
distance = Math.acos(distance)
distance = distance * 180/Math.PI
distance = distance * 60 * 1.1515
if (unit=="K") { distance = distance * 1.609344 }
if (unit=="N") { distance = distance * 0.8684 }
return distance
}
Define current place:
var currentLat = 1.28210155945393;
var currentLng = 103.81722480263163;
Find Records within 1KM:
for (var i = 0; i < data.length; i++) {
if (distance(currentLat, currentLng, data[i].lat, data[i].lng, "K") <= 1) {
console.log(data[i].location);
}
}