【问题标题】:How to get Google Maps API v3 to listen for dragend event and populate form field on drop?如何让 Google Maps API v3 监听 dragend 事件并在放置时填充表单字段?
【发布时间】:2013-11-26 18:54:42
【问题描述】:

我正在尝试在 Google 地图上获取点击位置的纬度和经度,然后将其存储在数据库中。我已经到了可以单击地图位置并填充表单字段的地步,但我还希望能够将标记拖放到新位置并在 dragend 事件上更新表单字段.知道如何做到这一点吗?

HTML:

<div id="container">
  <div class="row-fluid">
    <div class="span10 offset1">
      <div id="holyMapDiv"></div>
    </div>
  </div>
  <div class="row-fluid">
    <div class="span10 offset1">
      <div class="bradyRules">
        <div>Lattitude: <span id="latspan"></span></div>
        <div>Longitude: <span id="lngspan"></span></div>
        <div>Lat Lng: <span id="latlong"></span></div>
        <div>Lat Lng on click: 
        <input type="text" id="latlongclicked"></input></div>
      </div>
    </div>
  </div>
</div>

JavaScript:

var map;
var marker;

function updateMarkerPosition(latLng) {
  document.getElementById('latlongclicked').innerHTML = [
    latLng.lat(),
    latLng.lng()
  ].join(', ');
}

function mapa()
{
  var opts = {'center': new google.maps.LatLng(39.73757, -104.98472), 'zoom':8, 'mapTypeId': google.maps.MapTypeId.TERRAIN, draggableCursor: 'crosshair'}
    map = new google.maps.Map(document.getElementById('holyMapDiv'),opts);

  google.maps.event.addListener(map,'click',function(event) {
    document.getElementById('latlongclicked').value = event.latLng.lat() + ', ' + event.latLng.lng();
    placeMarker(event.latLng);
  })

  google.maps.event.addListener(map,'mousemove',function(event) {
    document.getElementById('latspan').innerHTML = event.latLng.lat();
    document.getElementById('lngspan').innerHTML = event.latLng.lng();
    document.getElementById('latlong').innerHTML = event.latLng.lat() + ', ' +     event.latLng.lng();
  });

  google.maps.event.addListener(marker,'dragend', function(event) {
    updateMarkerPosition(marker.getPosition());
  });

}

function placeMarker(location) {
  if ( marker ) {
    marker.setPosition(location);
  } else {
    marker = new google.maps.Marker({
      position: location,
      map: map,
      animation: google.maps.Animation.DROP,
      draggable: true
    });
  }
}

window.onload = mapa

谢谢。

【问题讨论】:

    标签: javascript google-maps google-maps-api-3


    【解决方案1】:
    1. 必须在 placeMarker() 的 else-branch 末尾添加 dragend-event,在添加监听器时,当前位置 markerundefined
    2. updateMarkerPosition() 中设置文本输入的innerHTML(通常不会有任何效果),改为设置value

    【讨论】:

    • 发现更新并按照我现在想要的方式工作。谢谢!
    猜你喜欢
    • 2010-12-05
    • 2015-11-23
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2017-08-27
    • 2012-06-12
    相关资源
    最近更新 更多