Question

I want to offer geolocation and an editable map marker that returns lat/lng to users via Google Maps API. I have successfully figured out how to do the geolocation part of this via the method described here:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>
function success(position) {
  var mapcanvas = document.createElement('div');
  mapcanvas.id = 'mapcontainer';
  mapcanvas.style.height = '400px';
  mapcanvas.style.width = '600px';

  document.querySelector('article').appendChild(mapcanvas);

  coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

  var options = {
    zoom: 15,
    center: coords,
    mapTypeControl: false,
    navigationControlOptions: {
        style: google.maps.NavigationControlStyle.SMALL
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("mapcontainer"), options);

  var marker = new google.maps.Marker({
      position: coords,
      map: map,
      title:"You are here!"
  });
}

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(success);
} else {
  error('Geo Location is not supported');
}
</script>

However, I also want to be able to allow the user to move the map and select another location via the map marker, and capture the lat / lng that they have selected. The method described here does what I want, but I am not sure how to get both scripts working together to add the functionality that I need. I am trying to create something that works like über does in this respect, if that helps explain the goal.

How can I make a Google map that centers based on geolocation, but also whose map marker can move and record the lat / lng of the final marker? Thanks for your ideas!

Était-ce utile?

La solution

You want to first set the marker's draggable property to true in the marker options.

Then listen for the dragend event on the marker - you can set this up with google.maps.event.addListener(marker, 'dragend', callback);.

Then in your callback function, get the marker's position using the getPosition() method.

As mentioned by @geocodezip refer to the API documention for more reference.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top