Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect a click event on a google map through an overlay?

Tags:

google-maps

My problem is that I have a circle map overlay but I want to be able to move the circle by clicking the map to set the new center, the actual problem is that when I click on the overlay and call my method 'setCenter(overlay, latlng) ' , I get undefined latlang and a valid overlay.

here is an example that can illustrate the problem, if you click the map a polygon is drawn and if you click inside the polygon no new polygon is drawn, if you click anywhere else on the map a polygon is drawn http://code.google.com/apis/maps/documentation/examples/polygon-simple.html

I want to be able to click the polygon and draw a new one making them overlap

thanks

like image 696
freddoo Avatar asked Mar 21 '10 18:03

freddoo


1 Answers

All you need to do is to set the clickable: false option in the GPolygon constructor, as in the following example (GPolygonOptions: API Reference):

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps Non Clickable Polygon Demo</title> 
   <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false" 
              type="text/javascript"></script>
</head> 
<body onunload="GUnload()">
   <div id="map" style="width: 450px; height: 300px"></div> 

   <script type="text/javascript"> 
      var map = new GMap2(document.getElementById("map"));
      map.setCenter(new GLatLng(37.4419, -122.1419), 13);

      GEvent.addListener(map, "click", function(overlay, latlng) {
         var lat = latlng.lat();
         var lon = latlng.lng();
         var latOffset = 0.01;
         var lonOffset = 0.01;
         var polygon = new GPolygon([
            new GLatLng(lat, lon - lonOffset),
            new GLatLng(lat + latOffset, lon),
            new GLatLng(lat, lon + lonOffset),
            new GLatLng(lat - latOffset, lon),
            new GLatLng(lat, lon - lonOffset)
         ], "#f33f00", 5, 1, "#ff0000", 0.2, { clickable: false });

         map.addOverlay(polygon);
      });
   </script> 
</body> 
</html>

Screenshot with evidence:

Google Maps Non Clickable Polygon Demo

Note that the click(overlay: GOverlay, latlng: GLatLng, overlaylatlng: GLatLng) event passes different arguments based on the context of the click, and whether or not the click occured on a clickable overlay. If the click does not occur on a clickable overlay, the overlay argument is null and the latlng argument contains the geographical coordinates of the point that was clicked. If the user clicks on an overlay that is clickable, the overlay argument contains the overlay object, while the overlaylatlng argument contains the coordinates of the clicked overlay (Source: API Reference).

like image 176
Daniel Vassallo Avatar answered Nov 07 '22 05:11

Daniel Vassallo