Store Location Map Block
Shortcode that embeds an OpenStreetMap tile map with a configurable address marker and info popup.
Module3 parts · by SnipCraft
PHPLogic
php
<?php
if ( ! function_exists( 'scseed_store_map_shortcode' ) ) {
function scseed_store_map_shortcode( $atts ) {
static $instance = 0;
$instance++;
$atts = shortcode_atts( array(
'lat' => '40.7128',
'lng' => '-74.0060',
'zoom' => '14',
'height' => '380',
'name' => 'Our Store',
'address' => '',
), $atts, 'store_map' );
$lat = floatval( $atts['lat'] );
$lng = floatval( $atts['lng'] );
$zoom = max( 1, min( 19, absint( $atts['zoom'] ) ) );
$height = absint( $atts['height'] );
$name = esc_html( $atts['name'] );
$address = esc_html( $atts['address'] );
$map_id = 'scseed-map-' . $instance;
ob_start();
?>
<div id="<?php echo esc_attr( $map_id ); ?>" class="scseed-store-map"
style="height:<?php echo $height; ?>px"
data-lat="<?php echo esc_attr( $lat ); ?>"
data-lng="<?php echo esc_attr( $lng ); ?>"
data-zoom="<?php echo esc_attr( $zoom ); ?>"
data-name="<?php echo esc_attr( $name ); ?>"
data-address="<?php echo esc_attr( $address ); ?>">
</div>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="">
<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV/XN/WLs=" crossorigin="" defer></script>
<?php
return ob_get_clean();
}
add_shortcode( 'store_map', 'scseed_store_map_shortcode' );
}CSSStyles
css
.scseed-store-map {
width: 100%;
border-radius: 10px;
overflow: hidden;
border: 1px solid #e2e8f0;
margin: 1rem 0;
z-index: 0;
position: relative;
}JavaScriptScript
js
(function () {
function initMaps() {
if (typeof L === 'undefined') return;
document.querySelectorAll('.scseed-store-map').forEach(function (el) {
if (el.dataset.init) return;
el.dataset.init = '1';
var lat = parseFloat(el.dataset.lat);
var lng = parseFloat(el.dataset.lng);
var zoom = parseInt(el.dataset.zoom, 10);
var name = el.dataset.name;
var addr = el.dataset.address;
var map = L.map(el).setView([lat, lng], zoom);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
maxZoom: 19
}).addTo(map);
var marker = L.marker([lat, lng]).addTo(map);
var popup = '<strong>' + name + '</strong>';
if (addr) popup += '<br>' + addr;
marker.bindPopup(popup).openPopup();
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function () { setTimeout(initMaps, 200); });
} else {
setTimeout(initMaps, 200);
}
window.addEventListener('load', initMaps);
})();#shortcode#location#map#openstreetmap#store