Need to find something?

Conditionally Center Google Maps field for Advanced Custom Fields

If you want to center the Google Maps field from Advanced Custom Fields based on conditions, you can easily do it with a filter acf/load_field. Let us see how.

If you have used the Google Maps field from Advanced Custom fields, you may already know that it centers at Melbourne, Australia. You can change lat and lng values to change this.

Google Maps field Lattitude and Longitude setting for initially centering the map
Default view of the Google Maps field from Advanced Custom Fields
The default view of the Google Maps field from Advanced Custom Fields

In a recent project, I needed to display the Google Maps field according to the user’s current location. The project consists of three countries and users will mostly select locations from those three countries. So, what we need is to default (center) the Google Maps field at those countries when the field is shown.

The Code Snippet

function acf_google_map_load_field( $field ) {
    if ( ef_event_country() == 'us' ) {
        $field['center_lat'] = '40.712776' ;
        $field['center_lng'] = '-74.005974';
    } elseif ( ef_event_country() == 'aus' ) {
        $field['center_lat'] = '-37.81411' ;
        $field['center_lng'] = '144.96328';
    } elseif ( ef_event_country() == 'nz' ) {
        $field['center_lat'] = '-36.848461' ;
        $field['center_lng'] = '174.763336';
    } else {
        // Default to US if country not set
        $field['center_lat'] = '40.712776' ;
        $field['center_lng'] = '-74.005974';
    return $field;

add_filter('acf/load_field/name=event_address', 'acf_google_map_load_field');Code language: PHP (php)

Here I already had a function ef_event_country that returns the user’s country. We simply assigned values to the field’s center_lat and center_lng with our own latitude and longitude values.

That ensured our users see their country when the Google Maps field is loaded 👌

Last Updated: November 15, 2021

Al-Mamun Talukder

About Al-Mamun Talukder

WordPress Developer. Minimalist Designer. Tech Enthusiast. Loves Cars. Founder of Omnixima.

Connect with me: Upwork, GitHub, Facebook, Twitter

Leave the first comment