// Get location data from Google
function parse_address_google( $address = '' ) {
if( empty( $address ) ) {
return;
}
$geolocate_api_key = 'AIzaSyCshTHf8t754yocWAZLD4bGtLrUMovKYjY';
$address = urlencode( $address );
$request = wp_remote_get("https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=$geolocate_api_key");
$json = wp_remote_retrieve_body( $request );
$data = json_decode( $json );
if ( !$data ) {
// ERROR! Google Maps returned an invalid response, expected JSON data
return;
}
if ( isset($data->{'error_message'}) ) {
// ERROR! Google Maps API returned an error
return;
}
if ( empty($data->{'results'}[0]->{'geometry'}->{'location'}->{'lat'}) || empty($data->{'results'}[0]->{'geometry'}->{'location'}->{'lng'}) ) {
// ERROR! Latitude/Longitude could not be found
return;
}
$array = json_decode( $json, true );
$result = $array['results'][0];
$location = array();
// street_number, street_name, city, state, post_code and country
foreach ($result['address_components'] as $component) {
switch ($component['types']) {
case in_array('street_number', $component['types']):
$location['street_number'] = $component['long_name'];
break;
case in_array('route', $component['types']):
$location['street_name'] = $component['long_name'];
break;
case in_array('sublocality', $component['types']):
$location['sublocality'] = $component['long_name'];
break;
case in_array('locality', $component['types']):
$location['city'] = $component['long_name'];
break;
case in_array('administrative_area_level_2', $component['types']):
$location['region'] = $component['long_name'];
break;
case in_array('administrative_area_level_1', $component['types']):
$location['state'] = $component['long_name'];
$location['state_short'] = $component['short_name'];
break;
case in_array('postal_code', $component['types']):
$location['postal_code'] = $component['long_name'];
break;
case in_array('country', $component['types']):
$location['country'] = $component['long_name'];
$location['country_short'] = $component['short_name'];
break;
}
}
$location['lat'] = $data->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$location['lng'] = $data->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
return $location;
}
// run on import
function wbmz_acf_update_map_field( $id ) {
// Get ACF map field
$field = get_field( 'field_614304efadf17', $id );
if( empty( $field['address'] ) ) {
return;
}
$location = parse_address_google( $field['address'] );
$args = wp_parse_args( $location, $field );
update_field( 'field_614304efadf17', $args, $id );
$to = 'mitchell@webmazing.nl';
$subject = 'Livsane | gmaps locatie copgehaald';
$body = 'Opgehaald';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
}
add_action( 'pmxi_saved_post', 'wbmz_acf_update_map_field', 10, 1 );
#acf #api #geolocate #google #import #map #places