我目前正在尝试通过 html5 获得的 GEO 来解决我的用户位置问题,现在我正在尝试从 Google API 获取格式化的地址。
我已经这样做了:
function LatLong($Latitude, $Longitude) {
$Url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$Latitude,$Longitude&sensor=true";
//send request:
$Client = curl_init($Url);
//Set options:
curl_setopt($Client, CURLOPT_RETURNTRANSFER, 1);
//query the API and fetch results:
$Response = curl_exec($Client);
//decode the response:
return json_decode($Response);
}
现在,为了获得完整的结果,我尝试了这个只是为了看看它是否有效:
print_r(LatLong($_COOKIE['latitude'], $_COOKIE['longitude'])->results);
我确实得到了结果:
"results" : [
{
"address_components" : [
{
"long_name" : "4",
"short_name" : "4",
"types" : [ "street_number" ]
},
{
"long_name" : "Neuwerk - Cuxhaven",
"short_name" : "Neuwerk - Cuxhaven",
"types" : [ "route" ]
},
{
"long_name" : "Hamburg-Insel Neuwerk",
"short_name" : "Hamburg-Insel Neuwerk",
"types" : [ "sublocality_level_1", "sublocality", "political" ]
},
{
"long_name" : "Hamburg",
"short_name" : "Hamburg",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Hamburg",
"short_name" : "Hamburg",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Tyskland",
"short_name" : "DE",
"types" : [ "country", "political" ]
},
{
"long_name" : "27499",
"short_name" : "27499",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Neuwerk - Cuxhaven 4, 27499 Hamburg, Tyskland",
"geometry" : {
"location" : {
"lat" : 53.91403529999999,
"lng" : 8.4899886
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 53.91538428029149,
"lng" : 8.491337580291502
},
"southwest" : {
"lat" : 53.91268631970849,
"lng" : 8.488639619708497
}
}
},
"place_id" : "ChIJrT-2jXcZtEcRv91jn7XQhcQ",
"types" : [ "street_address" ]
}
我想打印formatted_address
我尝试这样做:
print_r(LatLong($_COOKIE['latitude'], $_COOKIE['longitude'])->results->formatted_address);
但是我什么也没得到,我做错了什么?
最佳答案
正如问题中所发布的,results
是一个数组。这意味着您可能希望在获取 formatted_address
之前访问第一个元素。
试试这个:
print_r(LatLong($_COOKIE['latitude'], $_COOKIE['longitude'])->results[0]->formatted_address);
关于php - Google Geo API(纬度 + 经度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32558654/