YogeshChauhan . com

How to add Google Map in WordPress using ACF?

in WordPress on May 14, 2021

The Google Map field in Advanced Custom Fields provides an easy way to an interactive Google map interface. You can select a location in the backend and in the frontend, your users will be able to see that location on Google map.

It is dependent on the data from Google Maps API. Using jQuery you can make it autocomplete the search of a place, you can also do geocoding lookup as well as add markers to different places.

Prerequisites

  1. Google Map field is only supported in ACF pro so you need to have that to use it.
  2. Get your Google Maps API key.
  3. Enable the following APIs in your project.
    1. Geocoding API
    2. Maps JavaScript API
    3. Places API

Add ACF Google Map Field

Here’s the screenshot of how you can add the Google Map field using ACF. Change the fields according yo your requirements.

You can use “Center” to define the initial center point of map. It takes two values, latitude and longitude.

Use “Zoom” option to set the initial zoom of the map and “Height” option to set the height.

List of field settings shown when setting up a Google Map field

Register Google API key

Add one of these code snippet 👇 to your functions.php file.

Method 1: Filter


function my_acf_google_map_api( $api ){
    $api['key'] = 'xxx';
    return $api;
}
add_filter('acf/fields/google_map/api', 'my_acf_google_map_api');

Method 2: Setting


function my_acf_init() {
    acf_update_setting('google_api_key', 'xxx');
}
add_action('acf/init', 'my_acf_init');

amazon prime gift

Google Maps helper code

Inject Google Maps API script

Add this script to your header.php file or any other page template between header tags.



<script 
  src="https://maps.googleapis.com/maps/api/js
  ?key=YOUR_API_KEY">
</script>


Optional Style

Add this optional style if you want. You can always use the classes and add your own styles.


.acf-map {
    width: 100%;
    height: 400px;
    border: #ccc solid 1px;
    margin: 20px 0;
}

// Fixes potential theme css conflict.
.acf-map img {
   max-width: inherit !important;
}

Create a map.js

Create a map.js file and add this code in it.


(function( $ ) {

/**
 * initMap
 *
 * Renders a Google Map onto the selected jQuery element
 *
 * @date    22/10/19
 * @since   5.8.6
 *
 * @param   jQuery $el The jQuery element.
 * @return  object The map instance.
 */
function initMap( $el ) {

    // Find marker elements within map.
    var $markers = $el.find('.marker');

    // Create gerenic map.
    var mapArgs = {
        zoom        : $el.data('zoom') || 16,
        mapTypeId   : google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map( $el[0], mapArgs );

    // Add markers.
    map.markers = [];
    $markers.each(function(){
        initMarker( $(this), map );
    });

    // Center map based on markers.
    centerMap( map );

    // Return map instance.
    return map;
}

/**
 * initMarker
 *
 * Creates a marker for the given jQuery element and map.
 *
 * @date    22/10/19
 * @since   5.8.6
 *
 * @param   jQuery $el The jQuery element.
 * @param   object The map instance.
 * @return  object The marker instance.
 */
function initMarker( $marker, map ) {

    // Get position from marker.
    var lat = $marker.data('lat');
    var lng = $marker.data('lng');
    var latLng = {
        lat: parseFloat( lat ),
        lng: parseFloat( lng )
    };

    // Create marker instance.
    var marker = new google.maps.Marker({
        position : latLng,
        map: map
    });

    // Append to reference for later use.
    map.markers.push( marker );

    // If marker contains HTML, add it to an infoWindow.
    if( $marker.html() ){

        // Create info window.
        var infowindow = new google.maps.InfoWindow({
            content: $marker.html()
        });

        // Show info window when marker is clicked.
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open( map, marker );
        });
    }
}

/**
 * centerMap
 *
 * Centers the map showing all markers in view.
 *
 * @date    22/10/19
 * @since   5.8.6
 *
 * @param   object The map instance.
 * @return  void
 */
function centerMap( map ) {

    // Create map boundaries from all map markers.
    var bounds = new google.maps.LatLngBounds();
    map.markers.forEach(function( marker ){
        bounds.extend({
            lat: marker.position.lat(),
            lng: marker.position.lng()
        });
    });

    // Case: Single marker.
    if( map.markers.length == 1 ){
        map.setCenter( bounds.getCenter() );

    // Case: Multiple markers.
    } else{
        map.fitBounds( bounds );
    }
}

// Render maps on page load.
$(document).ready(function(){
    $('.acf-map').each(function(){
        var map = initMap( $(this) );
    });
});

})(jQuery);

Add jQuery to your functions.php

If you don’t have jQuery added already to your functions.php file, add it.


function insert_jquery()
{
    wp_enqueue_script('jquery', get_theme_file_uri('/js/jquery-3.5.1.min.js'), null, '3.5.1', false);
}
add_filter('wp_enqueue_scripts', 'insert_jquery', 1);

Add map.js to your functions.php


function maps()
{
    wp_enqueue_script('js-map', get_theme_file_uri('/js/map.js'), null, 1.0, true);
}
add_action('wp_enqueue_scripts', 'maps');

That’s it. Your map is ready now. Let’s render it.

Rendering the map

Render a single marker onto a map



<?php 
$location = get_field('location');
if( $location ): ?>
    <div class="acf-map" data-zoom="16">
        <div class="marker" data-lat="<?php echo esc_attr($location['lat']); ?>" data-lng="<?php echo esc_attr($location['lng']); ?>"></div>
    </div>
<?php endif; ?>


Render multiple markers on a map



<?php if( have_rows('locations') ): ?>
    <div class="acf-map" data-zoom="16">
        <?php while ( have_rows('locations') ) : the_row(); 

            // Load sub field values.
            $location = get_sub_field('location');
            $title = get_sub_field('description');
            $description = get_sub_field('description');
            ?>
            <div class="marker" data-lat="<?php echo esc_attr($location['lat']); ?>" data-lng="<?php echo esc_attr($location['lng']); ?>">
                <h3><?php echo esc_html( $title ); ?></h3>
                <p><em><?php echo esc_html( $location['address'] ); ?></em></p>
                <p><?php echo esc_html( $description ); ?></p>
            </div>
    <?php endwhile; ?>
    </div>
<?php endif; ?>


Display location address details



<?php 
$location = get_field('location');
if( $location ) {

    // Loop over segments and construct HTML.
    $address = '';
    foreach( array('street_number', 'street_name', 'city', 'state', 'post_code', 'country') as $i => $k ) {
        if( isset( $location[ $k ] ) ) {
            $address .= sprintf( '<span class="segment-%s">%s</span>, ', $k, $location[ $k ] );
        }
    }

    // Trim trailing comma.
    $address = trim( $address, ', ' );

    // Display HTML.
    echo '<p>' . $address . '.</p>';
}


You can always checkout the ACF Map docs.

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

What are Conditional Tags in WordPress?WordPressHow to modify navigation menus in WordPress?WordPressPHP Variables ScopePHPHow to convert an HTML radio buttons into a toggle switch using CSS?CSSLearn to make a responsive gallery using CSS Grid and without media queriesCSSThe flex-grow, flex-shrink and flex-basis Properties in CSSCSS