OpenStreetMap

A fully functional interactive map field using Leaflet.js and Nominatim geocoding. Editors search for an address or click the map to place markers. No Google Maps API key or billing account required.

Pro field

OpenStreetMap requires the Extra Fields for ACF Pro license.

Settings

SettingDefaultOptionsDescription
Modesinglesingle · multiplesingle allows one marker. multiple allows any number of named markers.
Default Latitude51.505DecimalMap center latitude when first loaded.
Default Longitude-0.09DecimalMap center longitude when first loaded.
Default Zoom13318Initial zoom level.
Map Height400Integer (px)Height of the map canvas in pixels.
Max Markers0IntegerMaximum markers in multiple mode. 0 = unlimited.
Tile Themeosmosm · cartodb · satelliteMap tile style.
Return Formatobjectobject · latlng · addressWhat get_field() returns.

Return values

return_format: 'object'

$map = get_field('office_location');
// [
//   'lat'     => 51.5074,
//   'lng'     => -0.1278,
//   'zoom'    => 13,
//   'address' => 'Westminster, London, UK',
//   'markers' => [
//     ['lat' => 51.5074, 'lng' => -0.1278, 'label' => 'HQ'],
//   ],
// ]

return_format: 'latlng'

$coords = get_field('office_location');
// ['lat' => 51.5074, 'lng' => -0.1278]

return_format: 'address'

$address = get_field('office_location');
// "Westminster, London, UK"

Usage

Rendering a Leaflet map on the frontend

$map = get_field('office_location');

if ($map) {
    $lat  = esc_attr($map['lat']);
    $lng  = esc_attr($map['lng']);
    $zoom = esc_attr($map['zoom']);

    wp_enqueue_script('leaflet', 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js', [], null, true);
    wp_enqueue_style('leaflet', 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css');

    echo '<div id="map" style="height: 400px;"></div>';
    echo "<script>
        document.addEventListener('DOMContentLoaded', function() {
            var map = L.map('map').setView([{$lat},{$lng}], {$zoom});
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);";

    foreach ($map['markers'] as $marker) {
        $mlat   = esc_js($marker['lat']);
        $mlng   = esc_js($marker['lng']);
        $mlabel = esc_js($marker['label'] ?? '');
        echo "L.marker([{$mlat},{$mlng}]).addTo(map).bindPopup('{$mlabel}');";
    }

    echo "});
    </script>";
}
$coords = get_field('branch_location'); // return_format: 'latlng'

if ($coords) {
    $query = $coords['lat'] . ',' . $coords['lng'];
    echo '<a href="https://maps.google.com/?q=' . esc_attr($query) . '" target="_blank" rel="noopener">Get directions</a>';
}

Displaying address text

$address = get_field('store_location'); // return_format: 'address'
if ($address) {
    echo '<p>' . esc_html($address) . '</p>';
}