You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过单选按钮控制Google Maps显示(默认隐藏,指定选项触发)

Solution to Toggle Google Maps Visibility with Radio Buttons

Let's walk through how to set this up properly—making sure the map stays hidden by default and only appears when your target radio buttons are selected.

First, update your HTML to include a hidden map container:

<div>
  <input type="radio" name="reception" value="livraison"> Livraison
</div>
<div>
  <input type="radio" name="reception" value="point"> Point de récupération
</div>
<!-- Map container hidden by default with basic styling -->
<div id="map" style="display: none; height: 400px; width: 100%; margin-top: 1rem;"></div>

Next, add the Google Maps API script (replace YOUR_API_KEY with your actual key from the Google Cloud Console):

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>

Now, the JavaScript to handle initialization and radio button interactions:

let map;

// Initialize the map (it will stay hidden until triggered)
function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 48.8566, lng: 2.3522 }, // Default to Paris—adjust to your needs
    zoom: 12,
  });
}

// Add event listeners to the radio buttons
document.querySelectorAll('input[name="reception"]').forEach(radio => {
  radio.addEventListener('change', function() {
    const mapContainer = document.getElementById('map');
    
    if (this.checked) {
      // Show the map
      mapContainer.style.display = 'block';
      // Fix rendering issues by triggering a map resize (critical for hidden containers)
      google.maps.event.trigger(map, 'resize');
      // Re-center the map to ensure it's in view
      map.setCenter({ lat: 48.8566, lng: 2.3522 });
    } else {
      // Hide the map if another option is selected (though radio buttons only allow one selection)
      mapContainer.style.display = 'none';
    }
  });
});

Key Tips:

  • The display: none on the map container ensures it's hidden initially.
  • The resize trigger fixes a common issue where maps don't render correctly after being hidden—this forces Google Maps to recalculate its dimensions.
  • If you want to save on initial load time, you can lazy-load the API only when a radio button is clicked for the first time. Here's that alternative:
let map;
let mapApiLoaded = false;

document.querySelectorAll('input[name="reception"]').forEach(radio => {
  radio.addEventListener('change', function() {
    const mapContainer = document.getElementById('map');
    
    if (this.checked) {
      mapContainer.style.display = 'block';
      
      if (!mapApiLoaded) {
        // Dynamically inject the Google Maps script
        const script = document.createElement('script');
        script.src = 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap';
        script.async = true;
        script.defer = true;
        document.body.appendChild(script);
        mapApiLoaded = true;
      } else {
        // Refresh the map if it's already loaded
        google.maps.event.trigger(map, 'resize');
        map.setCenter({ lat: 48.8566, lng: 2.3522 });
      }
    } else {
      mapContainer.style.display = 'none';
    }
  });
});

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 48.8566, lng: 2.3522 },
    zoom: 12,
  });
}

内容的提问来源于stack exchange,提问作者Barbell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:10:43