-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnearest.js
58 lines (51 loc) · 1.91 KB
/
nearest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Nearest:- finds the nearest things to a give thing, geospatially speaking
*
* Eg, given an array of objects with a lat/lon properties
*
* [
* { place: 'london', lat: , lon: },
* { place: 'manchester', lat: , lon: },
* { place: 'cardiff', lat: , lon: },
* ]
*
*/
var Nearest = function () {
// credit: http://www.perlmonks.org/?node_id=150054
this.distanceInKm = function (lat1,lon1,lat2,lon2) {
var deg2rad = function(deg) { return deg * (Math.PI/180) }
, R = 6371 // Radius of the earth in km
, dLat = deg2rad(lat2-lat1)
, dLon = deg2rad(lon2-lon1)
, a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
, c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
, d = R * c; // Distance in km
return d;
}
this.find = function( dataSource, opts ) {
var opts = opts || {}
, within = opts.within || 10
, limit = opts.limit || 50
, lat = opts.coords[0]
, lon = opts.coords[1]
, that = this;
return dataSource.map(function (record, index) { // calculate distance from give coords
return {
distance: parseFloat(that.distanceInKm(lat, lon, record.lat, record.lon).toFixed(2)),
i: index
}
}).sort(function (a,b) { // sort by distance
return a.distance - b.distance
}).filter(function (record) { // remove records above a given distance
return record.distance < within
}).map(function (record) { // return the original record
dataSource[record.i].distance = record.distance;
return dataSource[record.i];
}).slice(0, limit)
}
return this;
}
module.exports = Nearest;