Introducing our
first WordPress Plugin
Mapbox For Advanced Custom Fields Just £11 + VAT

The Mapbox Map field creates an interactive map with the ability to place a marker. This field features a search input and location finder button to place the marker. The data saved and returned is an array containing the markers lat, lng, and address.

ACF Mapbox Plugin

Easily add ACF Powered Maps to your website using Mapbox

Mapbox requires the registration of an access token to use it’s service. Mapbox offers a Free plan allowing for upto 50,000 map views per month (correct at time of writing).

1
How to Install & Activate Plugin

1. Browse to Plugins
2. Click Add New button
3. Click Upload Plugin
4. Select the Plugin zip file from your computer
5. Click Install Now
6. Once upload has completed, click the Activate Plugin button
7. Done!

2
Settings

Center
Enter a default lat and lng value to center the map on a desired location when no marker has been saved

Zoom
Set the zoom level for this map

Width
Set a custom width for the map

Height
Set a custom width for the map

Styles
Choose one from one ten possible Mapbox styles

Map Marker
Click to enable a marker within the map

Map Marker Popup
Click to enable an info-box to appear when the map marker is clicked

Navigation Control
Click to enable map Zoom and Perspective controls on the side of the map

Static Map
Click to enable a simple static map, not the dynamic, draggable version

3
Mapbox Access Token

Creating a new Access Token
1. Login to your Mapbox account
2. Click Create a token
3. Give your token a name
4. Click Create token
5. Enter your account password
6. Done!

Are you ready to start adding Mapbox maps to your website?
Buy Now
Are you ready to start adding Mapbox maps to your website?

Template Usage

The following code examples show how to display saved values onto a map.

Please also note that the Mapbox access token is required for this to work.

Helpers

The examples below require the following CSS to be available to the page template. Please note that the CSS can be modified to your liking, however they are a good starting point to understand how the PHP data can be translated through HTML into the Mapbox map.

<style type="text/css">
/* Map container */
.mapboxgl-map {
margin: 0 auto 5%;
width: 100%; /* Default map container width */
height: 400px; /* Default map container height */
}

/* Map marker */
.marker {
background-image: url(php echo plugins_url( 'acf-mapbox-gl-js/assets/images/marker-icon.png'); ?>); /* Update the file path according to your theme structure*/
background-size: cover;
width: 41px;
height: 41px;
cursor: pointer;
margin-top: -41px;
}

/* Marker's popup button */
.mapboxgl-popup-close-button {
background-color: #efefef;
width: 25px;
height: 25px;
padding: 0;
color: #999;
}

/* Marker's popup */
.mapboxgl-popup {
max-width: 200px;
top: -41px;
}

.mapboxgl-popup-content {
text-align: center;
font-family: 'Open Sans', sans-serif;
}

#error {
color: #FF0000;
}
</style>

Render a single marker onto a map

<?php $acf_mapbox_static = false; ?>
<?php if (isset($location['acf_mapbox_static'])) $acf_mapbox_static = true; ?>

<?php $name = 'mapbox'; // give your map a name ?>
<?php // Set each map's width and height attributes if specified ?>
<style type="text/css">
#map_<?php echo $name; ?> {
<?php if (isset($location['width']) && !empty($location['width'])): ?>width: <?php echo $location['width']; ?>px;<?php endif;?>
<?php if (isset($location['height']) && !empty($location['height'])): ?>height: <?php echo $location['height']; ?>px;<?php endif;?>
	max-width: 100%;
}
</style>
<!-- Map container with unique ID -->
<div id="map_<?php echo $name; ?>">
<?php 
	if ($acf_mapbox_static):
		$map_width = (isset($location['width']) && !empty($location['width'])) ? $location['width'] : 1280;
		$map_height = (isset($location['height']) && !empty($location['height'])) ? $location['height'] : 600;
		$zoom = isset($location['zoom']) ? $location['zoom'] : '16';
		$lat = $location['lat'];
		$lng = $location['lng'];
		$style = $location["styles"];
		$token = $api['key'];
		$marker = '';
		if (isset($location['enable_marker']) && $location['enable_marker']) {
			$marker = '/pin-l-20+0c248d(' . $lat . ',' . $lng . ')';
		}
		
		$url = 'https://api.mapbox.com/styles/v1/mapbox/' . $style . '/static' . $marker . '/' . $lat . ',' . $lng . ',' . $zoom . '/' . $map_width . 'x' . $map_height . '?access_token=' . $token;
		echo '<img src="' . $url . '" alt="">';
	endif; ?>
</div>
<!-- Check if we don't use static map image -->
<?php if(!$acf_mapbox_static): ?>
<script type="text/javascript">
if (mapboxgl) {
    // Set the access token
    mapboxgl.accessToken = '<?php echo $api['key']; ?>';
    try {
        // Create the map coordinates using the values from the form or from the user's selected location
        var map = new mapboxgl.Map({
            container: 'map_<?php echo $name; ?>',
            zoom: <?php echo (isset($location['zoom'])) ? $location['zoom'] : '16'; ?>,
            center: [<?php echo $location['lat']; ?>, <?php echo $location['lng']; ?>],
            style: 'mapbox://styles/mapbox/<?php echo $location['styles']; ?>'
            });
            <?php // Add the navigation control if it is set to be enabled ?>
            <?php if (isset($location['enable_nav_control']) && $location['enable_nav_control']): ?>
                var navControl = new mapboxgl.NavigationControl();
            map.addControl(navControl, 'top-left');
            <?php endif; ?>
            <?php // Add the marker if it is set to be enabled ?>
            <?php if (isset($location['enable_marker']) && $location['enable_marker']): ?>
            // This GeoJSON will be used to determine where the markers will appear on the map
            var geoJSON = {
            type: 'FeatureCollection',
                features: [{
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: [<?php echo $location['lat']; ?>, <?php echo $location['lng']; ?>]
                    },
                    properties: {
                        title: 'Mapbox',
                        description: '<?php echo $location['address']; ?>'
                    }
                }]
            };
            // Add the marker to map
            geoJSON.features.forEach(function (marker) {
            // Create an HTML element for each feature
            var el = document.createElement('div');
            el.className = 'marker';
            // Make a marker for the feature and add to the map
            var mapMarker = new mapboxgl.Marker(el).setLngLat(marker.geometry.coordinates);
            <?php if (isset($location['enable_marker_popup']) && $location['enable_marker_popup']): ?>
            // Set the popup if the marker popup is set to be enabled
            mapMarker.setPopup(new mapboxgl.Popup({offset: 25}) // adds popup
            .setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>')); // popup HTML
            <?php endif; ?>
            // Add the marker to the map
            mapMarker.addTo(map);
        });
        <?php endif; ?>
    } catch (error) {
    // Log important error message
    console.log(error.message);
    }
}
</script>
<?php endif; ?>
<?php else: ?>
<div style="color: #FF0000; margin: 0 auto; width: 50%; text-align: center;"><?php echo __('Please set the Mapbox access token and make sure to change the ACF field name. For more info, please read the readme.txt file inside the plugin folder.'); ?></div>
<?php endif; ?>

How to add a Mapbox map to your WordPress website

1

Download, install and activate the ACF Mapbox for WordPress Plugin.

2

Copy your Mapbox Access Token from your Mapbox account and add to functions.php

 function acf_mapbox_api($api)
{
    $api['key'] = 'API-KEY-GOES-HERE';

    return $api;
}

add_filter('acf/fields/mapbox/api', 'acf_mapbox_api');

function mapbox_acf_scripts_styles() {
    wp_enqueue_style( 'mapbox-style', '//api.mapbox.com/mapbox-gl-js/v1.4.1/mapbox-gl.css' );
    wp_enqueue_script( 'mapbox-script', '//api.mapbox.com/mapbox-gl-js/v1.4.1/mapbox-gl.js', array(), '1.0.0', false );
}
add_action( 'wp_enqueue_scripts', 'mapbox_acf_scripts_styles' ); 
3

Create a new field within your ACF Field Group for your Mapbox Map and give it a suitable name.

4

Within the (Custom) Post (Type) or Page editor, populate your new Mapbox ACF field with an address.

5

Update your front-end code using the "Template Usage" instructions above to show your Mapbox map on the front-end of your website.

Requirements

Advanced Custom Fields (free) v.4.4+

Advanced Custom Fields (pro) v.5.6+

Mapbox access token

WordPress v.4.9+

Take the next step and upgrade your Advanced Cusom Fields Plugin
Buy Now
Take the next step and upgrade your Advanced Cusom Fields Plugin
logo-200-white

Copyright © 2020
Natural Ranks (Liverpool) Limited
T/A WPbees – Freelance WordPress Developer

  0151 528 3330