Pregunta

Hello i am looking for a way to get the lat,long of any clicked point on a map and have that information stored in an id tag. I am using gmaps4rails v2 and my current code is as follows:

<script type="text/javascript">
  var handler2 = Gmaps.build('Google');
  handler2.buildMap({ provider: { }, internal: {id: 'map'}}, function(){
      // I assume this is the way you retrieve the amrkers array
      var json_data = <%=raw @hash.to_json %>;
      var markers = handler2.addMarkers(json_data);

      _.each(json_data, function(json, index){
          var marker  = markers[index];
          json.marker = marker;
          google.maps.event.addListener(handler2.map, 'click', function( event ){
              var latlong = document.getElementById("latlong");
              latlong.innerHTML =( "Latitude: "+event.latLng.lat()+" "+", longitude: "+event.latLng.lng() );
          });

      });
      handler2.bounds.extendWith(markers);
      handler2.getMap().setZoom(1);

  });
</script>

<div id="latlong">
This is the lat long of the currently clicked point.
</div>

The issue is that no matter where i click on the map the listener is not responding and i am not getting any result in my id tag "latlong". any help is appreciated thank you.

¿Fue útil?

Solución

Issue was addListener(handler2.map because handler.map is a gmaps4rails object, not a google map object.

So either you use handler2.getMap() or handler.map.getServiceObject() (the former is a shortcut).

One other thing: you can pass map options with the provider key of the buildMap function.

Here is the working code:

var handler2 = Gmaps.build('Google');
handler2.buildMap({ provider: { zoom: 1 }, internal: {id: 'map'}}, function(){
  // I assume this is the way you retrieve the amrkers array
  var json_data = <%=raw @hash.to_json %>;
  var markers = handler2.addMarkers(json_data);

  _.each(json_data, function(json, index){
      var marker  = markers[index];
      json.marker = marker;
      google.maps.event.addListener(handler2.getMap(), 'click', function( event ){
        var latlong = document.getElementById("latlong");
        latlong.innerHTML =( "Latitude: "+event.latLng.lat()+" "+", longitude: "+event.latLng.lng() );
      });
  });
  handler2.bounds.extendWith(markers);
  handler2.fitMapToBounds();
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top