Yatrix
Yatrix

Reputation: 13775

How can I reset style on a polygon?

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

Upvotes: 3

Views: 5059

Answers (2)

ksnabb
ksnabb

Reputation: 303

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

Upvotes: 4

L. Sanna
L. Sanna

Reputation: 6552

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

Upvotes: 2

Related Questions