Pregunta

How, when geocoding, can you simply move an existing marker to the result of a new geocode result.

Let's take this example:

  • When the map loads, a marker appears
  • When someone geocodes, the marker moves to the result
  • The marker is draggable, so the user can further move the marker (if they want to)
  • Perhaps they want to re-geocode a location, so the new result should automatically move the existing marker.

In this sample:

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

...a new marker is drawn for every new geocode.

Does that make sense?

Thanks!!!

-m

¿Fue útil?

Solución

  1. Make the marker global.
  2. Check if it exists before creating a new one.
  3. if it exists use .setPosition to move it to the new location
  4. if it doesn't exist, create a marker at the desired location.

Example that does something close to what you want

working code snippet:

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>

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top