Reputation: 3620
I have a nodejs server and multiply databases, one for each country.
I want to be able to select the correct country by coordinates (lat/Lon) the user sends as parameter. (e.g myserver/query/lat/lon)
I couldn't find a nodejs package which does that.
I did found ones who filter by country based on ip address but that's not the case here.
Thanks.
Upvotes: 1
Views: 4172
Reputation: 3620
Here is what I did:
I downloaded the kml files given by geofabrik for each country (e.g download.geofabrik.de/africa/cameroon.kml) .
Finally I loaded the file into nodejs and used a great package named "point-in-polygon" (https://www.npmjs.org/package/point-in-polygon).
The code:
var inside = require('point-in-polygon')
var fs = require('fs');
var file = __dirname + '/coutries.json';
var countries_json = JSON.parse(fs.readFileSync(file, 'utf8'));
var get_country = function(lat, lon){
var c_list = countries_json['countries'];
for(var num in c_list){
var country = c_list[num];
if (inside([lat, lon],country['coordinates'])){
return country['name'];
}
}
return 'not_found';
}
Upvotes: 2
Reputation: 13570
Here is a package for that: https://github.com/vkurchatkin/which-country
The API is quite simple:
var wc = require('which-country');
console.log(wc([-100, 40])); // prints "USA"
it uses R-tree under the hood, so it's much faster than linear scan (O(log n), I suppose).
Upvotes: 4