Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict Leaflet-control-geocoder results by city or bbox?

I'm trying to restrict results of Leaflet geocoder (using the Nominatim provider) to one city by using geocodingQueryParams. But suggestions and results are still for whole world. I've tried several modifications (geocodingQueryParams:'liberec' / geocodingQueryParams:'city=liberec' / geocodingQueryParams:'q=liberec') but with no success. Do you have some suggestions? Or is it possible to filter by bbox in this plugin?

My code:

var geocoder=L.Control.geocoder({
    placeholder: 'Hledej...',
    errorMessage: 'Nenašli jsme :(',
    defaultMarkGeocode: false,
    geocoder: new L.Control.Geocoder.Nominatim({
        geocodingQueryParams:'liberec'
        })
})
.on('markgeocode', function(e) {
    var bbox = e.geocode.bbox;
    var poly = L.polygon([
         bbox.getSouthEast(),
         bbox.getNorthEast(),
         bbox.getNorthWest(),
         bbox.getSouthWest()
    ]);
    map.fitBounds(poly.getBounds());
}).addTo(map);

I'm using Leaflet version 1.5.1.

like image 544
daniel.vrbik Avatar asked Sep 15 '25 09:09

daniel.vrbik


1 Answers

Let me quote Nominatim's documentation:

Result limitation

[...]

viewbox=<x1>,<y1>,<x2>,<y2>

The preferred area to find search results. Any two corner points of the box are accepted in any order as long as they span a real box.

Also, note that the geocodingQueryParams option from Leaflet-control-geocoder's Nominatim provider takes an Object, not a String; URL query parameters are usually given as a set of key-value pairs, with the parameter name as the key and the parameter value as the value.

Therefore, you can do something like:

var geocoder=L.Control.geocoder({
    geocoder: new L.Control.Geocoder.Nominatim({
        geocodingQueryParams: {
            "viewbox": "14.07,49.02,24.02,54.85"
        }
    })
});

If you have an instance of L.LatLngBounds instead of a <x1>,<y1>,<x2>,<y2> string, you can leverage toBBoxString():

var bbox = L.latLngBounds(/* stuff */);

var geocoder=L.Control.geocoder({
    geocoder: new L.Control.Geocoder.Nominatim({
        geocodingQueryParams: {
            "viewbox": bbox.toBBoxString()
        }
    })
});

Nominatim also allows for country and city parameters, but those are structured query parameters, only to be used when there's no query string. The following will NOT work as expected:

var geocoder=L.Control.geocoder({
    geocoder: new L.Control.Geocoder.Nominatim({
        geocodingQueryParams: {
            "country": "FR",
            "city": "Paris"
        }
    })
});
like image 132
IvanSanchez Avatar answered Sep 17 '25 23:09

IvanSanchez