Search code examples
javascriptgoogle-mapsgoogle-maps-api-3gmaps.js

gmaps.js trigger infoWindow


I'm having a bit of difficulty figuring out how to trigger a specified infoWindow using gmaps.js

My map is initialized as follows:

map = new GMaps({
    div: '#map-canvas'
});
renderMarkers();

My renderMarkers function basically executes an AJAX call to a PHP script which queries the database and returns a result set, and returns a series of addMarker calls like this:

LOOP THROUGH RESULT SET {

    map.addMarker({
        lat: marker.SiteLatitude, 
        lng: marker.SiteLongitude,
        infoWindow: {
           content: marker.contentHTML,
           closeclick: function(e) {
               $("#customer-details-container").hide();
           }
       },
       icon: marker.iconPath,
       id: marker.MyID
   })

}

I refresh/re-render the markers as the client triggers updates to the underlying database by using map.removeMarkers() and then triggering my renderMarkers() function. When the markers get redrawn on the map, if the user had an infoWindow open I want to trigger it to open.

I'm not sure how to trigger an infoWindow based on a specific ID. As an example, lets just say a marker was setup like so:

    map.addMarker({
        lat: 102.325 
        lng: -67.524,
        infoWindow: {
           content: "<div>test!</div>"
           closeclick: function(e) {
               $("#customer-details-container").hide();
           }
       },
       icon: "image/marker.png",
       id: 1234
   })

Am I correct in saying that I should be able to target it using that ID=1234? eg:

google.maps.event.trigger(markers[1234], 'click');

??

I'm not sure of the specific syntax to execute this using gmaps.js

ANY help greatly appreciated :D


Solution

  • Am I correct in saying that I should be able to target it using that ID=1234?

    I don't think so. The documentation is very incomplete and inside the gmaps.js I can't find anything with a functionality to access a marker by a property.

    But you may extend the prototype:

    GMaps.prototype.markerById=function(id){
      for(var m=0;m<this.markers.length;++m){
        if(this.markers[m].get('id')===id){
          return this.markers[m];
        }
      }
      return new google.maps.Marker();
    }
    

    usage:

    google.maps.event.trigger(map.markerById(12345), 'click');