|
| 1 | +from branca.element import CssLink, Figure, JavascriptLink, MacroElement |
| 2 | +from jinja2 import Template |
| 3 | + |
| 4 | +from folium.utilities import parse_options |
| 5 | + |
| 6 | +_default_js = [ |
| 7 | + ('Control.Geocoder.js', |
| 8 | + 'https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js') |
| 9 | + ] |
| 10 | + |
| 11 | +_default_css = [ |
| 12 | + ('Control.Geocoder.css', |
| 13 | + 'https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css') |
| 14 | + ] |
| 15 | + |
| 16 | + |
| 17 | +class Geocoder(MacroElement): |
| 18 | + """A simple geocoder for Leaflet that by default uses OSM/Nominatim. |
| 19 | +
|
| 20 | + Please respect the Nominatim usage policy: |
| 21 | + https://operations.osmfoundation.org/policies/nominatim/ |
| 22 | +
|
| 23 | + Parameters |
| 24 | + ---------- |
| 25 | + collapsed: bool, default False |
| 26 | + If True, collapses the search box unless hovered/clicked. |
| 27 | + position: str, default 'topright' |
| 28 | + Choose from 'topleft', 'topright', 'bottomleft' or 'bottomright'. |
| 29 | + add_marker: bool, default True |
| 30 | + If True, adds a marker on the found location. |
| 31 | +
|
| 32 | + For all options see https://github.com/perliedman/leaflet-control-geocoder |
| 33 | +
|
| 34 | + """ |
| 35 | + |
| 36 | + _template = Template(u""" |
| 37 | + {% macro script(this, kwargs) %} |
| 38 | + L.Control.geocoder( |
| 39 | + {{ this.options|tojson }} |
| 40 | + ).on('markgeocode', function(e) { |
| 41 | + {{ this._parent.get_name() }}.setView(e.geocode.center, 11); |
| 42 | + }).addTo({{ this._parent.get_name() }}); |
| 43 | +
|
| 44 | + {% endmacro %} |
| 45 | + """) |
| 46 | + |
| 47 | + def __init__( |
| 48 | + self, |
| 49 | + collapsed=False, |
| 50 | + position='topright', |
| 51 | + add_marker=True, |
| 52 | + **kwargs |
| 53 | + ): |
| 54 | + super(Geocoder, self).__init__() |
| 55 | + self._name = 'Geocoder' |
| 56 | + self.options = parse_options( |
| 57 | + collapsed=collapsed, |
| 58 | + position=position, |
| 59 | + defaultMarkGeocode=add_marker, |
| 60 | + **kwargs |
| 61 | + ) |
| 62 | + |
| 63 | + def render(self, **kwargs): |
| 64 | + super(Geocoder, self).render(**kwargs) |
| 65 | + figure = self.get_root() |
| 66 | + assert isinstance(figure, Figure), ('You cannot render this Element ' |
| 67 | + 'if it is not in a Figure.') |
| 68 | + |
| 69 | + for name, url in _default_js: |
| 70 | + figure.header.add_child(JavascriptLink(url), name=name) |
| 71 | + |
| 72 | + for name, url in _default_css: |
| 73 | + figure.header.add_child(CssLink(url), name=name) |
0 commit comments