我正在使用php将纬度和经度转换为WordPress自定义字段中的地址。它按照我想要的方式工作,除了我在地址末尾得到国家(例如1234 1st City State 90210 USA)。
这是我用来进行转换的代码。关于如何删除国名,有什么想法吗?
function getaddress($post_id)
{
$coorloc = get_field('event_location');
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.urlencode($coorloc).'&sensor=false';
$json = @file_get_contents($url);
$data=json_decode($json);
$status = $data->status;
if($status=="OK")
$address = $data->results[0]->formatted_address;
update_post_meta($post_id, "geocoderaddress", $address);
}
add_action('acf/save_post', 'getaddress', 1);
您不需要这样做,因为google提供address_components
正是出于这个原因。
http://maps.googleapis.com/maps/api/geocode/json?sensor=false&latlng=51.278777,-0.951090
API提供了每个组件,因此您可以随心所欲地使用每个部件。
供参考的address_components
代码段:
{
"long_name":"United Kingdom",
"short_name":"GB",
"types":[
"country",
"political"
]
},
{
"long_name":"RG27 9XB",
"short_name":"RG27 9XB",
"types":[
"postal_code"
]
}
我有一个想法
$addressBits = explode(" ", $address);
$parts = count($addressBits);
for($i = o; $i <= $parts - 1; $i++){
$newAddress .= $addressBits[$i] . " ";
}
也许你可以试试这个