3

在地理编码时,您如何简单地将现有标记移动到新地理编码结果的结果中。

让我们看这个例子:

  • 加载地图时,会出现一个标记
  • 当有人进行地理编码时,标记会移动到结果
  • 标记是可拖动的,因此用户可以进一步移动标记(如果他们愿意)
  • 也许他们想重新对位置进行地理编码,因此新结果应自动移动现有标记。

在此示例中:

https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple

...为每个新的地理编码绘制一个新的标记。

那有意义吗?

谢谢!!!

-m

4

1 回答 1

4
  1. 使标记全局化。
  2. 在创建新的之前检查它是否存在。
  3. 如果存在,请使用 .setPosition 将其移动到新位置
  4. 如果它不存在,请在所需位置创建一个标记。

做一些接近你想要的事情的例子

工作代码片段:

var map = null;
var marker = null;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow({pixelOffset: new google.maps.Size(0,-34)});

function initialize() {
  map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: new google.maps.LatLng(42, -85),
    zoom: 4
  });
}

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);
      content = results[0].formatted_address;
      infowindow.setContent(content);
      if (marker && marker.setPosition) {
        marker.setPosition(results[0].geometry.location);
      } else {
        marker = new google.maps.Marker({
          map: map,
          icon: {
            url: 'http://maps.google.com/mapfiles/arrow.png',
            anchor: new google.maps.Point(10, 34)
          },
          position: results[0].geometry.location
        });
        google.maps.event.addListener(marker, 'click', function(evt) {
          infowindow.open(map);
        });
      }
      infowindow.setPosition(results[0].geometry.location);
      infowindow.open(map);
    } else {
      alert('Your search was not successful for the following reason: ' + status);
    }
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<input id="address" value="New York, NY" />
<input id="geocode" type="button" value="Find" onclick="codeAddress()" />
<div id="map-canvas"></div>

于 2012-09-27T19:55:12.027 回答