Skip to content

GeoJson show arg doesn't work as expected #1283

Closed

Description

@beautah

Please add a code sample or a nbviewer link, copy-pastable if possible

def add_huc_chropleth(m, data_type='swe', show=False, huc_level='6', 
                      gis_path='gis', filter_str=''):
    
    huc_str = f'HUC{huc_level}'
    stat_type_dict = {'swe': 'Median', 'prec': 'Avg.'}
    stat_type = stat_type_dict.get(data_type, '')
    layer_name = f'{huc_str} % {stat_type} {data_type.upper()}'
   
    style_function = lambda x: style_chropleth(
        x, data_type=data_type, huc_level=huc_level, huc_filter=filter_str
    )
    if True:
        json_path = f'{STATIC_URL}/gis/HUC{huc_level}.geojson'
        folium.GeoJson(
            json_path,
            name=layer_name,
            embed=False,
            overlay=True,
            control=True,
            # smooth_factor=2.0,
            style_function=style_function,
            show=show,
            tooltip=folium.features.GeoJsonTooltip(
                ['Name', f'{data_type}_percent'],
                aliases=['Basin Name:', f'{layer_name}:'])
        ).add_to(m)

def style_chropleth(feature, data_type='swe', huc_level='2', huc_filter=''):
    huc_filter = str(huc_filter)
    huc_level = str(huc_level)
    colormap = get_colormap()
    stat_value = feature['properties'].get(f'{data_type}_percent', 'N/A')
    huc_id = str(feature['properties'].get(f'HUC{huc_level}', 'N/A'))
    if not stat_value == 'N/A':
        stat_value = float(stat_value)
    
    return {
        'fillOpacity': 
            0 if stat_value == 'N/A' or 
            not huc_id[:len(huc_filter)] == huc_filter else 
            0.75,
        'weight': 0,
        'fillColor': 
            '#00000000' if stat_value == 'N/A' or 
            not huc_id[:len(huc_filter)] == huc_filter else 
            colormap(stat_value)
    }

Problem description

Not sure if this is due to the loading of the ajax call to the geojson url or the fact it's so highly styled (would imagine the former), but the show arg doesn't get expected results when used as shown above. I monkey patched the folium.features.py file to have the GeoJson._template explicitly determine if the the geojson is added to the map or simply defined using the following snipet:

 _template = Template(u"""
# ...
        {%- if this.show %}
            function {{ this.get_name() }}_add (data) {
                {{ this.get_name() }}.addData(data)
                    .addTo({{ this._parent.get_name() }});
            }
        {%- else %}
            function {{ this.get_name() }}_add (data) {
                {{ this.get_name() }}.addData(data);
            }
        {%- endif %}   
# ...
 """
...
# also need to add self.show to the init method:
def __init__(self, data, style_function=None, highlight_function=None,  # noqa
                 name=None, overlay=True, control=True, show=True,
                 smooth_factor=None, tooltip=None, embed=True):
        super(GeoJson, self).__init__(name=name, overlay=overlay,
                                      control=control, show=show)
        self._name = 'GeoJson'
        self.embed = embed
        self.show = show
# ...

Expected Output

Normally the layer inherited class takes care of removing the layer which was added by default by appending the geo_json_###...###.remove(); to the js script. My thought it that since the ajax call is loading it async it's finishing the .remove() before the layer is added and therefore all the layers are just turned on by default.

I'd be happy to make a pull request but I'm locked down on my computer and therefore cannot use your contribution workflow which requires installation of things. I submitted another basic pull request for a browser print plugin but again I couldn't follow the contribution work flow. Any suggestions on how I can contribute without using miniconda, etc.

Output of folium.__version__

'0.10.1'

Activity

  1. added
    bug
    on Apr 13, 2020
  2. Conengmo commented on Apr 13, 2020

    @Conengmo
    Member

    Hi @beautah, thanks for your bug report! You're right, show=False doesn't work when not embedding the data. You're also right about the ajax call finishing after .remove(), good catch.

    I looked into it a bit and made a PR with a fix: #1289 Can you check out if this solves your issue? You don't need anything special, just install folium from the git branch. (pip install git+https://github.com/Conengmo/folium.git@geojson-fix-show, possibly use -u since you're locked down)

  3. added
    work in progress
    on Apr 13, 2020
  4. beautah commented on Apr 13, 2020

    @beautah
    ContributorAuthor
  5. Conengmo commented on Apr 13, 2020

    @Conengmo
    Member

    Thanks for testing the fix! Good to know it works for you. We'll get it merged soon, it will be in the next release. That won't be long I think. In the meantime you can install from our git master branch.

    About your second point, I see what you mean. For plugins you currently have to do monkey patching indeed. Having a _default_js and _default_css in each plugin module would make sense for users that want do define local locations. We don't really have a staff working on folium or anything, so if somebody (maybe you? :) wants this, they can create a PR! I'd happily review it. If you want to discuss this more, you can open a new issue for it.

  6. beautah commented on Apr 13, 2020

    @beautah
    ContributorAuthor
  7. Conengmo commented on Apr 13, 2020

    @Conengmo
    Member

    I haven't thought about it that much, so using the same methodology sounds like a good idea. Unless you have suggestions of course.

    will likely have to wait until after COVID calms down and I’m not running a preschool and working a day job

    Sounds like you have quite some things on your plate right now :) no hurries, in the meantime good luck

  8. removed
    work in progress
    on Jun 18, 2020
  9. beautah commented on Feb 25, 2021

    @beautah
    ContributorAuthor

    @Conengmo just wanted to thank you for adding the optional js and css for each plugin, crazy to think that was almost a year ago when I promised to "get around to it"... still doing double duty running a preschool and working from home ;) But schools are opening next week, I swear I still had planned to get around to this, looks like I'll need to find another bug to work on, I just pulled the newest release so I'll dig in and find something.

  10. Conengmo commented on Feb 26, 2021

    @Conengmo
    Member

    It's been a quite a year for sure :) Of course you're welcome to help, though I don't know of any obvious issues at the moment. There are a lot of open issues on Github, it's a bit hard to triage everything, but I try to spot any bugs that need fixing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions