通过百度api实现通过经纬度反查省市区

1、首先登录百度帐号,创建一个新应用,选择WEB应用吧,设置下可访问的白名单

2、将获得的ak填入接口中,形如:

http://api.map.baidu.com/geocoder/v2/?ak=你的百度key&location=".$latitude.",".$longitude."&output=json&pois=1

3、运行接口,可得到返回的json串

具体代码如下:

$query = "SELECT * FROM store order by id desc";
$row = mysql_query($query);
$n = 1;
while($rows = mysql_fetch_array($row)){
    $longitude = $rows['longitude'];
    $latitude = $rows['latitude'];
    //调取百度接口,其中ak为百度帐号key,注意location纬度在前,经度在后
    $api = "http://api.map.baidu.com/geocoder/v2/?ak=你的百度key&location=".$latitude.",".$longitude."&output=json&pois=1";
    $content = file_get_contents($api);
    $arr = json_decode($content,true);
    $province = $arr['result']['addressComponent']['province'];
    $city = $arr['result']['addressComponent']['city'];
    $district = $arr['result']['addressComponent']['district'];
    $sql = "UPDATE store set province='".$province."',city='".$city."',area='".$district."' where storeid=".$rows['storeid'];
    $res = mysql_query($sql);
    if($res){
        echo '成功更新第'.$n.'个门店
'; $n++; }else{ echo '失败'; } }



你可能感兴趣的:(php,百度api)