WordPress: ottenere le coordinate di un indirizzo con le API di Google Maps
Le API delle Google Maps ci permettono di ottenere le coordinate di un indirizzo.
Possiamo implementare la seguente funzione:
function my_get_coords( $address ) {
$address = urlencode( $address ); // Indirizzo codificato
$url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address={$address}";
$resp_json = wp_remote_get( $url, array( 'timeout' => 2 ) ); // 2 secondi di timeout
if( !is_wp_error( $resp_json ) ) {
$resp = json_decode( $resp_json['body'], true ); // Output JSON come array associativo
if( $resp['status'] == 'OK' ) {
$lat = $resp['results'][0]['geometry']['location']['lat'];
$lng = $resp['results'][0]['geometry']['location']['lng'];
if( $lat && $lng ) {
$data_arr = array();
$data_arr['latitude'] = $lat;
$data_arr['longitude'] = $lng;
return $data_arr;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
Esempio d'uso:
$coords = my_get_coords( 'Via San Michele 162, Vasto' );
if( is_array( $coords ) ) {
//...
}