Search code examples
python-3.xoverridinggisfolium

How to overide a feature method in Folium


I am using the LatLngPopup() Folium function to get the map coordinates to pop-up when I click on a map. However, the accuracy is severely limited to only 4 decimals, which are useless when you are zoomed into a small area.

class LatLngPopup(MacroElement):
    """
    When one clicks on a Map that contains a LatLngPopup,
    a popup is shown that displays the latitude and longitude of the pointer.
    """
    _template = Template(u"""
            {% macro script(this, kwargs) %}
                var {{this.get_name()}} = L.popup();
                function latLngPop(e) {
                    {{this.get_name()}}
                        .setLatLng(e.latlng)
                        .setContent("Latitude: " + e.latlng.lat.toFixed(4) +
                                    "<br>Longitude: " + e.latlng.lng.toFixed(4))
                        .openOn({{this._parent.get_name()}});
                    }
                {{this._parent.get_name()}}.on('click', latLngPop);
            {% endmacro %}
            """)  # noqa

    def __init__(self):
        super(LatLngPopup, self).__init__()
        self._name = 'LatLngPopup'

I want to override this class with better precision, and tried to use something like this:

class GetLatLngPopup(LatLngPopup):
    _template = Template(u"""
            {% macro script(this, kwargs) %}
                var {{this.get_name()}} = L.popup();
                function latLngPop(e) {
                    {{this.get_name()}}
                        .setLatLng(e.latlng)
                        .setContent("Latitude: " + e.latlng.lat.toFixed(7) +
                                    "<br>Longitude: " + e.latlng.lng.toFixed(7))
                        .openOn({{this._parent.get_name()}});
                    }
                {{this._parent.get_name()}}.on('click', latLngPop);
            {% endmacro %}
            """)

    def __init__(self):
        super(GetLatLngPopup, self).__init__()
        self._name = 'GetLatLngPopup'

However, this is not working, giving the error:

class GetLatLngPopup(LatLngPopup):
NameError: name 'LatLngPopup' is not defined

Solution

  • As always, when you start asking the right questions, you sometimes find the answer sooner, than you expected.

    The solution to the above was that I needed to re-import the specific functions I am overriding with:

    from folium.features import LatLngPopup
    from jinja2 import Template
    
    # Then use my own class without the folium prefix:
    #folium.LatLngPopup().add_to(m)
    GetLatLngPopup().add_to(m)
    

    Then it works!