Location.distance = function ( loc1, loc2 ) {
return Math.sqrt(
Math.pow( loc2.longitude - loc1.longitude, 2 ) +
Math.pow( loc2.latitude - loc1.latitude, 2 )
);
};
Location.prototype.sortByProximity = function ( arr ) {
var that = this;
arr.sort(function ( a, b ) {
return Location.distance( that, a ) - Location.distance( that, b );
});
};
First, you have a static function Location.distance
which takes two Location
instances and returns a value representing their relative distance.
Second, you have a sortByProximity
method which is invoked as a method on Location
instances, and which expects an array of Location
instances as its first argument.
Usage:
baseLocation.sortByProximity( locArr );
// locArr is now sorted in regard to baseLocation
Live demo: http://jsfiddle.net/hGp66/