HelpOverFlow
HelpOverFlow

Reputation: 335

Filter Json Features by HTML SELECT object

I have the following websites Brazil1 and Brazil2

I uploaded some GPS stations (Json point features) and I am in need to select an specific GPS station (based on the station name "Estação RBMC) using a HTML select Object:

<select name="sometext" >
  <option value="MGRP">mgrp</option>
  <option value="MGV1">mgv1</option>
  <option value="VICO">vico</option>
  <option value="MGBH">mgbh</option>
  </select> 

My first attempt was URL, but I did not understand much.

Could someone give a tip on that?

Thank you for your time.

Upvotes: 1

Views: 754

Answers (1)

nathansnider
nathansnider

Reputation: 2883

The important thing to specify in the select element is the id, because that is what you will use to add event listeners. Something like this:

<select id="sta_select">
  <option>(select station)</option>
  <option value="MGRP">mgrp</option>
  <option value="MGV1">mgv1</option>
  <option value="VICO">vico</option>
  <option value="MGBH">mgbh</option>
</select>

You can then add event listeners based on that id:

var sta_select = L.DomUtil.get("sta_select");
L.DomEvent.addListener(sta_select, 'click', function (e) {
    L.DomEvent.stopPropagation(e);
});
L.DomEvent.addListener(sta_select, 'change', changeHandler);

The click listener with the stopPropagation method is to prevent clicks on the selector from propagating through to the map if they overlap with the map pane, which could (depending on your settings) immediately unselect the layer you are trying to highlight. The change listener will run a handler function, which you can set to do anything you want. Here, I've set it to open the popup for a marker when its corresponding option is selected (based on a match between the value attribute in the option element and the SG_RBMC property in the geoJson layer):

function changeHandler(e) {
    for (i in estacoes_rbmc._layers) {
        if (estacoes_rbmc._layers[i].feature.properties.SG_RBMC === e.target.value) {
            estacoes_rbmc._layers[i].openPopup();
        }
    }
}

Here is a fiddle that shows it at work:

http://jsfiddle.net/nathansnider/80qcstLf/

and also a somewhat fancier version that puts the select element on the map inside a Leaflet control and automatically populates the option attributes:

http://jsfiddle.net/nathansnider/avn0ph1p/

Upvotes: 1

Related Questions