I can not get the style to reset on a leaflet polygon. The setStyle
works just fine on hover, however resetting it when I stop hovering is not working. I'm getting Uncaught TypeError: Object [object Object] has no method 'resetStyle'. I understand what that error means, but I can't figure out how to properly do this.
Thanks in advance.
$.getJSON('geoJSON.json', function (json) {
L.geoJson(json, {
...
onEachFeature: function (feature, layer) {
var defaultStyle = layer.style;
layer.on('mouseover', function (e) {
this.setStyle({
color: '#2262CC',
weight: 3,
opacity: 0.6,
fillOpacity: 0.65,
fillColor: '#2262CC'
});
});
layer.on('mouseout', function (e) {
this.resetStyle();
});
}
}).addTo(map);
});
I can not get the style to reset on a leaflet polygon. The setStyle
works just fine on hover, however resetting it when I stop hovering is not working. I'm getting Uncaught TypeError: Object [object Object] has no method 'resetStyle'. I understand what that error means, but I can't figure out how to properly do this.
Thanks in advance.
$.getJSON('geoJSON.json', function (json) {
L.geoJson(json, {
...
onEachFeature: function (feature, layer) {
var defaultStyle = layer.style;
layer.on('mouseover', function (e) {
this.setStyle({
color: '#2262CC',
weight: 3,
opacity: 0.6,
fillOpacity: 0.65,
fillColor: '#2262CC'
});
});
layer.on('mouseout', function (e) {
this.resetStyle();
});
}
}).addTo(map);
});
Share
Improve this question
asked May 20, 2013 at 15:50
YatrixYatrix
13.8k17 gold badges54 silver badges82 bronze badges
2 Answers
Reset to default 4The code above fails because the resetStyle function can be found in the geojson layer and not in the layer that "this" points to.
Also the geojson layer requires a style path option set for the default style for resetStyle to work.
$.getJSON('geoJSON.json', function (json) {
var geojson = L.geoJson(json, {
...
style: <default style here>
onEachFeature: function (feature, layer) {
var defaultStyle = layer.style;
layer.on('mouseover', function (e) {
this.setStyle({
color: '#2262CC',
weight: 3,
opacity: 0.6,
fillOpacity: 0.65,
fillColor: '#2262CC'
});
});
layer.on('mouseout', function (e) {
geojson.resetStyle();
});
}
}).addTo(map);
});
It may be a problem of context:
$.getJSON('geoJSON.json', function (json) {
L.geoJson(json, {
...
onEachFeature: function (feature, layer) {
var defaultStyle = layer.style,
that = this;//NEW
layer.on('mouseover', function (e) {
this.setStyle({
color: '#2262CC',
weight: 3,
opacity: 0.6,
fillOpacity: 0.65,
fillColor: '#2262CC'
});
});
layer.on('mouseout', function (e) {
that.resetStyle(); //NEW
});
}
}).addTo(map);
});