发布于 4年前

ip地址如何转换为经纬度坐标?

最近,在做地图相关的应用。 有大量的用户数据是ip地址,如果把用户标记在地图上,需要把ip地址转换为经纬度坐标。

使用的方案比较折腾:

Nginx 有 geoip 的模块,检查安装的 Nginx 是否编译了这个模块。

nginx -V

nginx version: nginx/1.1.19
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-log-path=/var/log/nginx/access.log --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --with-debug --with-http_addition_module --with-http_dav_module --with-http_geoip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_realip_module --with-http_stub_status_module --with-http_ssl_module --with-http_sub_module --with-http_xslt_module --with-ipv6 --with-sha1=/usr/include/openssl --with-md5=/usr/include/openssl --with-mail --with-mail_ssl_module --add-module=/build/buildd/nginx-1.1.19/debian/modules/nginx-auth-pam --add-module=/build/buildd/nginx-1.1.19/debian/modules/nginx-echo --add-module=/build/buildd/nginx-1.1.19/debian/modules/nginx-upstream-fair --add-module=/build/buildd/nginx-1.1.19/debian/modules/nginx-dav-ext-module

如果是没有重新编译一个带 geoip 模块的 Nginx 使用。

Nginx 的配置文件配置 geoip 的数据库,geoip 的数据库有收费的,也有免费的下载,我都是用免费的,经常更新一下即可。

http {
    geoip_country  /etc/nginx/GeoIP.dat;
    geoip_city     /etc/nginx/GeoLiteCity.dat;
}

GEO 的信息就可以通过fastcgi的参数传递给应用了,以下是Django的一段 fastcgi 配置示例。

#GeoIP
fastcgi_param GEOIP_COUNTRY_CODE $geoip_city_country_code;
fastcgi_param GEOIP_COUNTRY_CODE3 $geoip_country_code3;
fastcgi_param GEOIP_COUNTRY_NAME $geoip_country_name;
fastcgi_param GEOIP_CITY_COUNTRY_CODE $geoip_city_country_code;
fastcgi_param GEOIP_CITY_COUNTRY_CODE3 $geoip_city_country_code3;
fastcgi_param GEOIP_CITY_COUNTRY_NAME $geoip_city_country_name;
fastcgi_param GEOIP_REGION $geoip_region;
fastcgi_param GEOIP_CITY $geoip_city;
fastcgi_param GEOIP_POSTAL_CODE $geoip_postal_code;
fastcgi_param GEOIP_CITY_CONTINENT_CODE $geoip_city_continent_code;
fastcgi_param GEOIP_LAT $geoip_latitude;
fastcgi_param GEOIP_LNG $geoip_longitude;

Django 把得到的经纬度通过 Ajax 传递到前台,交给 Google Map API 显示即可。如果是国内的 IP 可能就不准确,我用了纯真IP的数据库,方法 Google 一下有很多。

这个方法的限定是使用 Nginx + fastcgi,不是适合所有的人。

©2020 edoou.com   京ICP备16001874号-3