简体   繁体   中英

How to identify a google map marker on click?

I'm creating a Google Map from the developer API v3. It's populated with markers created dynamically from ColdFusion querying an MsSQL database.

 <cfloop query="One">
 <script>locations[<cfoutput>#One.userID#</cfoutput>
] = new google.maps.LatLng(<cfoutput>#One.latLng#</cfoutput>);
 </script>
 </cfloop>

I need a way to recognise the marker when its clicked so I can display address details in a box below the map and also higlight markers when a button is clicked lower on the page.

In general, you would typically assign your own custom properties to the Marker. Something like:

function markerClicked(e) {
    console.log('Marker ' + marker.myData + ' has been clicked');
}
var marker = new google.maps.Marker(...);
marker.myData = 1; //this could be arbitrary data or even another object
google.maps.event.addListener(marker, 'click', markerClicked);

Adding custom data to any Google Maps API object has risks though. Google's code is obfuscated and the internal (non-documented) properties can and do change. Make sure your property is named in such a way that it won't conflict with any existing property or future property. Tip: Choose a property name longer than 3 letters.

If you are going to minify/compile/compress your maps code, then there are additional considerations .

What about :

google.maps.event.addListener(marker, "click", function (e) {
    var clicked = this;
    //...
});

This is pretty thoroughly documented/explained in the documentation.

https://developers.google.com/maps/documentation/javascript/overlays#InfoWindows

When you create markers, add dom listeners to the markers like this

  google.maps.event.addListener(marker, 'click', function() {
     infowindow.open(map,marker);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM