OpenLayers feature layer handler

I would have an openlayers vector layer with features scattered across the map. I want to be able to click on a function and show a message.

I am not sure if there is a way to add a listener / handler to each function.

Any ideas?

+4
source share
3 answers

Add SelectFeture Control:

var selectFeature = new OpenLayers.Control.SelectFeature(vector_layer); map.addControl(selectFeature); selectFeature.activate(); 

After that, you can listen to the selection / cancellation of events in the vector layer:

 vector_layer.events.on({ 'featureselected': function(feature) { //display your message here }, 'featureunselected': function(feature) { //hide message } }); 
+7
source

You need to use a combination of the SelectFeature control and one of the OpenLayers.Popup classes, such as OpenLayers.Popup.FramedCloud . Here is an example of what:

http://openlayers.org/dev/examples/select-feature-openpopup.html

In this example, try using the "draw polygon" option to draw a polygon (double-click on the map to complete the polygon). Then use "select polygon on click" and click on the polygon and you will get a popup with a frame.

You can view the source of the page to find out how to do this. Here are the relevant parts of the code. Of course, you can change the message to what you want to display in the cloud frame:

  var map = <your OpenLayers.Map object>; var polygonLayer = <your vector layer>; selectControl = new OpenLayers.Control.SelectFeature(polygonLayer, {onSelect: onFeatureSelect, onUnselect: onFeatureUnselect}); map.addControl(selectControl); // not in the example, but do this function onPopupClose(evt) { selectControl.unselect(selectedFeature); } function onFeatureSelect(feature) { var message = "<div style='font-size:.8em'>Feature: " + feature.id +"<br>Area: " + feature.geometry.getArea()+"</div>"; selectedFeature = feature; popup = new OpenLayers.Popup.FramedCloud("chicken", feature.geometry.getBounds().getCenterLonLat(), null, message, null, true, onPopupClose); feature.popup = popup; map.addPopup(popup); } function onFeatureUnselect(feature) { map.removePopup(feature.popup); feature.popup.destroy(); feature.popup = null; } 

Below are links to the controls you will use:

+4
source

If there are many vector layers, is it necessary to write "layer_name.events.on ..." for each layer? Is it possible to make a list of layers and assign ".events.on" to all of them?

0
source

Source: https://habr.com/ru/post/1387465/


All Articles