Skip to content

Instantly share code, notes, and snippets.

@MogulChris
Created January 23, 2019 02:24
Show Gist options
  • Save MogulChris/b7c2bf3b8fa864b96880bfe38c0209ae to your computer and use it in GitHub Desktop.
Save MogulChris/b7c2bf3b8fa864b96880bfe38c0209ae to your computer and use it in GitHub Desktop.
Programmatically update ACF Google Maps fields
<?php
//You need an API key and an address (as a string) to geocode
//ACF Google Maps field data looks like:
/*
array(
'address' => '123 My Street, Mytown, Mycountry, Mypostcode',
'lat' => '123.45678',
'lng' => '-125.67890',
)
*/
$api_key = 'YOUR_API_KEY_HERE';
$address = urlencode($address_string);
$post_id = 123;
$response = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=$api_key");
$response = json_decode($response,true);
if(!empty($response['results'][0]['geometry']['location'])){
$geo = $response['results'][0]['geometry']['location'];
$formatted_address = $response['results'][0]['formatted_address'];
$location = array('address' => $formatted_address, 'lat' => $geo['lat'], 'lng' => $geo['lng']);
update_field('YOUR_FIELD_KEY', $location, $post_id);
}
@iffikhan30
Copy link

Supperb

@johannlucas
Copy link

Thank you, great time saved.

@chrisokwakol
Copy link

hey so the field is updating, i can see it when i var_dump the acf field but the address on the map in the backend isn't updating. how do i go about this?

@cfxd
Copy link

cfxd commented Aug 12, 2025

This is seriously awesome, thanks for sharing it! The resulting field value only got me about 80% of the way there though and I had to come up with a but of additional parsing in order to save the field with the same array properties as when editing in the admin (I also used more WP friendly fetching tools) . Here's what I did:

function update_google_map_field($field_name = false, $address = false, $post_id = false) {
  if(!$field_name || !$address || !$post_id) return;

  $api_key    = acf_get_setting('google_api_key');
  if(!$api_key) update_field('YOUR_FIELD_KEY', [], $post_id);

  $address_param = urlencode($address);
  $maps_url      = "https://maps.googleapis.com/maps/api/geocode/json?address={$address_param}&key={$api_key}";
  $response      = wp_remote_get($maps_url);

  if(is_wp_error($response)) return;

  $response_body = wp_remote_retrieve_body($response);
  $response_json = json_decode($response_body, true);

  if(isset($response_json['status']) && $response_json['status'] === 'OK' && !empty($response_json['results'][0]['geometry']['location'])) {
    $result            = $response_json['results'][0];
    $location          = $result['geometry']['location'];
    $formatted_address = $result['formatted_address'];

// transform this just like the JS does in the admin
    $field_value = [
      'address' => $result['formatted_address'],
      'lat'     => $location['lat'],
      'lng'     => $location['lng'],
    ];

    if(!empty($result['place_id'])) {
      $field_value['place_id'] = $result['place_id'];
    }

    if(!empty($result['name'])) {
      $field_value['name'] = $result['name'];
    }

    $i = [
      'street_number' => ['street_number'],
      'street_name'   => ['street_address', 'route'],
      'city'          => ['locality', 'postal_town'],
      'state'         => [
        'administrative_area_level_1',
        'administrative_area_level_2',
        'administrative_area_level_3',
        'administrative_area_level_4',
        'administrative_area_level_5'
      ],
      'post_code'     => ['postal_code'],
      'country'       => ['country']
    ];

    foreach($i as $key => $types) {
      foreach($result['address_components'] as $component) {
        $r = $component['types'][0];
        if(in_array($r, $types, true)) {
          $field_value[$key] = $component['long_name'];
          if($component['long_name'] !== $component['short_name']) {
            $field_value[$key . '_short'] = $component['short_name'];
          }
        }
      }
    }
    update_field('YOUR_FIELD_KEY', $field_value, $post_id);
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment