Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Geocoder plugin: support other built-in providers #1852

Conversation

prusswan
Copy link
Contributor

@prusswan prusswan commented Dec 24, 2023

tested with Nominatim, Photon, Google:

from branca.element import MacroElement
from jinja2 import Template

from folium.elements import JSCSSMixin
from folium.utilities import parse_options

import folium

class EnhancedGeocoder(JSCSSMixin, MacroElement):
    """A simple geocoder for Leaflet that by default uses OSM/Nominatim.

    Please respect the Nominatim usage policy:
    https://operations.osmfoundation.org/policies/nominatim/
    Parameters
    ----------
    collapsed: bool, default False
        If True, collapses the search box unless hovered/clicked.
    position: str, default 'topright'
        Choose from 'topleft', 'topright', 'bottomleft' or 'bottomright'.
    add_marker: bool, default True
        If True, adds a marker on the found location.
    geocode_zoom: int, default 11
        Set zoom level used for displaying the geocode result, note that this only has an effect when add_marker is set to False. Set this to None to preserve the current map zoom level.
    geocode_provider: str, default 'nominatim'
        Defaults to "nominatim", see https://github.com/perliedman/leaflet-control-geocoder/tree/2.4.0/src/geocoders for other built-in providers.
    geocode_provider_options: dict, default {}
        For use with specific providers that may require api keys or other parameters.

    For all options see https://github.com/perliedman/leaflet-control-geocoder

    """

    _template = Template(
        """
        {% macro script(this, kwargs) %}

            var geocoderOpts_{{ this.get_name() }} = {{ this.options|tojson }};

            // note: geocoder name should start with lowercase
            var geocoderName_{{ this.get_name() }} = geocoderOpts_{{ this.get_name() }}["geocodeProvider"];

            var customGeocoder_{{ this.get_name() }} = L.Control.Geocoder[ geocoderName_{{ this.get_name() }} ](
                geocoderOpts_{{ this.get_name() }}['geocodeProviderOptions']
            );
            geocoderOpts_{{ this.get_name() }}["geocoder"] = customGeocoder_{{ this.get_name() }};

            L.Control.geocoder(
                geocoderOpts_{{ this.get_name() }}
            ).on('markgeocode', function(e) {
                var zoom = geocoderOpts_{{ this.get_name() }}['geocodeZoom'] || {{ this._parent.get_name() }}.getZoom();
                {{ this._parent.get_name() }}.setView(e.geocode.center, zoom);
            }).addTo({{ this._parent.get_name() }});

        {% endmacro %}
    """
    )

    default_js = [
        (
            "Control.Geocoder.js",
            "https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js",
        )
    ]
    default_css = [
        (
            "Control.Geocoder.css",
            "https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css",
        )
    ]

    def __init__(
        self,
        collapsed: bool = False,
        position: str = "topright",
        add_marker: bool = True,
        geocode_zoom: int | None = 11,
        geocode_provider: str = "nominatim",
        geocode_provider_options: dict = {},
        **kwargs
    ):
        super().__init__()
        self._name = "Geocoder"
        self.options = parse_options(
            collapsed=collapsed,
            position=position,
            default_mark_geocode=add_marker,
            geocode_zoom=geocode_zoom,
            geocode_provider=geocode_provider,
            geocode_provider_options=geocode_provider_options,
            **kwargs
        )

google_key = "placeholder"
gc2_default = EnhancedGeocoder() # nominatim
#gc2_photon = EnhancedGeocoder(geocode_provider="photon")
#gc2_google = EnhancedGeocoder(geocode_provider="google",
#                           geocode_provider_options={"apiKey": google_key})


m2 = folium.Map(location=[43.7798, 11.24148], zoom_start=13, tiles="cartodb positron")

gc2_default.add_to(m2)
#gc2_photon.add_to(m2)
#gc2_google.add_to(m2)

folium.LayerControl().add_to(m2)
m2

folium/plugins/geocoder.py Outdated Show resolved Hide resolved
folium/plugins/geocoder.py Outdated Show resolved Hide resolved
@prusswan prusswan force-pushed the add-support-for-multiple-geocode-providers branch from ac95f40 to f716052 Compare January 5, 2024 23:44
@prusswan prusswan force-pushed the add-support-for-multiple-geocode-providers branch from 856e5aa to 5c7d7a0 Compare January 6, 2024 01:09
@Conengmo Conengmo self-requested a review January 8, 2024 14:31
Copy link
Member

@Conengmo Conengmo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good overall! Few small comments before we can merge this.

folium/plugins/geocoder.py Outdated Show resolved Hide resolved
folium/plugins/geocoder.py Outdated Show resolved Hide resolved
folium/plugins/geocoder.py Outdated Show resolved Hide resolved
collapsed: bool = False,
position: str = "topright",
add_marker: bool = True,
geocode_zoom: int | None = 11,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as the default zoom level of 11 is not suitable for close-up locations (and only works when add_marker is False)

Question: is 11 a good default? Or would None be a better default?

And another question: should we check or correct this value when add_marker is False?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

11 would preserve the current behavior so existing users would not be caught by surprise. The real gotcha would be the case when add_marker=True (when default handler in leaflet-control-geocoder will be using fit_bounds with no regard to current map zoom). What may not be obvious to normal folium users (with no knowledge of JS) is that both the default event handler for markgeocode as well as the one defined in _template would be triggered.

Not sure if there is a need to correct (beyond keeping the current default of 11). Can you explain more?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if there is a need to correct (beyond keeping the current default of 11).

That's good then. It was more a question for you. We can keep it like it is now then.

@Conengmo Conengmo changed the title expanding Geocoder plugin to support other built-in providers defined in leaflet-control-geocoder Geocoder plugin: support other built-in providers Jan 10, 2024
@Conengmo Conengmo merged commit 0ee09a6 into python-visualization:main Jan 16, 2024
12 checks passed
@Conengmo
Copy link
Member

Thanks @prusswan! Nice addition!

hansthen pushed a commit to hansthen/folium that referenced this pull request Jan 24, 2024
…on#1852)

* expanding Geocoder plugin to support other built-in providers supported by leaflet-control-geocoder

* Added geocode_zoom option for setting zoom level used to display the geocode result

* fixed docstring and type notation for geocode_zoom

* dropped geocode_ prefix in arguments

* fixed import block (ruff --fix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants