Shoora
4/11/2018 - 11:08 AM

JavaScript-free implementation of Google Maps with WordPress Advanced Custom Fields

JavaScript-free implementation of Google Maps with WordPress Advanced Custom Fields

<?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>';
}