OpenLayers WFS Layer with Popups
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/openlayers/2.11/OpenLayers.js"></script>
<body onload="init()">
<p>OpenLayers WFS with select control and Popups</p>
<div id="map"></div>
</body>
CSS
#map {
width: 400px;
height: 600px;
}
JavaScript
var map;
var layer, wms, selectControl;
function init() {
map = new OpenLayers.Map('map');
wms = new OpenLayers.Layer.WMS(
"OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0", {
layers: 'basic'
});
layer = new OpenLayers.Layer.Vector("WFS", {
strategies: [new OpenLayers.Strategy.BBOX()],
protocol: new OpenLayers.Protocol.WFS({
url: "http://demo.opengeo.org/geoserver/wfs",
featureType: "ne_10m_populated_places",
featureNS: "http://openstreemap.org"
})
});
map.addLayers([wms, layer]);
map.setCenter(new OpenLayers.LonLat(146.7, -41.8), 6);
selectControl = new OpenLayers.Control.SelectFeature(map.layers[1],
{onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
map.addControl(selectControl);
selectControl.activate();
}
function onPopupClose(evt) {
selectControl.unselect(selectedFeature);
}
function onFeatureSelect(feature) {
selectedFeature = feature;
popup = new OpenLayers.Popup.FramedCloud("chicken",
feature.geometry.getBounds().getCenterLonLat(),
new OpenLayers.Size(100,100),
"<h2>"+feature.attributes.NAME + "</h2>" + feature.attributes.ADM0NAME,
null, true, onPopupClose);
feature.popup = popup;
//map.addPopup(popup);
map.addPopup(popup,true);
}
function onFeatureUnselect(feature) {
map.removePopup(feature.popup);
feature.popup.destroy();
feature.popup = null;
}