Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 449
Bergen88 Avatar asked Jan 02 '15 20:01

Bergen88


1 Answers

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);
like image 180
iH8 Avatar answered Oct 10 '22 19:10

iH8