Support

Account

Home Forums Front-end Issues Displaying A Google Map On Front-End Reply To: Displaying A Google Map On Front-End

  • This is a pretty old thread so I apologize for bringing it back from the dead. I was also pretty confused by the maps documentation and it seemed like a lot of work and JavaScript to generate just one map, so I came up with a work around that uses the Google Maps Embed API in addition to the Google Maps JS API.

    Code is below, and also available as a gist here. Because it uses both the JS API and Embed API, you’ll need to generate keys for both.

    To make the map, all you’ll need to do is call acf_make_map( get_field( ‘your_google_map_field_name’ ) );

    <?php
    /**
     * Set constants for Google Maps JS API key--used for ACF's backend map--and Google Maps
     * Embed API Key, used for generating maps on the site front end.
     *
     * @link https://developers.google.com/maps/documentation/javascript/get-api-key
     * @link https://developers.google.com/maps/documentation/embed/get-api-key
     */
    const GOOGLE_MAPS_JS_API_KEY = 'MAPS-JS-API-KEY';
    const GOOGLE_MAPS_EMBED_API_KEY = 'MAPS-EMBED-API-KEY';
    /**
     * Hook Maps JS API into ACF intialization.
     */
    function add_google_map_to_acf_init() {
        acf_update_setting( 'google_api_key', GOOGLE_MAPS_JS_API_KEY );
    }
    add_action( 'acf/init', 'add_google_map_to_acf_init' );
    /**
     * Pass in ACF Google Map field to generate HTML for
     * Google maps embed on the front end of the site.
     *
     * @param array  $acf_map_field  The array generated by ACF Google Maps field.
     *
     * @link https://developers.google.com/maps/documentation/embed/guide
     */
    function acf_make_map( $acf_map_field ){
        $address_field = $acf_map_field['address'];
        $encoded_address = urlencode( $address_field );
        echo '
            <iframe
                width="600"
                height="450"
                frameborder="0" style="border:0"
                src="https://www.google.com/maps/embed/v1/place?key=' . GOOGLE_MAPS_EMBED_API_KEY . '&q=' . $encoded_address . '" allowfullscreen>
            </iframe>';
    }