Introduction
Advanced Custom Fields (ACF) is a powerful plugin for WordPress that allows developers to easily add custom fields to their websites. When combined with the Google Maps API, ACF can be used to add dynamic markers to a map based on custom field data. In this blog post, we’ll explore how to use ACF fields to add markers to a Google Map in a WordPress theme.
Setting Up ACF Fields
The first step in adding markers to a Google Map is to set up the necessary ACF fields. In this example, we will create a custom post type called “City” and add a location field to it. This location field will store the latitude and longitude coordinates for each city.
- Install and activate the ACF plugin.
- Create a new field group and add a field of type “Google Map”. Name this field “Location”.
- Assign the field group to the “City” custom post type.
This setup allows you to input the geographic coordinates for each city directly from the WordPress admin panel.
Displaying the Map with Markers
Once the ACF fields are set up, we can move on to displaying the map with markers in the front-end of our WordPress site. Below is a code snippet that demonstrates how to query the “City” custom post type and add markers to a Google Map:
This code will render a map with markers for each city post. The latitude and longitude coordinates are retrieved from the ACF location field.
Initializing the Google Map
To make the markers functional, you need to initialize the Google Map and add the markers using JavaScript. Below is a sample JavaScript code that you can include in your theme to achieve this:
<script async src="https://maps.googleapis.com/maps/api/js? key=YOUR_API_KEY&loading=async&callback=initMap"> </script>
(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);
//CSS
.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;
}
This script initializes the Google Map, loops through each marker div, and places a marker on the map at the specified coordinates. The map is then adjusted to fit all the markers within the visible area.
Conclusion
Using ACF fields to add markers to a Google Map in WordPress is a straightforward process that can significantly enhance the functionality and user experience of your website. By following the steps outlined in this blog post, you can easily set up and display dynamic maps with customizable markers based on your custom field data. Happy mapping!