移动地图时将标记移动到地图中间

时间:2015-07-29 04:01:42

标签: google-maps

获得此地图,用户可以在其中获取标记的坐标。用户可以在文本字段中键入位置,例如一个城市,然后使用标记精确定位获取坐标的确切位置。坐标在文本字段中呈现。地图怎么样,当用户移动地图时,标记会自动转到中间?

<html>

<head>

  <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
  <script>
    var geocoder;
    var map;
    var mapOptions = {
      zoom: 17,
      mapTypeId: google.maps.MapTypeId.HYBRID
    }
    var marker;

    function initialize() {
      geocoder = new google.maps.Geocoder();
      map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
      codeAddress();
    }

    function codeAddress() {

      var address = document.getElementById('address').value;
      geocoder.geocode({
        'address': address
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);
          if (marker)
            marker.setMap(null);
          marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location,
            draggable: true
          });
          google.maps.event.addListener(marker, "dragend", function() {
            document.getElementById('lat').value = marker.getPosition().lat();
            document.getElementById('lng').value = marker.getPosition().lng();
          });
          document.getElementById('lat').value = marker.getPosition().lat();
          document.getElementById('lng').value = marker.getPosition().lng();
        } else {
          alert('Geocode was not successful for the following reason: ' + status);
        }
      });
    }
  </script>
</head>

<body onload="initialize()">

  <div class="container">

    <form>
      <input id="address" type="textbox" style="width:200px" value="London">


      <input type="button" value="Search" onclick="codeAddress()">

      <!---
			  <br />
			  <br />
			  
			<i>
			(Use the red marker to pinpoin the location, then below the map, click on submit.)
			</i>
			  --->

      <br />

      <div id="map_canvas" style="height:300px;width:350px;top:30px"></div>



      <br />
      <br />


      <br />

      <table>
        <tr>
          <td>
            Lat:
          </td>
          <td>
            <input type="text" id="lat" name="lat" />
          </td>
        </tr>
        <tr>
          <td>
            Lng:
          </td>
          <td>
            <input type="text" id="lng" name="lng" />
          </td>
        </tr>
      </table>
      <br />
      <br />

    </form>
  </div>

</body>

</html>

1 个答案:

答案 0 :(得分:1)

将地图拖动侦听器添加到您的代码中:

google.maps.event.addListener(map, "dragend", function() {
    marker.setMap(null);
    marker = new google.maps.Marker({
        map: map,
        position: map.getCenter(),
        draggable: true
    });
});

检查jsfiddle