We save the GEO coordinates after saving a post.
/**
* Location
*/
class Location {
/**
* Construct
*/
public function __construct() {
// GEO
add_action( 'save_post', array( $this, 'save_post_try_geocode' ) );
}
/**
* Save post try geocode
*/
public function save_post_try_geocode( $post_id ) {
$address = ventures_get_field( 'ventures_location_address', $post_id );
$latitude = ventures_get_field( 'ventures_location_latitude', $post_id );
$longitude = ventures_get_field( 'ventures_location_latitude', $post_id );
$key = get_option( 'ventures_google_maps_api_key' );
if ( empty( $address ) ) {
return;
}
if ( $latitude || $longitude ) {
return;
}
if ( empty( $key ) ) {
return;
}
$data = null;
// URL
$url = sprintf(
'https://maps.googleapis.com/maps/api/%s/%s?%s',
'geocode',
'json',
_http_build_query(
array(
'address' => $address,
'sensor' => false,
'key' => $key,
)
)
);
$response = wp_remote_get( $url );
if ( ! is_wp_error( $response ) ) {
$body = $response['body'];
$data = json_decode( $body );
}
if ( empty( $data ) ) {
return;
}
if ( $data ) {
foreach ( $data->results as $result ) {
$location = $result->geometry->location;
$latitude = $location->lat;
$longitude = $location->lng;
update_field( 'ventures_location_latitude', $latitude, $post_id );
update_field( 'ventures_location_longitude', $longitude, $post_id );
}
}
}
}