To retrieve the index, utilize the code snippet below. The approach emulates the pattern established by @Meadow.
let points = [{
"latitude": 55.85,
"longitude": 4.22
},
{
"latitude": 55.89,
"longitude": 4.16
},
{
"latitude": 55.88,
"longitude": -4.24
},
{
"latitude": 55.86,
"longitude": 4.21
}
];
let allDistance:any = [];
points.forEach((x,index)=> {
var res = this.getDistance(x.latitude, x.longitude, 55.87, 4.20, "km");
allDistance.push({ distance: res, obj: x,index: index});
});
allDistance.sort((a, b) => a.distance - b.distance);
console.log("Index:"+allDistance[0].index);
console.log(allDistance);
Custom Distance Calculation Function:
getDistance(markerLat: any, markerLon: any, sourceLat: any, sourceLng: any,unit): any {
var radlat1 = Math.PI * sourceLat / 180;
var radlat2 = Math.PI * markerLat / 180;
var theta = sourceLng - markerLon;
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;
dist = dist * 1.609344;
if (unit != 'mi') {
return isNaN(dist) ? 0 : dist;
}
return isNaN(dist * 0.62137) ? 0 : dist * 0.62137;
}