我有这个 php 从谷歌服务器获取有关特定地理位置的数据。
<?php
if ($_GET['latitude'] AND $_GET['longitude']) {
$lat = $_GET['latitude'];
$lng = $_GET['longitude'];
echo json_encode(reverse_geocode($lat,$lng));
}
?>
<?php
//Get STATE from Google GeoData
function reverse_geocode($lat,$lng) {
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&sensor=false";
$result = file_get_contents("$url");
$json = json_decode($result);
foreach ($json->results as $result) {
foreach($result->address_components as $addressPart) {
//print_r($addressPart);
if((in_array('locality', $addressPart->types)) && (in_array('political', $addressPart->types))) {
$city = $addressPart->long_name;
}
else if((in_array('administrative_area_level_1', $addressPart->types)) && (in_array('political', $addressPart->types))) {
$state = $addressPart->long_name;
}
else if((in_array('country', $addressPart->types)) && (in_array('political', $addressPart->types))) {
$country = $addressPart->long_name;
}
else if(in_array('route', $addressPart->types)) {
$street = $addressPart->long_name;
}
else if(in_array('street_number', $addressPart->types)) {
$street_number = $addressPart->long_name;
}
else if(in_array('postal_code', $addressPart->types)) {
$postal_code = $addressPart->long_name;
}
}
}
//return $address;
return array('country' => $country, 'state' => $state, 'city' => $city, 'street' => $street_number . " " . $street, 'zip' => $postal_code);
//print_r($json);
}
?>
为了?latitude=49.260441796677014&longitude=-123.12049284766846
这将返回:
{"country":"Canada","state":"British Columbia","city":"Vancouver","street":"706-750 West 12th Avenue","zip":"V5Z"}
注意 zip,它是邮政编码的 3 个字母前缀,不是真正的邮政编码。为什么会这样?在原始 json 数据中,我似乎有完整的邮政编码。取消注释print_r($addressPart);
以查看我在说什么。