1

I have 2 styling methods for countries on my map:
style_init() for the initial style of a country,
style_new() for when a country changes and I want to re-style it on the map:

style_init(feature: any)           style_new(feature: any)
{                                  {
    return {                           return {
        fillColor: '#ffffff',              fillColor: '#000000', // new style here...
        color: '#ffffff',                  color: '#ffffff',
        ...                                ...
    };                                 };
}                                  }

I'm successfully using style_init() when initialising the map:

this.map_layer = L.geoJSON(this.countries, {
    style: this.style_init
}).addTo(this.map);

To update the style of a country, I'm currently embedding the style code into setStyle():

this.map_layer.eachLayer(function (layer: any)
{
    if( layer.feature.name == target_country )
    {
        layer.setStyle({
            fillColor: '#000000', // currently using raw style code here...
            color: '#000000',
        });
    }
});

I'm using setStyle() instead of .addTo(map) because the countries have already been added and I don't want to remove and re-add them or add a new country over the top of the existing initial country.
However, I want to use my style_new() method within the setStyle() call, like this:

this.map_layer.eachLayer(function (layer: any)
{
    if( layer.feature.name == target_country )
    {
        layer.setStyle({
            this.style_new() // using my function here instead
        });
    }
});

But trying this produces errors such as:
':' expected
'this' implicitly has type 'any' because it does not have a type annotation

How can I make setStyle() use my predefined function, instead of having the write the explicit style code?

1 Answer 1

1

Since style_new function returns style object, it must not be embedded in the object specifiers {} when you call it, so code should look like this:

this.map_layer.eachLayer(function (layer: any) {
  if( layer.feature.name == target_country) {
    layer.setStyle(this.style_new());
  }
});
2
  • Thank you for the answer. I have tried this but Angular now throws an error: 'this' implicitly has type 'any' because it does not have a type annotation. Is it because I'm using a this. within a different this. ? May 8 at 12:14
  • Since I'm not familiar with Angular, I can't help you with the right function call there, but it should be basic Angular stuff.
    – TomazicM
    May 8 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.