loading...

How to easily add multiple Google Maps markers

avatar

BY Prasetyo Priambodo

{Senior Developer}

18 January 2018

Reading Time: 3 minutes

Last weekend I helped a friend to integrate Google maps into their WordPress site. The idea is to add multiple markers to a custom map, and my first thought is using Advanced Custom Fields (ACF). ACF lets you select a marker easily by address, and you can refine your marker position directly from the map using the drag and drop feature.

ACF has a solid documentation and examples on how to do it, as you can see here. If you follow the instructions correctly, it’s straightforward. Well, I will show you how to add multiple markers to a WordPress site using ACF.

Get Google Maps API Key

To use Google Maps into your application, you need API KEY where you can download here. Once you have your key, please put this code into your functions.php

// Google Maps API Key
add_action('acf/init', 'digitalnoir_acf_init');
function digitalnoir_acf_init() {
	acf_update_setting('google_api_key', 'REPLACE_WITH_YOUR_KEY');
}

Prepare the field in the backend

In this tutorial I want my maps to appear on the Contact page, so let’s create a field for the contact page only. I’m using ACF Pro so I will create the field using a repeater field, the setting as below:

Add your data

Now go to contact page and add your markers…as many as you want!

That’s it, your setup on the backend is done. Now, let’s render your data into a working map.

Create a page template

To create a page template with WordPress is very simple, you just need to generate a file with name page-contact.php and insert this line of code:

<?php
/**
* Template Name: Contact Page
*/

get_header(); 

    $_markers = get_field('map_markers');
    if(is_array($_markers)){
        echo '<div class="acf-map" style="height:500px;width:100%">';
        foreach($_markers as $value){
            
            $marker_location    = $value['marker']; // map marker data
            $marker_description = $value['description']; // map marker description
        ?>

            <div class="marker" data-lat="<?php echo $marker_location['lat']; ?>" data-lng="<?php echo $marker_location['lng']; ?>">
                <?php echo $marker_description ?>
            </div>
        <?php
        }
        echo '</div>'; // .acf-map
    }

get_footer();

Creating Javascript to render the code

Create a new file in your javascript directory called maps.js and registering your file using the wp_enqueue_scripts function. Please put this code into functions.php

// Registering script
add_action( 'wp_enqueue_scripts', 'digitalnoir_enqueue_scripts' ); 
function digitalnoir_enqueue_scripts() {    
	wp_enqueue_script('js-google', '//maps.googleapis.com/maps/api/js?key=REPLACE_WITH_YOUR_KEY, null, null);
	wp_enqueue_script('js-maps', get_stylesheet_directory_uri() . '/js/maps.js', array('jquery'), null, true);     
}

Now let’s open the maps.js file and put in this line of code:

(function($) {
    // generate map
    function new_map($el) {
        // var
        var $markers = $el.find('.marker');
        // vars
        var args = {
            zoom: 16,
            center: new google.maps.LatLng(0, 0),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        // create map	        	
        var map = new google.maps.Map($el[0], args);
        // add a markers reference
        map.markers = [];
        // add markers
        $markers.each(function() {
            add_marker($(this), map);
        });
        // center map
        center_map(map);
        return map;
    }
    // add the marker
    function add_marker($marker, map) {
        // var
        var latlng = new google.maps.LatLng($marker.attr('data-lat'), $marker.attr('data-lng'));
        // create marker
        var marker = new google.maps.Marker({
            position: latlng,
            map: map
        });
        // add to array
        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);
            });
        }
    }
    // center the map
    function center_map(map) {
        // vars
        var bounds = new google.maps.LatLngBounds();
        // loop through all markers and create bounds
        $.each(map.markers, function(i, marker) {
            var latlng = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
            bounds.extend(latlng);
        });
        // only 1 marker?
        if (map.markers.length == 1) {
            // set center of map
            map.setCenter(bounds.getCenter());
            map.setZoom(16);
        } else {
            // fit to bounds
            map.fitBounds(bounds);
        }
    }
    // embed it
    var map = null;
    $(document).ready(function() {
        $('.acf-map').each(function() {
            // create map
            map = new_map($(this));
        });
    });
})(jQuery);

Tadaa! You have been successfully embedded Google Maps with multiple location markers!

Want to get up and running with a new WordPress website, we’re here to help. Get in touch for a chat!

Like what you see?
Subscribe now to receive regular updates

ABOUT THE AUTHOR

Prasetyo Priambodo

Pras basically has a black belt in Wordpress. He weaves our designs into beautiful code. He also has a great eye for design but is not quick to admit it!!

avatar
MORE ARTICLES LIKE THIS