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 に答える