0

On my map, I have an OpenStreetMap tiles in the background and a VectorLayer on top. Now I want VectorLayer to be changed by user via drop down menu. How can I achieve this?

Here's my HTML drop down menu code:

<select id="line">
    <option value="1a">Line 1A</option>
    <option value="1b">Line 1B</option>
    <option value="2a">Line 2A</option>
    <option value="2b">Line 2B</option>
</select>

Here's my map script:

      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM({
            url: 'tiles/{z}/{x}/{y}.png',
            crossOrigin: null,
            })
          }), linelayergroup
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([100.568, 14.353]),
          zoom: 14,
          minZoom: 14,
          maxZoom: 19,
          extent: [11187608.82, 1608083.02, 11203003.55, 1621297.19],
          constrainResolution: true
        })
      });

And here's my VectorLayer 1a script:

    var layer1a = new ol.layer.Vector({
        source: source1a,
        style: function(feature) {
            allbusstyle.getText().setText(feature.get('name'));
            return allbusstyle;
        }
    });

How the code of var linelayergroup should be?, to be the VectorLayerGroup that can be changed by value in the HTML drop down menu. For example, if user select Line 1A in drop down menu, the VectorLayer will change from default to layer layer1a, and if user select another choice, the VectorLayer will change from layer1a to that choice.

Thank you for your assistance.

1 Answers1

1

You can do it in several ways.

1- Toggling visibility: You can add all 4 layers to the map. When user select a layer in the dropdown menu you should turn that layer visible and make others hidden.
This can be done easily by an event handler on the dropdown menu(you should on change toggle visibility of layers).

var object = document.getElementById("line");
object.addEventListener("change", function(){
    layer1a.setVisible(false);
    // same for other layers

    switch(object.value){
        case "1a":
            layer1a.setVisible(true);
            break;
        // same for other layers
    }
});

2- Changing source: Also you can change the layer source. in this way, you should add only one layer. when user selects from list you need to replace layer source and re-render it. so the layer will be changed.

Hope this helps

Mahdi Mahmoodian
  • 473
  • 2
  • 13