最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mouseover actions with geojson polygon - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Jan 2, 2015 at 20:57 Bergen88Bergen88 1772 gold badges4 silver badges15 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 15

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);

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);
});
发布评论

评论列表(0)

  1. 暂无评论