#181 - Dynamic Google Maps With CMS Location Pins v0.1
Display CMS locations on a dynamic Google Map with interactive pins and info windows.
<!-- 💙 MEMBERSCRIPT #181 v.01 - DYNAMIC GOOGLE MAPS WITH CMS LOCATION PINS 💙 -->
<script>
document.addEventListener('DOMContentLoaded', function() {
console.log('Dynamic Google Maps with CMS data loaded!');
// Configuration - Customize these values as needed
const config = {
// Map settings
defaultZoom: 10,
defaultCenter: { lat: 40.7128, lng: -74.0060 }, // New York City as default
mapTypeId: 'roadmap', // roadmap, satellite, hybrid, terrain
mapId: "df5b64a914f0e2d26021bc7d", // Set to your Map ID for Advanced Markers (optional but recommended)
// Marker settings
markerIcon: null, // Set to custom icon URL if desired
markerAnimation: 'DROP', // DROP, BOUNCE, or null
// Info window settings
infoWindowMaxWidth: 300,
infoWindowPixelOffset: { width: 0, height: -30 },
// Data attributes
mapContainerAttr: 'map-container',
locationItemAttr: 'location-item',
locationNameAttr: 'location-name',
locationAddressAttr: 'location-address',
locationLatAttr: 'location-lat',
locationLngAttr: 'location-lng',
locationDescriptionAttr: 'location-description'
};
// Initialize the dynamic map
function initializeDynamicMap() {
const mapContainer = document.querySelector(`[data-ms-code="${config.mapContainerAttr}"]`);
if (!mapContainer) {
console.log('No map container found with data-ms-code="map-container"');
return;
}
console.log('Initializing dynamic map...');
// Set map container dimensions
mapContainer.style.width = config.mapWidth;
mapContainer.style.height = config.mapHeight;
mapContainer.style.borderRadius = '8px';
mapContainer.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
// Load Google Maps API if not already loaded
if (typeof google === 'undefined' || !google.maps) {
loadGoogleMapsAPI();
} else {
createMap();
}
}
// Load Google Maps API
function loadGoogleMapsAPI() {
// Check if script is already being loaded
if (document.querySelector('script[src*="maps.googleapis.com"]')) {
console.log('Google Maps API already loading...');
return;
}
console.log('Loading Google Maps API...');
const script = document.createElement('script');
script.src = `https://maps.googleapis.com/maps/api/js?key=${getGoogleMapsAPIKey()}&libraries=marker&loading=async&callback=initDynamicMap`;
script.async = true;
script.defer = true;
script.onerror = function() {
console.error('Failed to load Google Maps API');
showMapError('Failed to load Google Maps. Please check your API key.');
};
document.head.appendChild(script);
// Make initDynamicMap globally available
window.initDynamicMap = createMap;
}
// Get Google Maps API key from data attribute or environment
function getGoogleMapsAPIKey() {
const mapContainer = document.querySelector(`[data-ms-code="${config.mapContainerAttr}"]`);
const apiKey = mapContainer?.getAttribute('data-api-key') ||
document.querySelector('[data-ms-code="google-maps-api-key"]')?.value ||
'YOUR_GOOGLE_MAPS_API_KEY'; // Replace with your actual API key
if (apiKey === 'YOUR_GOOGLE_MAPS_API_KEY') {
console.warn('Please set your Google Maps API key in the map container or form field');
showMapError('Google Maps API key not configured. Please contact the administrator.');
}
return apiKey;
}
// Create the map with CMS data
function createMap() {
const mapContainer = document.querySelector(`[data-ms-code="${config.mapContainerAttr}"]`);
if (!mapContainer) {
console.error('Map container not found');
return;
}
console.log('Creating map with CMS data...');
// Get location data from CMS
const locations = getLocationDataFromCMS();
if (locations.length === 0) {
console.log('No location data found in CMS');
showMapError('No locations found. Please add location data to your CMS.');
return;
}
console.log(`Found ${locations.length} locations:`, locations);
// Calculate map center based on locations
const mapCenter = calculateMapCenter(locations);
// Initialize the map
const mapOptions = {
center: mapCenter,
zoom: config.defaultZoom,
mapTypeId: config.mapTypeId,
styles: getMapStyles(), // Custom map styling
gestureHandling: 'cooperative', // Require Ctrl+scroll to zoom
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
rotateControl: true,
fullscreenControl: true
};
// Add Map ID if provided (recommended for Advanced Markers)
if (config.mapId) {
mapOptions.mapId = config.mapId;
}
const map = new google.maps.Map(mapContainer, mapOptions);
// Create markers for each location
const markers = [];
const bounds = new google.maps.LatLngBounds();
locations.forEach((location, index) => {
const marker = createLocationMarker(map, location, index);
markers.push(marker);
// AdvancedMarkerElement uses position property instead of getPosition() method
bounds.extend(marker.position);
});
// Fit map to show all markers
if (locations.length > 1) {
map.fitBounds(bounds);
// Ensure minimum zoom level
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
if (map.getZoom() > 15) {
map.setZoom(15);
}
});
}
console.log('Map created successfully with', markers.length, 'markers');
}
// Get location data from CMS elements
function getLocationDataFromCMS() {
const locationItems = document.querySelectorAll(`[data-ms-code="${config.locationItemAttr}"]`);
const locations = [];
locationItems.forEach((item, index) => {
const name = getElementText(item, config.locationNameAttr);
const address = getElementText(item, config.locationAddressAttr);
const lat = parseFloat(getElementText(item, config.locationLatAttr));
const lng = parseFloat(getElementText(item, config.locationLngAttr));
const description = getElementText(item, config.locationDescriptionAttr);
// Validate coordinates
if (isNaN(lat) || isNaN(lng)) {
console.warn(`Invalid coordinates for location ${index + 1}:`, { lat, lng });
return;
}
// Validate coordinate ranges
if (lat < -90 || lat > 90 || lng < -180 || lng > 180) {
console.warn(`Coordinates out of range for location ${index + 1}:`, { lat, lng });
return;
}
locations.push({
name: name || `Location ${index + 1}`,
address: address || '',
lat: lat,
lng: lng,
description: description || '',
index: index
});
});
return locations;
}
// Helper function to get text content from nested elements
function getElementText(parent, attribute) {
const element = parent.querySelector(`[data-ms-code="${attribute}"]`);
return element ? element.textContent.trim() : '';
}
// Calculate map center based on locations
function calculateMapCenter(locations) {
if (locations.length === 0) {
return config.defaultCenter;
}
if (locations.length === 1) {
return { lat: locations[0].lat, lng: locations[0].lng };
}
// Calculate average coordinates
const totalLat = locations.reduce((sum, loc) => sum + loc.lat, 0);
const totalLng = locations.reduce((sum, loc) => sum + loc.lng, 0);
return {
lat: totalLat / locations.length,
lng: totalLng / locations.length
};
}
// Create a marker for a location
function createLocationMarker(map, location, index) {
const position = { lat: location.lat, lng: location.lng };
// CHANGE MARKER CONTENT ELEMENT
const markerContent = document.createElement('div');
markerContent.style.cssText = `
width: 32px;
height: 32px;
background-color: #4285f4;
border: 2px solid #ffffff;
border-radius: 50%;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: transform 0.2s ease;
`;
// Add custom icon if specified
if (config.markerIcon) {
markerContent.style.backgroundImage = `url(${config.markerIcon})`;
markerContent.style.backgroundSize = 'cover';
markerContent.style.backgroundPosition = 'center';
markerContent.style.backgroundColor = 'transparent';
markerContent.style.border = 'none';
} else {
// Add default pin icon
const pinIcon = document.createElement('div');
pinIcon.style.cssText = `
width: 8px;
height: 8px;
background-color: #ffffff;
border-radius: 50%;
`;
markerContent.appendChild(pinIcon);
}
// Add hover effect
markerContent.addEventListener('mouseenter', function() {
this.style.transform = 'scale(1.1)';
});
markerContent.addEventListener('mouseleave', function() {
this.style.transform = 'scale(1)';
});
// Create AdvancedMarkerElement
const marker = new google.maps.marker.AdvancedMarkerElement({
position: position,
map: map,
title: location.name,
content: markerContent
});
// Create info window content
const infoWindowContent = createInfoWindowContent(location);
// Add click event to marker
marker.addListener('click', function() {
// Close any existing info windows
closeAllInfoWindows();
// Create and open info window
const infoWindow = new google.maps.InfoWindow({
content: infoWindowContent,
maxWidth: config.infoWindowMaxWidth,
pixelOffset: config.infoWindowPixelOffset
});
infoWindow.open(map, marker);
// Store reference for closing
window.currentInfoWindow = infoWindow;
});
return marker;
}
// Create info window content
function createInfoWindowContent(location) {
let content = `<div style="padding: 10px; font-family: Arial, sans-serif;">`;
if (location.name) {
content += `<h3 style="margin: 0 0 8px 0; color: #333; font-size: 16px;">${escapeHtml(location.name)}</h3>`;
}
if (location.address) {
content += `<p style="margin: 0 0 8px 0; color: #666; font-size: 14px;">${escapeHtml(location.address)}</p>`;
}
if (location.description) {
content += `<p style="margin: 0; color: #555; font-size: 13px; line-height: 1.4;">${escapeHtml(location.description)}</p>`;
}
content += `</div>`;
return content;
}
// Close all info windows
function closeAllInfoWindows() {
if (window.currentInfoWindow) {
window.currentInfoWindow.close();
window.currentInfoWindow = null;
}
}
// Escape HTML to prevent XSS
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Custom map styles (optional)
function getMapStyles() {
return [
{
featureType: 'poi',
elementType: 'labels',
stylers: [{ visibility: 'off' }]
},
{
featureType: 'transit',
elementType: 'labels',
stylers: [{ visibility: 'off' }]
}
];
}
// Show error message
function showMapError(message) {
const mapContainer = document.querySelector(`[data-ms-code="${config.mapContainerAttr}"]`);
if (mapContainer) {
mapContainer.innerHTML = `
<div style="
display: flex;
align-items: center;
justify-content: center;
height: ${config.mapHeight};
background: #f8f9fa;
border: 2px dashed #dee2e6;
border-radius: 8px;
color: #6c757d;
font-family: Arial, sans-serif;
text-align: center;
padding: 20px;
">
<div>
<div style="font-size: 24px; margin-bottom: 10px;">🗺️</div>
<div style="font-size: 14px;">${message}</div>
</div>
</div>
`;
}
}
// Initialize the map
initializeDynamicMap();
// Debug function
window.debugDynamicMap = function() {
console.log('=== Dynamic Map Debug Info ===');
console.log('Map container:', document.querySelector(`[data-ms-code="${config.mapContainerAttr}"]`));
console.log('Location items:', document.querySelectorAll(`[data-ms-code="${config.locationItemAttr}"]`));
console.log('CMS locations:', getLocationDataFromCMS());
console.log('Google Maps loaded:', typeof google !== 'undefined' && !!google.maps);
console.log('Config:', config);
};
});
</script>
Customer Showcase
Have you used a Memberscript in your project? We’d love to highlight your work and share it with the community!
Erstellen des Make.com-Szenarios
1. Laden Sie den JSON-Blaupause unten, um angegeben zu bekommen.
2. Navigieren Sie zu Make.com und erstellen Sie ein neues Szenario...

3. Klicken Sie auf das kleine Kästchen mit den 3 Punkten und dann auf Blaupause importieren...

4. Laden Sie Ihre Datei hoch und voila! Sie sind bereit, Ihre eigenen Konten zu verknüpfen.
Brauchen Sie Hilfe mit diesem MemberScript?
Alle Memberstack-Kunden können im 2.0 Slack um Unterstützung bitten. Bitte beachten Sie, dass dies keine offiziellen Funktionen sind und der Support nicht garantiert werden kann.
Treten Sie dem 2.0 Slack beiAutorisierung und Zahlungen für Webflow-Websites
Fügen Sie Ihrer Webflow-Website Logins, Abonnements, Gated Content und vieles mehr hinzu - einfach und vollständig anpassbar.
.webp)
"Wir verwenden Memberstack schon seit langem, und Es hat uns geholfen, Dinge zu erreichen, die wir mit Webflow nie für möglich gehalten hätten. Es hat uns ermöglicht, Plattformen mit großer Tiefe und Funktionalität zu bauen, und das Team dahinter war immer sehr hilfsbereit und offen für Feedback.

"Ich habe eine Mitgliedschaftsseite mit Memberstack und Jetboost für einen Kunden erstellt. Es fühlt sich wie Magie an, mit diesen Tools zu bauen. Als jemand, der in einer Agentur gearbeitet hat, wo einige dieser Anwendungen von Grund auf neu programmiert wurden, verstehe ich jetzt endlich den Hype. Das ist viel schneller und viel billiger."

"Eines der besten Produkte, um eine Mitgliederseite zu starten - ich mag die Benutzerfreundlichkeit von Memberstack. Ich war in der Lage, meine Mitgliederseite innerhalb eines Tages einzurichten und zu betreiben.. Einfacher geht's nicht. Außerdem bietet es die Funktionalität, die ich brauche, um die Benutzererfahrung individueller zu gestalten."

"Mein Geschäft wäre ohne Memberstack nicht das, was es ist. Wenn Sie denken, dass $30/Monat teuer sind, versuchen Sie mal, einen Entwickler zu engagieren, der für diesen Preis individuelle Empfehlungen in Ihre Website integriert. Unglaublich flexible Tools für diejenigen, die bereit sind, einige minimale Anstrengungen zu unternehmen und die gut zusammengestellte Dokumentation zu lesen."


"Die Slack-Community ist eine der aktivsten, die ich kenne, und andere Kunden sind bereit, Fragen zu beantworten und Lösungen anzubieten. Ich habe ausführliche Bewertungen von alternativen Tools durchgeführt und wir kommen immer wieder auf Memberstack zurück - sparen Sie sich die Zeit und probieren Sie es aus."

Brauchen Sie Hilfe mit diesem MemberScript? Treten Sie unserer Slack-Community bei!
Treten Sie der Memberstack-Community Slack bei und fragen Sie los! Erwarten Sie eine prompte Antwort von einem Team-Mitglied, einem Memberstack-Experten oder einem anderen Community-Mitglied.
Unserem Slack beitreten