如何在div class而非id中嵌入并显示Google Map?
Got it, let's fix this up for you! The core adjustment here is switching the target element selector from an ID to a class, since you want the map to load into the <div class="custom-gmap-class"></div> instead of the ID-based container. Here's how to do it properly:
Step 1: Update the Map Initialization Code
First, modify the JavaScript that initializes your Google Map. Instead of using getElementById() (which targets a unique ID), use querySelector() (for a single class instance) or querySelectorAll() (if you have multiple map containers with the same class).
Example for a Single Map Container
If you only have one .custom-gmap-class div on your page:
function initMap() { // Target the class-based container const mapContainer = document.querySelector('.custom-gmap-class'); // Always check if the element exists to avoid errors if (mapContainer) { const map = new google.maps.Map(mapContainer, { center: { lat: -34.397, lng: 150.644 }, // Replace with your desired coordinates zoom: 8, // Adjust zoom level as needed }); } }
Example for Multiple Map Containers
If you have multiple divs with custom-gmap-class and want a map in each:
function initMap() { // Get all elements with the target class const mapContainers = document.querySelectorAll('.custom-gmap-class'); mapContainers.forEach((container, index) => { // You can customize each map's settings (e.g., unique center points) const customCenter = { lat: -34.397 + (index * 0.1), lng: 150.644 + (index * 0.1) }; new google.maps.Map(container, { center: customCenter, zoom: 8, }); }); }
Step 2: Verify Your HTML Structure
Make sure your HTML includes the class-based div (and set a height/width so the map is visible):
<!-- Replace the old ID-based div with this --> <div class="custom-gmap-class" style="width: 100%; height: 400px;"></div>
Step 3: Ensure Google Maps API is Loaded Correctly
Double-check that your Google Maps API script is properly linked with the callback pointing to your initialization function:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
(Don't forget to replace YOUR_API_KEY with your actual Google Maps API key.)
That's it! This will render your Google Map in the class-based div instead of the ID-based one.
内容的提问来源于stack exchange,提问作者clap

