我對JSON相當陌生,並且試圖使用curl從Google Maps API獲取經過編碼的城市的經緯度。我使用的功能是:使用PHP(curl)從JSON(Google Maps API)中提取數據
function geocode($city){
$cityclean = str_replace (" ", "+", $city);
$details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $cityclean . "&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $details_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$geoloc = json_decode(curl_exec($ch), true);
$step1 = $geoloc['results'];
$step2 = $step1['geometry'];
$coords = $step2['location'];
print $coords['lat'];
print $coords['lng'];
}
所有這一切的目標是,從結果拉緯度和經度值 - >幾何 - >位置以下JSON的數組:
{
"status": "OK",
"results": [ {
"types": [ "locality", "political" ],
"formatted_address": "Westminster, London, UK",
"address_components": [ {
"long_name": "London",
"short_name": "London",
"types": [ "locality", "political" ]
}, {
"long_name": "Westminster",
"short_name": "Westminster",
"types": [ "administrative_area_level_3", "political" ]
}, {
"long_name": "Greater London",
"short_name": "Greater London",
"types": [ "administrative_area_level_2", "political" ]
}, {
"long_name": "England",
"short_name": "England",
"types": [ "administrative_area_level_1", "political" ]
}, {
"long_name": "United Kingdom",
"short_name": "GB",
"types": [ "country", "political" ]
} ],
"geometry": {
"location": {
"lat": 51.5001524,
"lng": -0.1262362
},
"location_type": "APPROXIMATE",
"viewport": {
"southwest": {
"lat": 51.3493528,
"lng": -0.3783580
},
"northeast": {
"lat": 51.7040647,
"lng": 0.1502295
}
},
"bounds": {
"southwest": {
"lat": 51.3493528,
"lng": -0.3783580
},
"northeast": {
"lat": 51.7040647,
"lng": 0.1502295
}
}
}
} ]
}
但是,它不打印任何東西。我知道該函數可以成功從Google獲取JSON並將其帶到我的服務器,就像我爲'status'值做了一個打印語句,並返回'OK'。這個問題似乎是當我嘗試深入研究JSON的時候。
對不起,如果這是一個簡單的問題,但正如我所說,我是新來的,現在它讓我瘋狂。
非常感謝! :)
偉大的作品,非常感謝:)我認爲這將是什麼做的陣列,我只以前使用JSON獲得從容器中的數據。再次感謝! :D – 2011-04-02 20:24:25
不客氣:-)玩得開心! – 2011-04-02 20:26:39
嗨,有沒有辦法使用用戶的ip獲得緯度長? – 2014-05-26 10:50:59