diff --git a/umap/static/umap/js/modules/autocomplete.js b/umap/static/umap/js/modules/autocomplete.js index 8ce17a4c..38ac27b7 100644 --- a/umap/static/umap/js/modules/autocomplete.js +++ b/umap/static/umap/js/modules/autocomplete.js @@ -249,6 +249,10 @@ export class BaseAjax extends BaseAutocomplete { } } + buildUrl(value) { + return Util.template(this.url, { q: encodeURIComponent(value) }) + } + async search() { let val = this.input.value if (val.length < this.options.minChar) { @@ -258,7 +262,7 @@ export class BaseAjax extends BaseAutocomplete { if (val === this.cache) return this.cache = val val = val.toLowerCase() - const url = Util.template(this.url, { q: encodeURIComponent(val) }) + const url = this.buildUrl(val) this.handleResults(await this._search(url)) } diff --git a/umap/static/umap/js/modules/importers/communesfr.js b/umap/static/umap/js/modules/importers/communesfr.js index 6b4c0f15..75d889a1 100644 --- a/umap/static/umap/js/modules/importers/communesfr.js +++ b/umap/static/umap/js/modules/importers/communesfr.js @@ -1,5 +1,6 @@ import { DomUtil } from '../../../vendors/leaflet/leaflet-src.esm.js' import { BaseAjax, SingleMixin } from '../autocomplete.js' +import * as Util from '../utils.js' class Autocomplete extends SingleMixin(BaseAjax) { createResult(item) { @@ -8,6 +9,17 @@ class Autocomplete extends SingleMixin(BaseAjax) { label: `${item.nom} (${item.code})`, }) } + + buildUrl(value) { + let url = this.url + let options = { q: encodeURIComponent(value) } + const re = /^(0[1-9]|[1-9][ABab\d])\d{3}$/gm + if (re.test(value)) { + url = "https://geo.api.gouv.fr/communes?code={code}&limit=5" + options = { code: encodeURIComponent(value) } + } + return Util.template(url, options) + } } export class Importer { @@ -25,7 +37,7 @@ export class Importer { textContent: "Importer les contours d'une commune française.", }) const options = { - placeholder: 'Commune…', + placeholder: 'Nom ou code INSEE…', url: 'https://geo.api.gouv.fr/communes?nom={q}&limit=5', on_select: (choice) => { importer.url = `https://geo.api.gouv.fr/communes?code=${choice.item.value}&format=geojson&geometry=contour`