Currently, I am transitioning a functional JS solution to Typescript. In my possession is an array of objects containing geolocation data in the form of latitude and longitude coordinates.
My goal is to arrange these objects based on their proximity to a specific location identified as currentLocation
.
I am facing a challenge in storing currentLocation
as a private attribute and then accessing it within the sorting function. Even after attempting this.currentLocation
, the variable remains undefined in the compare
function. Despite trying out compare.bind(this)
, the issue persists as this
is not defined.
Does anyone have suggestions on how to resolve this dilemma? In the past, I managed to circumvent this in JavaScript by using global variables, but I am seeking a more refined approach. It is worth noting that sortByDistance
functions as a method within an object.
sortByDistance() {
this.currentPosition = Leaflet.latLng(this._currentLatLng[0], this._currentLatLng[1]);
function compare(a, b) {
let p1 = Leaflet.latLng(a.lat, a.lng);
let p2 = Leaflet.latLng(b.lat, b.lng);
if (p1.distanceTo(this.currentPosition) < p2.distanceTo(this.currentPosition))
return -1;
else if (p1.distanceTo(this.currentPosition) > p2.distanceTo(this.currentPosition))
return 1;
return 0;
}
compare.bind(this);
this.sorted = this.objects.sort(compare);
}