feat: allow to search by code INSEE in communes importer

This commit is contained in:
Yohan Boniface 2024-10-03 16:55:02 +02:00
parent d0d40cff99
commit f1619579a4
2 changed files with 18 additions and 2 deletions

View file

@ -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))
}

View file

@ -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`