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 02 Answers
Reset to default 15L.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);
});