Bergen88
Bergen88

Reputation: 177

Mouseover actions with geojson polygon

First time using geojson polygons in Leaflet. I would like to add the following actions: 1. Mouseover change color 2. Onclick hyperlink to url

Here is the code one polygon layer.

/* Overlay Layers */
var boroughs = L.geoJson(null, {
  style: function (feature) {
    return {
      color: "blue",
      fill: false,
      opacity: 1,
      clickable: true
    };
  },

$.getJSON("data/boroughs.geojson", function (data) {
  boroughs.addData(data);
});

Current working map with toggle layers.

Upvotes: 6

Views: 15087

Answers (2)

Bergen88
Bergen88

Reputation: 177

Here is the working code for displaying geojson polygons, with mouseover and onclick hyperlink using 'URL' field in geojson.

   var districts = L.geoJson(null, {
  style: function (feature) {
    return {
      color: "green",
      fill: true,
      opacity: 0.8
    };
  },


onEachFeature(feature, layer) {
    layer.on('mouseover', function () {
      this.setStyle({
        'fillColor': '#0000ff'
      });
    });
    layer.on('mouseout', function () {
      this.setStyle({
        'fillColor': '#ff0000'
      });
    });
    layer.on('click', function () {
    window.location = feature.properties.URL;
    });
}

});

$.getJSON("data/districts.geojson", function (data) {
  districts.addData(data);
});

Upvotes: 1

iH8
iH8

Reputation: 28688

L.GeoJSON's options have a onEachFeature option which i see you've used extensively in your source code. It takes a function with two parameters, feature (which contains the geojson feature) and layer (which contains a reference to the actual polygon layer) The layer supports mouseevents which you can hook into. For example:

var layer = new L.GeoJSON(null, {
  onEachFeature: function (feature, layer) {
    layer.on('mouseover', function () {
      this.setStyle({
        'fillColor': '#0000ff'
      });
    });
    layer.on('mouseout', function () {
      this.setStyle({
        'fillColor': '#ff0000'
      });
    });
    layer.on('click', function () {
      // Let's say you've got a property called url in your geojsonfeature:
      window.location = feature.properties.url;
    });
  }
}).addTo(map);

Upvotes: 15

Related Questions