Shortest Distance From An Array
- by notyou61
I have an ajax function which returns the latitudes and longitudes of locations stored in a database. These are returned and placed in an array. A calculation is performed to return their distance from the users current location based on the latitude/longitude. I would like to return only the record with the shortest calculated distance. My code is as follows:
Ajax Success
// Success
success: function (data) {
// Obtain Log/Lat
navigator.geolocation.getCurrentPosition(function(position) {
// Obtain Current Position Lat/Lon
glbVar.latitude = position.coords.latitude;
glbVar.longitude = position.coords.longitude;
// Console Log
//console.log('Lat: ' + glbVar.latitude + ' Lon: ' + glbVar.longitude);
// Obtain Location Distances
for ( var i = 0; i < data.length; i++ ) {
// Location Instances
var varLocation = data[i];
// Location Distance
varLocation.distance = calculateDistance(glbVar.longitude, glbVar.latitude, varLocation.locationLongitude, varLocation.locationLatitude);
}
// Sort Locations By Distance
var sortedData = data.sort(function(a, b) {
// Return Locations
return a.distance - b.distance;
});
// Output Results
$.map(sortedData, function(item) {
// Obtain Location Distance
varLocationsDistance = calculateDistance(glbVar.longitude, glbVar.latitude, item.locationLongitude, item.locationLatitude);
// Obtain Location Radius Assignment
if (varLocationsDistance <= varLocationRadius) {
// Function Return
functionReturn = $({locationID : item.locationID + ', Distance : ' + varLocationsDistance + ' m'});
// Return
// Function to get the Min value in Array
Array.min = function( sortedData ){
functionReturn = Math.min.apply( Math, sortedData );
//
console.log(functionReturn);
};
}
});
});
}
The calculateDistance function returns the distance from the users current location and those from the database. The varLocationsDistance <= varLocationRadius "If" statement returns records within a certain distance radius (100 meters), within that statement I would like to return the shortest distance.
I am a self taught amateur web developer and as a result may not have provide enough information for an answer, please let me know.
Thanks,