Google Maps API 3: Obtener coordenadas desde el clic derecho


Tengo 2 cuadros de texto para lat y lon para cuando un usuario está introduciendo un nuevo registro en la base de datos.

Tengo una vista previa en vivo de Google Maps que funciona muy bien, ahora lo que quiero hacer es agregar un evento de clic derecho en el mapa que rellene los cuadros de texto lat/lon con el coord hecho clic.

¿Es esto posible?

Sé cómo agregar el receptor de eventos, y miré a través de los documentos de la API, pero no vi nada que haga esto. Sé que puedes hacerlo en el mapa de Google en su sitio.

Author: guyfromfl, 2011-10-26

2 answers

google.maps.event.addListener(map, "rightclick", function(event) {
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    // populate yor box/field with lat, lng
    alert("Lat=" + lat + "; Lng=" + lng);
});
 154
Author: Jiri Kriz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-26 18:04:53

Puede crear un objeto InfoWindow ( documentación de la clase aquí) y adjuntarle un controlador de eventos rightclick que lo rellenará con la latitud y longitud de la ubicación en la que se hizo clic en el mapa.

function initMap() {
  var myOptions = {
      zoom: 6,
      center: new google.maps.LatLng(-33.8688, 151.2093)
    },
    map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
    marker = new google.maps.Marker({
      map: map,
    }),
    infowindow = new google.maps.InfoWindow;
  map.addListener('rightclick', function(e) {
    map.setCenter(e.latLng);
    marker.setPosition(e.latLng);
    infowindow.setContent("Latitude: " + e.latLng.lat() +
      "<br>" + "Longitude: " + e.latLng.lng());
    infowindow.open(map, marker);
  });
}
html,
body {
  height: 100%;
}
#map-canvas {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAIPPUQ0PSWMjTsgvIWRRcJv3LGfRzGmnA&callback=initMap" async defer></script>
<div id="map-canvas"></div>
 3
Author: user2314737,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-30 11:09:17