通过IP定位经纬度

由于需要给客户端提交数据接口并且数据中包括经纬度,然而数据库中只存储了IP,于是需要通过IP定位经纬度。

一开始查找是否存在Google API直接将IP转化成经纬度,没有,只有将地址转化成经纬度,开始其它查找,得到方案一和方案二:
【方案一】
使用闭关纪要21.地图人站点的IP查询经纬度和经纬度查询行政区划的服务
地址为:
http://dituren-service.appspot.com/services/ip_lookup?c=onIpLookupLoaded&ip=24.24.24.24
其实现思路为:采用IP库实现了通过IP得到一个地址的文字描述之后,再通过Google的地址解析服务去匹配经纬度,调用代码如下:

1
2
3
4
5
6
7
8
9
10
11
<?PHP
$url = "http://dituren-service.appspot.com/services/ip_lookup?c=onIpLookupLoaded&ip=24.24.24.24";
$content = @file_get_contents($url);
$result = array();
if (!empty($content)) {
    preg_match("/\((.*)\)/i", $content, $matches);
    $result = json_decode($matches[1], true);
}
print_r($result);
 
?>

【方案二】
使用http://www.blueforge.net/map/ 提供的IP地址查询服务
取数据代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?PHP
$arr = explode(" ", microtime());
$rst = $arr[1] . substr($arr[0], strpos($arr[0], '.') + 1, 3);
 
$url = "http://www.blueforge.net/map/?rs=get_ip_info&rst=&rsrnd=" . $rst . "&rsargs[]=" . $ip;
$rs = @file_get_contents($url);
preg_match("/{(.*)}/", $rs, $matches);
 
$str = '$arr=array(' . str_replace(':', '=>', $matches[1]) . ');';
$str = str_replace('parseFloat', 'floatVal', $str);
eval($str);
print_r($arr);
 
?>

由于作者是直接给JS用的,所以源地址返回的数据是JS代码,我在这里做了一个替换,将其变为PHP代码。
以上两种方法都是基于Google API,并且在速度和稳定性方面存在极大的隐患

【方案三】
比较好的方案是在本地有一个数据库存储了相关信息,直接取出来,
http://www.maxmind.com/ 这个网站提供了这样一个数据库,在其城市级的数据中,我们可以找到经纬度信息,网站提供了各种语言的程序实现,这里就不再多说了。
数据库下载地址:
http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
PHP程序下载地址:
http://geolite.maxmind.com/download/geoip/api/php/

方案三存在两个问题:

1、一些数据不全
2、存在一些乱码,特别是城市相关信息

发表评论

电子邮件地址不会被公开。 必填项已用*标注


*

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>