I recently came across a helpful formula in this question that allows me to determine the nearest marker on the map based on the current position. However, I am now looking to enhance this formula so that it can identify not just the closest marker, but the closest n
number of locations (such as the top 5 or top 10 closest). I'm unsure about how to go about implementing this modification.
Below is the adjusted formula I am currently using:
function rad(x) {return x*Math.PI/180;}
function find_closest_marker(center, map) {
var lat = center.lat();
var lng = center.lng();
var R = 6371; // radius of earth in km
var distances = [];
var closest = -1;
for( i=0;i<markers.length; i++ ) {
var mlat = markers[i].position.lat();
var mlng = markers[i].position.lng();
var dLat = rad(mlat - lat);
var dLong = rad(mlng - lng);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
distances[i] = d;
if ( closest == -1 || d < distances[closest] ) {
closest = i;
}
}
//Displaying the title of the closest marker
console.log(markers[closest].title);
}
This is how I load the markers initially:
// Adding markers to the map
function setMarkers(center, map) {
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "js/data.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
// Loop over each JSON element
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lon);
// Creating and placing a marker on the map
var icon = 'assets/marker.png';
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: icon,
title: data.loc
});
markers.push(marker);
infoBox(map, marker, data);
}
}
Any insights on how I could further modify the formula to identify the closest n
markers instead of just the single closest one?