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

如何在JavaScript中通过可拖拽Google Maps标记保存经纬度至变量(Jsfiddle)

解决方案:单个可拖拽标记并保存经纬度到JavaScript变量

没问题,我帮你调整了代码,去掉了多余的第二个标记,同时添加了逻辑来在拖动标记时把经纬度保存到JavaScript变量里。下面是修改后的完整代码,你可以直接在JSFiddle中使用:

<!DOCTYPE html>
<title>Single Draggable Marker with Lat/Lon Storage</title>
<style>
  #map {
    height: 400px;
    width: 100%;
  }
  #floating-panel {
    position: absolute;
    top: 10px;
    left: 25%;
    z-index: 5;
    background-color: #fff;
    padding: 5px;
    border: 1px solid #999;
    text-align: center;
    font-family: Arial, sans-serif;
    line-height: 30px;
    padding-left: 10px;
  }
</style>
<body>
<div id="map"></div>
<div id="floating-panel">
  Current Latitude: <input type="text" readonly id="current-lat">
  Current Longitude: <input type="text" readonly id="current-lng">
</div>
<script>
// 全局变量存储当前标记的经纬度
let currentLat, currentLng;
let marker;

function initMap() {
  const map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: { lat: 37.983810, lng: 23.727539 }
  });

  // 创建单个可拖拽标记
  marker = new google.maps.Marker({
    map: map,
    draggable: true,
    position: { lat: 38.017973, lng: 23.694077 }
  });

  // 初始化变量值
  updateLatLng(marker.getPosition());

  // 监听标记位置变化事件
  google.maps.event.addListener(marker, 'position_changed', () => {
    updateLatLng(marker.getPosition());
  });
}

// 更新经纬度变量和显示输入框
function updateLatLng(position) {
  currentLat = position.lat();
  currentLng = position.lng();
  
  // 更新页面输入框显示,方便验证
  document.getElementById('current-lat').value = currentLat.toFixed(6);
  document.getElementById('current-lng').value = currentLng.toFixed(6);
  
  // 这里可以添加你需要的其他逻辑,比如使用currentLat和currentLng做后续处理
  console.log('当前经纬度:', currentLat, currentLng);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBojvE89boyOqT01eKQd-UV_Dc4dpLRpzw&callback=initMap" async defer></script>
</body>

关键修改说明:

  • 新增了全局变量 currentLat 和 currentLng,用来存储标记的实时经纬度
  • 移除了原来的第二个标记、折线以及相关的计算逻辑,只保留单个可拖拽标记
  • 添加了 updateLatLng 函数,负责更新变量值并同步到页面输入框,你也可以在这个函数里添加其他需要使用经纬度的业务逻辑
  • 修复了原代码中Google Maps API链接的语法错误(缺少了?分隔符)
  • 调整了地图初始缩放级别,让标记显示更清晰

现在当你拖动标记时,currentLat 和 currentLng 会自动更新为最新的经纬度值,同时页面上的输入框也会实时显示这些值,控制台也会打印出当前坐标方便调试。

内容的提问来源于stack exchange,提问作者Irini K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:12:02