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

引入Google Map API与Geolocation后地图无法显示的问题

问题分析与修复方案

核心问题

你的代码里有两个关键问题导致地图无法显示:

  1. map容器被覆盖:showPosition函数里先把map元素的innerHTML替换成了经纬度文本,这会清空容器,之后再初始化地图时,容器结构已被破坏,无法正常渲染地图。
  2. map容器无尺寸:Google Maps需要容器有明确的宽高才能渲染,默认<div id="map">没有设置样式,就算初始化成功也会看不见。

另外,无API密钥的警告虽然暂时不影响基础功能,但长期使用建议添加官方API密钥,避免后续功能受限。

修复后的代码

<!DOCTYPE html>
<html>
  <head>
    <title>MY FORM</title>
    <style>
      /* 给map容器设置明确宽高 */
      #map {
        width: 100%;
        height: 400px;
        margin-top: 10px;
      }
    </style>
  </head>
  <body>
    <button onclick="getLocation()">获取位置</button>
    <!-- 新增独立元素显示经纬度,不占用地图容器 -->
    <div id="location-info"></div>
    <div id="map"></div>
    <!-- 替换成你自己的API密钥,去掉无意义的callback参数 -->
    <script
      type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=你的API密钥"
    ></script>
    <script>
      const locationInfo = document.getElementById('location-info')
      const mapContainer = document.getElementById('map')

      function getLocation() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(showPosition)
        } else {
          locationInfo.innerHTML = '该浏览器不支持地理定位功能。'
        }
      }

      function showPosition(position) {
        // 经纬度显示到独立元素,不修改地图容器
        locationInfo.innerHTML =
          '纬度: ' +
          position.coords.latitude +
          '<br>经度: ' +
          position.coords.longitude

        const mapProp = {
          center: new google.maps.LatLng(
            position.coords.latitude,
            position.coords.longitude
          ),
          zoom: 12, // 调高放大级别,显示更清晰
        }
        // 使用未被修改的地图容器初始化地图
        new google.maps.Map(mapContainer, mapProp)
      }
    </script>
  </body>
</html>

关键修改点

  • 新增<div id="location-info">专门显示经纬度,避免破坏地图容器结构。
  • 给#map添加CSS样式,设置明确的宽高。
  • 移除原API链接中无意义的callback=Function.prototype参数,并提示添加个人API密钥。
  • 调整变量命名,让代码逻辑更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:32:57