简体   繁体   English

NodeJS通过纬度/经度查找国家/地区

[英]NodeJS find country by Lat/Lon

I have a nodejs server and multiply databases, one for each country. 我有一个nodejs服务器,并有多个数据库,每个国家一个。
I want to be able to select the correct country by coordinates (lat/Lon) the user sends as parameter. 我希望能够通过用户作为参数发送的坐标(纬度/经度)选择正确的国家/地区。 (eg myserver/query/lat/lon) (例如,myserver / query / lat / lon)
I couldn't find a nodejs package which does that. 我找不到能做到这一点的nodejs包。
I did found ones who filter by country based on ip address but that's not the case here. 我确实找到了那些根据IP地址按国家/地区进行过滤的人,但实际情况并非如此。

Thanks. 谢谢。

Here is a package for that: https://github.com/vkurchatkin/which-country 这是一个软件包: https : //github.com/vkurchatkin/which-country

The API is quite simple: 该API非常简单:

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). 它在后台使用R树,因此它比线性扫描要快得多(我想是O(log n))。

Here is what I did: 这是我所做的:
I downloaded the kml files given by geofabrik for each country (eg download.geofabrik.de/africa/cameroon.kml) . 我下载了geofabrik为每个国家/地区提供的kml文件(例如,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 ). 最终,我将文件加载到nodejs中,并使用了一个名为“ 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';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM