Display Multiple ACF Locations on a Google Map in Divi
By George Nicolaou
The original example combines Advanced Custom Fields location data with a map displayed in Divi. Its main idea is useful: keep location data structured, then build the display from that source.
Check the data first
Confirm the field names and the shape of each location record. Validate latitude and longitude as numeric coordinates. A coordinate of zero can be valid, so a simple “empty” check can accidentally discard a real location.
Review the integration
Use an appropriately restricted map API key and check the provider’s current account and billing requirements. Keep reusable PHP in a maintained plugin or child theme rather than scattering it across page layouts. Escape values when you put them into HTML or JavaScript.
Test more than the happy path
- No locations, one location and several locations.
- Missing coordinates, long addresses and special characters.
- A narrow mobile screen and a slow or unavailable map request.
- Keyboard access and an address list that remains useful without the map.
The code below is the earlier implementation. Compare its hooks and fields with your current installation before adapting it. A text list with addresses and directions links can be a better fallback than an empty map container.
Related guides
<style type="text/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;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDVc887KdBcTyAXWFXdiLcMaE3oBTuQYv8"></script>
<script type="text/javascript">
(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);
</script>
<?php
$location = get_field('map');
//echo "<pre>";
//echo esc_attr($location['lat']);
//echo "</pre>";
if( esc_attr($location['lat']!="0") ): ?>
<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; ?><?php
$location2 = get_field('map3');
//echo "<pre>";
//echo esc_attr($location2['lat']);
//echo "</pre>";
if( esc_attr($location2['lat']!="0") ): ?>
<div class="acf-map" data-zoom="16">
<div class="marker" data-lat="<?php echo esc_attr($location2['lat']); ?>" data-lng="<?php echo esc_attr($location2['lng']); ?>"></div>
</div>
<?php endif; ?>
0 Comments