class ThemeMapBlock {
/**
* Create and initialise objects of this class
* @param {object} block
*/
constructor(block) {
this.block = block;
this.init();
}
/**
* Example function to run class logic
* Can access `this.block`
*/
init() {
const lazyLoadMap = (block) => {
const io = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.initMap(block);
io.disconnect(); // ensures map loads only once
}
});
}, { threshold: [0.7] });
io.observe(block);
}
lazyLoadMap(this.block);
}
initMap( block ) {
if ( ! mapboxgl ) {
console.error( mapboxgl );
return;bb
}
const mapContainer = block.querySelector( '.block-map-block__map-container' );
// Create a new token - https://account.mapbox.com/
mapboxgl.accessToken = 'pk.eyJ1Ijoic3RyYXRlZ2lxIiwiYSI6ImNtajJxNjUwbzBzMXgzbHNma3hjOXRkZWgifQ.TVPB8Q2vZDjBKp7AcGAK-w';
let lng = parseFloat( mapContainer.getAttribute('data-lng') );
let lat = parseFloat( mapContainer.getAttribute('data-lat') );
let zoom = parseFloat( mapContainer.getAttribute('data-zoom') );
let pinIcon = mapContainer.dataset.pinicon;
let company = mapContainer.dataset.company;
let companyAddress = mapContainer.dataset.companyaddress || mapContainer.dataset.address;
let address = mapContainer.dataset.address;
this.map = new mapboxgl.Map({
container: mapContainer,
style: 'mapbox://styles/mapbox/streets-v11',
center: [lng, lat],
zoom: zoom,
cooperativeGestures: true,
});
const popupHTML = `
`;
let marker;
if (pinIcon) {
const el = document.createElement('div');
el.className = 'custom-marker';
el.style.backgroundImage = `url(${pinIcon})`;
el.style.width = '40px';
el.style.height = '40px';
el.style.backgroundSize = 'cover';
el.style.cursor = 'pointer';
marker = new mapboxgl.Marker(el)
.setLngLat([lng, lat])
.setPopup(new mapboxgl.Popup().setHTML(popupHTML)); // shows on click
}
else {
marker = new mapboxgl.Marker({ color: "#FF2C31" })
.setLngLat([lng, lat])
.setPopup(new mapboxgl.Popup().setHTML(popupHTML));
}
marker.addTo(this.map);
// Add zoom and rotation controls to the map.
this.map.addControl( new mapboxgl.NavigationControl() );
}
}
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.block-map-block').forEach( block => new ThemeMapBlock(block) );
});
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 2,
"name": "strategiq/map-block",
"title": "Map block",
"description": "Map block",
"category": "strategiq",
"icon": "strategiq",
"acf": {
"mode": "preview",
"renderTemplate": "block-map-block.php"
},
"supports": {
"anchor": true,
"align": false,
"mode":false,
"color": {
"background": false,
"text": false,
"gradients": false
},
"spacing": {
"padding": [
"top",
"bottom"
],
"margin": [
"top",
"bottom"
]
}
},
"style": "file:../../assets/css/map-block/block-map.css"
}