1

I have a GeoJSON map. It's a map of a country, which is made up of states, which are in turn made up of sub-state regions.

I can create a Leaflet map where I can highlight (in this case 'orange') the sub-state regions as the cursor touches them. I would like to simultaneously highlight other sub-state regions (in a different colour) that are in the same state as the initial region (ie. I want to highlight the selected sub-state region one colour, and the remainder of the state another colour).

I think I need to put the new bit of code at the comment 'new bit of code here', but I don't know how to select the other elements in the geojson that ARE NOT the one currently selected, but that still have the feature property STATE_NAME16 == tmp.

geojson = L.geoJson(States_Data, {

    onEachFeature: function (feature, layer) {
        layer.on('mouseover', function () {
          var tmp = feature.properties.STATE_NAME16 ;

          this.setStyle({
            'fillColor': 'orange'
          });

          //[new bit of code here]

        });

    }


}).addTo(map);
0

There are two ways to style GeoJSON features with Leaflet. The first is as you are doing now: passing a static object with a style defined as a JSON object. The alternative is to define a function that takes a feature, and returns a style. Something like the following would highlight red in the first case (sub-state), then blue (same state), and finally null (everything else) as a fallback.

var style = function(feature) {
  if (feature.properties.subStateRegion == hovered_sub_state_region) return {'fill-color': 'red'}
  if (feature.properties.state == hovered_state) return {'fill-color': 'blue'}
  return {'fill-color': null}
})

Then it's a matter of getting your application to update the hovered_sub_state_region and hovered_state state variables in your hover handler. This could be done by mutating a global variable, or otherwise with some form of state management (e.g. setState in React). Possibly you will need to trigger a re-render, with redraw or setStyle (passing that style variable); at this point it depends on how you have put together your application.

Check out the Options > style part of the Leaflet GeoJSON docs: https://leafletjs.com/examples/geojson/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.