openlayers simple mouseover on marker

user987875 picture user987875 · Dec 15, 2011 · Viewed 38.4k times · Source

It sounds so simple but I can't find any newbie tutorial: Could anybody give me a simple example how I create (vektor)markers in OpenLayers that open an infowindow on mouseover and even close it on mouseout?

I found parts of this explained but not all of it....

Answer

Kyle picture Kyle · Jun 18, 2012

For a simple example of how to do this, you need to do a couple of things:

Create a vector layer to contain your markers and add it to the map:

this.markerLayer = new OpenLayers.Layer.Vector(
    "My Marker Layer",
    { /* configuration options are set here */ }
);
map.addLayer(this.markerLayer);

Create your marker and add it to the map:

var marker = new OpenLayers.Feature.Vector(point, attributes, markerStyle);
this.markerLayer.addFeatures([marker]);

Create a select control for your layer, and register a function to build your popup when the user hovers over your marker:

var selectControl = new OpenLayers.Control.SelectFeature(this.markerLayer, {
    hover: true
});
selectControl.events.register('featurehighlighted', null, onFeatureHighlighted);

Build your popup:

onFeatureHighlighted: function (evt) {
    // Needed only for interaction, not for the display.
    var onPopupClose = function (evt) {
        // 'this' is the popup.
        var feature = this.feature;
        if (feature.layer) {
            selectControl.unselect(feature);
        }  
        this.destroy();
    }

    feature = evt.feature;
    popup = new OpenLayers.Popup.FramedCloud("featurePopup",
            feature.geometry.getBounds().getCenterLonLat(),
            new OpenLayers.Size(100,100),
            "<h2>"+feature.attributes.station_na + "</h2>" +
            "Location: " + feature.attributes.location + '<br/>' +
            "Elevation: " + feature.attributes.elev_,
            null, true, onPopupClose);
    feature.popup = popup;
    popup.feature = feature;
    map.addPopup(popup, true);
}, // ...