您的位置:首页 > 其它

curl 模拟发起百度地图API post请求

2015-11-20 18:11 603 查看
注:开始做的是get请求,比较简单,然后又查询了一番就做成了post请求,有几个地方特别说明一下:
  一,$address,是必须传的,$city可不传;
  二,ak跟之前的key一直,需要申请,我的好像没申请直接网上找的用的;
  三,如果你希望回调某个函数的话,$data 里面的callback可填你要填写的回调函数名,如果希望结果直接输出的则填null,(这里面坑了一下,因为没经验啊);
  四,对json对象的处理,json_decode真的很强大,但是刚刚一直用print_r打印,结果返回的是带函数的参数,显示的是参数,用var_dump才发现原因,有点坑的,
  五,output:控制输出格式,还有xml类型的,没试过,详情看文档去吧;
 如果希望编译为数组则json_decoded(string, true);第二个参数默认是false的;
代码如下,亲测可用的;
<code php>
protected function _get_coordinate_by_name ($address, $city='') {
$url = 'http://api.map.baidu.com/geocoder/v2/';

$data = array(
'ak'      => 'E4805d16520de693a3fe707cdc962045',
'callback' => null,
'output'   => 'json',
'address'  => $address,
'city'    => $city,
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_REFERER, 'http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-geocoding');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ret  = curl_exec($ch);
curl_close($ch);
$ret  =  json_decode($ret, true);
$_coord['lat'] = $ret['result']['location']['lat'];
$_coord['lng'] = $ret['result']['location']['lng'];

return $_coord;
}
</code>
注:http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-geocoding
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: