Search code examples
popupopenlayersmarkersgeorss

What is the proper way in OpenLayers (OSM) to trigger a popup for a feature?


I have the feature ID, I can grab the marker layer on GeoRSS loadend, but I'm still not sure how to cause the popup to appear programmatically.

I'll create the popup on demand if that's necessary, but it seems as though I should be able to get the id of the marker as drawn on the map and call some event on that. I've tried using jQuery and calling the $(marker-id).click() event on the map elements, but that doesn't seem to be working. What am I missing?

Since I was asked for code, and since I presumed it to be boilerplate, here's where I am so far:

map = new OpenLayers.Map('myMap'); 
map.addLayer(new OpenLayers.Layer.OSM()); 
map.addLayer(new OpenLayers.Layer.GeoRSS(name,url));

//I've done some stuff as well in re: projections and centering and 
//setting extents, but those really don't pertain to this question.

Elsewhere I've done a bit of jQuery templating and built me a nice list of all the points that are being shown on the map. I know how to do a callback from the layer loadend and get the layer object, I know how to retrieve my layer out of the map manually, I know how to iter over the layers collection and find my layer. So I can grab any of those details about the popup, but I still don't know how to go about using the built-in methods of the DOM or of this API to make it as easy as element.click() which is what I would prefer to do.


Solution

  • You don't have to click the feature to open a popup.

    First you need a reference to the feature from the feature id. I would do that in the loadend event of the GeoRSS layer, using the markers property on the layer.

    Assuming you have a reference to your feature, I would write a method which handles the automatic popup:

    var popups = {}; // to be able to handle them later 
    
    function addPopup(feature) {
    
    var text = getHtmlContent(feature); // handle the content in a separate function.
    
    var popupId = evt.xy.x + "," + evt.xy.y; 
    var popup = popups[popupId];
    if (!popup || !popup.map) {
        popup = new OpenLayers.Popup.Anchored(
            popupId,
            feature.lonlat,
            null,
            " ",
            null,
            true,
            function(evt) {
                delete popups[this.id];
                this.hide();
                OpenLayers.Event.stop(evt);
            }
        );
        popup.autoSize = true;
        popup.useInlineStyles = false;
        popups[popupId] = popup;
        feature.layer.map.addPopup(popup, true);
    }
    popup.setContentHTML(popup.contentHTML + text);
    popup.show();
    
    }