由于做微信公众平台的时候需要根据经纬度获取地址,所以才有这个,本来没什么好写的,可是由于没做过php解析json对象,所以还是吃了点小亏,写下来记录一下
百度地图地址解析
直接给出链接 http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-geocoding
在该例子中需要通过经纬度获取地址
api链接 http://api.map.baidu.com/geocoder/v2/?ak=百度应用&location=经度,纬度&output=json&pois=0;
不需要回调函数
通过该地址返回的json数据如下
{
status: 0,
result: {
location: {
lng: 112.99999999488,
lat: 35.999999889577
},
formatted_address: “山西省长治市长治县东师线”,
business: “”,
addressComponent: {
city: “长治市”,
country: “中国”,
direction: “”,
distance: “”,
district: “长治县”,
province: “山西省”,
street: “东师线”,
street_number: “”,
country_code: 0
},
poiRegions: [ ],
sematic_description: “”,
cityCode: 356
}
}
php解析json对象
我看了阮一峰的一篇文章 http://www.ruanyifeng.com/blog/2011/01/json_in_php.html
由于返回的是json文本,所以首先要将json文本转换为php数据结构,利用json_decode($json),
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
经过上述转换,即可得到如下php对象
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
所以获取其中对象的时候,可利用如下方式
$json->{'a'}
附上实现代码
function getKm($lat1, $lng1, $lat2, $lng2)
{
if($lat1 == 0 && $lng1 == 0){
if($lat2 == 0 && $lng2 == 0){
return "0";
}else {
$url = "http://api.map.baidu.com/geocoder/v2/?ak=gGboNqlNjflXCNq0A6ewpSLB&location=" . $lat2 . "," . $lng2 . "&output=json&pois=0";
$json = file_get_contents($url);
$json = json_decode($json);
return $json->{'result'}->{'addressComponent'}->{'city'};
}
}else {
$dis = getKmnum($lat1,$lng1,$lat2,$lng2);
return $dis.'km';
}
}
同时附上经纬度计算距离的代码
function getKmnum($lat1, $lng1, $lat2, $lng2)
{
$earthRadius = 6367000; //approximate radius of earth in meters
$lat1 = ($lat1 * pi()) / 180;
$lng1 = ($lng1 * pi()) / 180;
$lat2 = ($lat2 * pi()) / 180;
$lng2 = ($lng2 * pi()) / 180;
$calcLongitude = $lng2 - $lng1;
$calcLatitude = $lat2 - $lat1;
$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
$stepTwo = 2 * asin(min(1, sqrt($stepOne)));
$calculatedDistance = $earthRadius * $stepTwo;
$dis = ceil(round($calculatedDistance) / 1000);
return $dis;
}