javascript - 在谷歌地图javascript中拖动 map 上的标记(可拖动方向)时如何显示更新的坐标?

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

我正在开发一个网络应用程序,用户可以在其中拖动屏幕上的目的地标记,并自动更新持续时间和目的地的输入字段。我还放入了起点和终点坐标字段,并且我想在拖动屏幕标记时也更新它们。我只是不知道从哪里获取这些值。这是我的代码:

<div id="map" style="width: 400px; height: 300px;"></div> 
  Duration: <input id="duration"></div> 
  Distance:  <input id="distance"></input>
  Origin Longitude <input id="origin_longitude"></input>
  Origin Latitude <input id="origin_latitude"></input>
  Destination Longitude <input id="destination_longitude"></input>
  Destination Latitude <input id="destination_latitude"></input>
 <div>



<script type="text/javascript"> 
function initialize() {
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true
  });

  var myOptions = {
    zoom: 7,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  var map = new google.maps.Map(document.getElementById("map"), myOptions);
  directionsDisplay.setMap(map);

var request = {
    origin: new google.maps.LatLng(51.403650, -1.323252),
    destination: new google.maps.LatLng(51.403650, -1.323252),
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };


  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
        directions = directionsDisplay.getDirections();
        // Display the distance:
        document.getElementById('distance').value =
          directions.routes[0].legs[0].distance.value + " meters";
        // Display the duration:
        document.getElementById('duration').value =
          directions.routes[0].legs[0].duration.value + " seconds";





      })
    } else {
      alert("directions request failed:" + status)
    }
  });
}
google.maps.event.addDomListener(window, "load", initialize);

   </script> 

最佳答案

查看 this示例。

只需添加

marker.addListener('position_changed', printMarkerLocation);

然后就可以定义函数了

function printMarkerLocation(){
    console.log('Lat: ' + marker.position.lat() + ' Lng:' + marker.position.lng() );}

关于javascript - 在谷歌地图javascript中拖动 map 上的标记(可拖动方向)时如何显示更新的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36674337/

相关文章:

javascript 代码在插入 html 地理定位 map 时不起作用

java - 在 Java EE 框架中使用 Mysql 的 Google map

javascript - 谷歌地图叠加更新技术

javascript - 如何在 javascript、谷歌地图中使用 setPanel() 添加地点搜索框和文本方向

javascript - 脚本5007 : Unable to get value of the property '0' : object is null or undefined

javascript - 使用 javascript 将值相乘

javascript - Morris 图表未显示 MVC 的最后一个 xkey 值

javascript - 从 mysql 检索纬度和经度,将其传递给谷歌地图 api

google-maps - Mongodb 地理空间索引与 GoogleMaps 方向服务

javascript - React - Google Map 组件在重新渲染后不会更改 map