Quick programmatic setup of Google Maps using Advanced Custom Fields.

First set up the project in Google Cloud Console and obtain an API key for Google Maps. More info is available on the ACF documentation.

You will also need to set up a map and obtain the map ID from within Google Cloud Console. This allows you to use the AdvancedMarkerElement library and get rid of the deprecation notice in the console for the MarkerElement library.

Add a filter to your theme to register the API key with ACF:


function mytheme_acf_google_map_api($api) {

    $api['key'] = 'YOUR_KEY';
    return $api;

}

add_filter('acf/fields/google_map/api', 'mytheme_acf_google_map_api');

The Google Map field returns an array e.g:


Array
(
    [address] => AMP Technology Centre - Serviced Offices, Workshops, Conferencing and Meeting Rooms, Rotherham, UK
    [lat] => 53.3868086
    [lng] => -1.3779999
    [zoom] => 14
    [place_id] => ChIJL9hWFdR3eUgRgfRhwzKwCeo
    [name] => AMP Technology Centre - Serviced Offices, Workshops, Conferencing and Meeting Rooms
    [city] => Rotherham
    [state] => England
    [post_code] => S60 5WG
    [country] => United Kingdom
    [country_short] => GB
)

You can then load and render them map in one go using the following HTML:


<?php
$map_location = get_field('map_location', $post);
?>

<div class="ratio ratio-1x1">
    <div id="map">
    </div>
</div>

<script type="text/javascript">
    (function() {

        window.initMap = function() {

            const map = new google.maps.Map(document.querySelector("#map"), {
                zoom: ' . $map_location['zoom'] . ',
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                mapId: "[YOUR MAP ID]"
            });

            const latLng = {
                lat: parseFloat(' . $map_location['lat'] . '),
                lng: parseFloat(' . $map_location['lng'] . ')
            };

            const marker = new google.maps.marker.AdvancedMarkerElement({
                position : latLng,
                map: map
            });

            map.setCenter(latLng);

        }

    })();
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=[YOUR KEY]&callback=initMap&libraries=marker&loading=async"></script>

Also note the inclusion of callback=initMap in the Google Maps script src which calls the initMap() function once the library has loaded.

You must include libraries=marker to use the AdvancedMarkerElement, and loading=async is recommended by Google Maps also for performance.

Mobile Menu