SPB Git

Repository Public

geo.ts 7.4 KB 172 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : sdk/web/src/geo.ts9 * Module           : sdk10 * Repository       : https://git.spboucher.ai/ka-maps-engine11 * Created          : 2026-12-0112 * Last Modified    : 2026-12-0113 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: support@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Recherche et géocodage inverse : appels à geo.spboucher.ai faits par le SDK (pas par le moteur),43// utilisables sans carte, côté navigateur comme côté serveur (Node 18+, `fetch` global).4445import type { LngLat } from './types.js';46import { KaMapError } from './types.js';4748export const DEFAULT_GEO_ENDPOINT = 'https://geo.spboucher.ai';4950export interface GeoResult {51  id: string;52  type: string;53  label: string;54  lon: number;55  lat: number;56  score?: number;57  approx?: boolean;58  housenumber?: string;59  street?: string;60  municipality?: string;61  borough?: string;62  postcode?: string | null;63  [k: string]: unknown;64}65export interface GeoSearchResponse {66  results: GeoResult[];67  attribution: string;68  [k: string]: unknown;69}70export interface GeoReverseResponse {71  address?: (GeoResult & { distance_m?: number }) | null;72  attribution: string;73  [k: string]: unknown;74}75export interface GeoBoundary {76  id: string;77  level: string;78  code: string;79  name: string;80  area_km2?: number;81  [k: string]: unknown;82}83export interface GeoSearchOptions {84  /** Favorise les résultats proches de ce point. */85  near?: LngLat;86  /** 1 à 25 (défaut du service : 8). */87  limit?: number;88  /** Types voulus (`address`, `street`, `place`, `postcode`…), séparés par des virgules côté service. */89  types?: string[];90  endpoint?: string;91  signal?: AbortSignal;92}93export interface GeoReverseOptions {94  endpoint?: string;95  signal?: AbortSignal;96}9798async function getJson<T>(url: string, signal?: AbortSignal): Promise<T> {99  let res: Response;100  try {101    res = await fetch(url, { signal, headers: { accept: 'application/json' }, credentials: 'omit' });102  } catch (cause) {103    if ((cause as { name?: string })?.name === 'AbortError') throw cause;104    throw new KaMapError('network', `geo : service injoignable (${url})`, { cause });105  }106  if (!res.ok) {107    let detail = '';108    try {109      const body = (await res.json()) as { error?: string; message?: string };110      detail = body.error ?? body.message ?? '';111    } catch {112      /* corps non JSON */113    }114    throw new KaMapError('network', `geo : HTTP ${res.status}${detail ? ` — ${detail}` : ''}`);115  }116  return (await res.json()) as T;117}118119function root(endpoint?: string): string {120  return (endpoint ?? DEFAULT_GEO_ENDPOINT).replace(/\/+$/, '');121}122123export function createGeo(defaultEndpoint?: string) {124  return {125    /** Recherche d'adresses, de voies, de lieux et de codes postaux. */126    search(q: string, options: GeoSearchOptions = {}): Promise<GeoSearchResponse> {127      const query = q.trim();128      if (!query) return Promise.resolve({ results: [], attribution: '' });129      const p = new URLSearchParams({ q: query.slice(0, 120) });130      if (options.near) p.set('near', `${options.near[0]},${options.near[1]}`);131      if (options.limit != null) p.set('limit', String(Math.max(1, Math.min(25, Math.round(options.limit)))));132      if (options.types?.length) p.set('types', options.types.join(','));133      return getJson<GeoSearchResponse>(`${root(options.endpoint ?? defaultEndpoint)}/v1/search?${p}`, options.signal);134    },135    /** Adresse la plus proche d'un point, avec ses découpages administratifs. */136    reverse(lngLat: LngLat, options: GeoReverseOptions = {}): Promise<GeoReverseResponse> {137      const p = new URLSearchParams({ lon: String(lngLat[0]), lat: String(lngLat[1]) });138      return getJson<GeoReverseResponse>(`${root(options.endpoint ?? defaultEndpoint)}/v1/reverse?${p}`, options.signal);139    },140    /** Découpages administratifs (région, MRC, municipalité, arrondissement…) qui contiennent un point. */141    boundariesAt(lngLat: LngLat, options: GeoReverseOptions = {}): Promise<{ boundaries: GeoBoundary[]; attribution: string }> {142      return this.get('/v1/boundaries', { lon: lngLat[0], lat: lngLat[1] }, options);143    },144    /** Contour d'un découpage (`id` tel que rendu par `boundariesAt`, ex. `mrc/66`), simplifié pour un zoom. */145    boundary(id: string, options: GeoReverseOptions & { zoom?: number; tolerance?: number } = {}): Promise<Record<string, unknown>> {146      const path = id.split('/').map(encodeURIComponent).join('/');147      return this.get(`/v1/boundaries/${path}`, { zoom: options.zoom, tolerance: options.tolerance }, options);148    },149    /** Lieux à proximité d'un point (`kinds` : genres voulus ; `radius` en mètres ; `limit` par genre). */150    nearby(lngLat: LngLat, options: GeoReverseOptions & { kinds?: string[]; radius?: number; limit?: number } = {}): Promise<{ items: Record<string, unknown>[]; count: number; attribution: string }> {151      return this.get('/v1/nearby', { lon: lngLat[0], lat: lngLat[1], kinds: options.kinds?.join(','), radius: options.radius, limit: options.limit }, options);152    },153    /** Altitude du terrain en un point (mètres, avec source et référentiel). */154    elevation(lngLat: LngLat, options: GeoReverseOptions = {}): Promise<{ elevation_m: number | null; source: string; [k: string]: unknown }> {155      return this.get('/v1/elevation', { lon: lngLat[0], lat: lngLat[1] }, options);156    },157    /**158     * Appel direct d'une route du service (`/v1/isochrone`, `/v1/route`, `/v1/measure`, `/v1/boundaries/search`…) :159     * les paramètres indéfinis sont omis, les erreurs deviennent des `KaMapError` de code `network`.160     */161    get<T = Record<string, unknown>>(path: string, params: Record<string, string | number | boolean | undefined> = {}, options: GeoReverseOptions = {}): Promise<T> {162      const p = new URLSearchParams();163      for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== '') p.set(k, String(v));164      const qs = p.toString();165      return getJson<T>(`${root(options.endpoint ?? defaultEndpoint)}${path.startsWith('/') ? path : `/${path}`}${qs ? `?${qs}` : ''}`, options.signal);166    },167  };168}169170/** `geo.search(q, {near, limit})`, `geo.reverse([lon, lat])` sur geo.spboucher.ai. */171export const geo = createGeo();172
Files main
Menu

Theme