Hello,
I’ve recently implemented a Mapbox globe with the help of this tutorial.
Got a great result but now I can’t seem to crack the next challenge.
The yellow dots represent various CMS locations (coordinates get pulled from the CMS), and I would like to display the rest of the location information (i.e. name, description, images, etc.) in the left column once a location gets clicked.
Here is the piece of code that makes the map run and displays the dots.
<!-- Mapbox with CMS markers -->
<script>
// Replace with your own Mapbox access token
mapboxgl.accessToken = 'pk.eyJ1Ij....';
// Get the location data from the displayed elements
const getLocationData = () => {
const locationElements = document.querySelectorAll('#location-data .location');
const locations = [];
locationElements.forEach(element => {
const id = element.getAttribute('data-id');
const lat = parseFloat(element.getAttribute('data-lat'));
const lng = parseFloat(element.getAttribute('data-lng'));
if (!isNaN(lat) && !isNaN(lng)) {
locations.push({ id, lat, lng });
}
});
return locations;
};
// Initialize the map
const initializeMap = () => {
const locations = getLocationData();
if (locations.length === 0) {
console.error('No locations found.');
return;
}
const map = new mapboxgl.Map({
container: 'map',
// You can change the style url below with your own style from Mapbox
style: 'mapbox://styles/...',
center: [24.115625, 56.946203],
zoom: 5.5
});
map.addControl(new mapboxgl.NavigationControl());
locations.forEach(location => {
const markerElement = document.createElement('div');
markerElement.className = 'marker';
const marker = new mapboxgl.Marker({
element: markerElement,
anchor: 'bottom' // Set the anchor point to bottom
})
.setLngLat([location.lng, location.lat])
.addTo(map);
markerElement.addEventListener('click', () => {
console.log('Marker clicked:', location.id);
map.flyTo({ center: [location.lng, location.lat], zoom: 16 });
});
});
};
// Call the function to initialize the map
initializeMap();
</script>
So far, I tried updating the code to include other CMS item attributes, but it seems like attributes can’t pull Rich Text and image fields, which I need for this use case.
I suspect that the solution may involve an Embed element in some form but unfortunately haven’t found a good approach yet.
Thanks!