Code generation and events in Google Maps API

I’m moving fast with new RNS features development and I discover new GM API nuances, this time with events.

In map edition mode it will be possible to change icons for particular route points and add some notes. All markers are kept in array, and for each marker I add listener for event ‘click’ which opens info windows with openInfoWindowHtml(). Pretty straightforward. But HTML code for this window becomes a little more complicated. In this window I place bunch of links, which are basically calls to JavaScript functions (with onclick property) with parameters generated when ‘click’ handler for particular marker is run. This code is dynamic and depends on other variables state, thus results can differ for each time handler is used for some marker.

Today I have noticed that click on opened info window will trigger Google Maps ‘click’ event, and since info window is another overlay in terms of GM API, You should be aware that using code from GM API documentation to add markers can lead to errors.

var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

GEvent.addListener(map, "click", function(marker, point) {
  if (marker) {
    map.removeOverlay(marker);
  } else {
    map.addOverlay(new GMarker(point));
  }

If You open somewhere info window with link on it, clicking on it will trigger again ‘click’ event on map object with marker variable pointing to overlay which represents info window. And as result with above code will close info window. If link is leading to some other page this is no problem, but in case You need to not running this event when window is open (this was my case, ‘click’ event handler was messing variables state, since it was ‘thinking‘ it was clicked on marker) You can add some logical global variable to check at event handler start:

GEvent.addListener(map, "click", function(marker, point) {
  if (!runClickEvent)
     return
  if (marker) {
    map.removeOverlay(marker);
  } else {
    map.addOverlay(new GMarker(point));
  }

And open info window this way:

marker.openInfoWindowHtml(content)
runClickEvent = false
GEvent.addListener( map.getInfoWindow(), 'closeclick', 
    function () { runClickEvent = true } )

Last line adds new handler for event fired when user clicks in close button on info window. Handler is responsible for restoring ‘click’ handler to usable state setting global variable to value resulting in not returning from first if in ‘click’ handler.

Don’t forget to initialize runClickEvent on script beginning with var runClickEvent = true

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.