@geosdi/ngx-geocoding
v3.0.1
Published
Component to get a list of place with a geocoding service
Maintainers
Readme
@geosdi/ngx-geocoding
Address search for Angular, from one or more sources tried in order.
Out of the box it queries Nominatim (OpenStreetMap), which needs no API key and is what this library has always done. Google can be added on top: the library never sees your key, it uses the Maps JS SDK the host application already loads in the page.
A source that is not usable is skipped, and that is not an error: the same configuration therefore works both on a deploy that has a Google key and on one that does not.
Installation
npm i @geosdi/ngx-geocoding --save
Peer dependencies:
"@angular/common": ">=22.0.0",
"@angular/core": ">=22.0.0",
"rxjs": ">=7.8.0"Nominatim is called through HttpClient, so the application must provide it —
provideHttpClient() in the bootstrap providers, or HttpClientModule on a
module-based application.
Configuration
Everything is declared in the application providers, with
provideNgxGeocoding:
import { provideNgxGeocoding } from '@geosdi/ngx-geocoding';
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(),
provideNgxGeocoding({
sources: ['google', 'nominatim'],
country: 'it',
bias: { lat: 40.83, lon: 14.11, radiusM: 25_000 },
}),
],
});| option | type | default | used by |
| -------------- | ------------------------------ | ----------------------- | ------------------------------ |
| sources | ("google" \| "nominatim")[] | ["nominatim"] | the order sources are tried in |
| country | string — two letters, "it" | none | google only |
| bias | { lat, lon, radiusM } | none | google only |
| nominatimUrl | string | public OSM search.php | nominatim only |
bias is a bias, not a filter: an address outside the area is still
reachable, but "via Roma" proposes the nearby one first. Without it Google
orders as it likes, and on a common street name the first suggestion is almost
always somewhere else.
provideNgxGeocoding is optional: not calling it leaves everything as it
was — one source, Nominatim.
Nominatim
Nothing to configure, no key, no Cloud project.
provideNgxGeocoding({
sources: ['nominatim'],
nominatimUrl: 'https://nominatim.example.org/search.php',
});Two things to know:
countryandbiasare not applied to Nominatim. The request is left exactly as this library has always sent it (?q=…&format=jsonv2), because that is the behaviour applications relied on before Google existed here;- the public OpenStreetMap endpoint is a courtesy service with a usage policy
(roughly: one request per second, no bulk traffic). For anything more than
occasional searches point
nominatimUrlat your own instance.
Nominatim results already carry lat and lon.
Two things live outside this library.
1. The SDK tag, in index.html, with the application's own key:
<script
defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&language=it"
></script>- the key belongs to the application and must not be passed to this library: there is no option for it. Loading the SDK here too would also mean two copies of it in the same page;
libraries=places— without it only the third step of the cascade (Geocoder) can answer;languagedecides the language of the suggestions: the library passes no language of its own to the SDK, so the one in the script tag is used;deferis fine: the library waits for the SDK up to 10 s, polling every 100 ms, so a search typed right after startup does not get lost. Withoutlibraries=placesthe wait happens twice, once per Places step, so the first search reaches theGeocoderonly after about 20 s.
2. The Google Cloud project, where the key must have:
- Maps JavaScript API enabled — this is the SDK itself;
- Places API (New) and/or Places API (legacy) enabled, for the suggestions. Either one is enough, see the cascade below;
- Geocoding API enabled, for the last step;
- if the key has HTTP referrer restrictions, every origin the application
is deployed on must be listed. A missing one answers
REQUEST_DENIED, which looks exactly like a product that was never enabled.
Which Google API actually answers
google is a cascade, and it is worth knowing before "simplifying" that
code: from a browser only Places (New) exposes CORS, so a plain fetch to
the other Google APIs cannot work at all. Going through the SDK, search works
with whatever the Cloud project has already enabled:
AutocompleteSuggestion(Places New) — the way Google recommends since 1 March 2025, and the only one offered to new projects. The product behind it must be enabled separately: where it is not, it answers403and the cascade steps down;AutocompleteService(Places legacy) — same incremental suggestions. Google calls it deprecated and "not available to new customers", but it is what answers on projects where the New one was never enabled;Geocoder— no incremental suggestions, usually a single result, but it already carries the coordinates and lives in the base SDK, so it does not needlibraries=places.
Steps go down on their own. A step that is not usable — the class missing
from the SDK, the product not enabled, the key refused — is not retried for the
rest of the session; reloading the page resets that. A step that fails for a
transient reason (OVER_QUERY_LIMIT, UNKNOWN_ERROR, the network) is skipped for
that search only. Each fallback is written to the console with the reason.
Usage
import { Component, inject } from '@angular/core';
import { GeocodingLocation, NgxGeocodingService } from '@geosdi/ngx-geocoding';
@Component({ selector: 'app-search', standalone: true, template: '…' })
export class SearchComponent {
private readonly geocodingService: NgxGeocodingService = inject(NgxGeocodingService);
places: GeocodingLocation[] = [];
chosen?: GeocodingLocation;
search(address: string): void {
this.geocodingService.geocode(address).subscribe({
// An empty list means "nothing found", and also fires subjectNoResults.
next: (res: GeocodingLocation[]) => (this.places = res),
// The error means "I could not search at all": no source was usable.
error: () => (this.places = []),
});
}
// Google suggestions arrive WITHOUT coordinates: resolve() asks for them,
// for the chosen place only. Places that already have them (Nominatim, the
// Geocoder) are returned as they are, so calling it is always correct.
choose(place: GeocodingLocation): void {
this.geocodingService.resolve(place).subscribe((full: GeocodingLocation) => {
this.chosen = full;
if (full.lat && full.lon) {
// Number(undefined) would be NaN: coordinates may be missing if the
// detail request failed, and the place is returned as it was.
this.moveMap(Number(full.lat), Number(full.lon));
}
});
}
private moveMap(lat: number, lon: number): void {
// the application's own: for example map.setView([lat, lon], 16)
}
}geocode errors when no source could be used, and emits an empty list
when the search simply found nothing: "I found nothing" and "I could not
search" are two different things, and a search bar has to tell them apart.
Methods
| Method | action |
| ------------------------------------------------------------------ | -------------------------------------------------------------------- |
| geocode(address: string): Observable<GeocodingLocation[]> | suggestions for the typed text, from the first source that answers |
| resolve(place: GeocodingLocation): Observable<GeocodingLocation> | coordinates of the chosen place; returns it unchanged on failure |
Model
| GeocodingLocation | content |
| ------------------- | ----------------------------------------------------------------------------- |
| display_name | the address to show |
| lat, lon | coordinates, as strings — absent on Google suggestions |
| place_id | id of the place, what resolve needs — always a string, Nominatim's included |
Events
| Subject | type | action |
| ------------------ | ---------------------------- | ------------------------------------ |
| subjectNoResults | Subject<null> | emits when a source finds nothing |
| subjectLocation | Subject<GeocodingLocation> | the chosen place, for the app to use |
| subjectRemove | Subject<null> | the chosen place was removed |
Only subjectNoResults is emitted by the library. subjectLocation and subjectRemove are
channels for the application: nothing in the library calls next on them.
Troubleshooting
Every fallback is logged with console.warn, prefixed [ngx-geocoding].
| what you see | what it means |
| ------------------------------------------- | ---------------------------------------------------------------------------------- |
| SDK Maps senza la libreria 'places' | libraries=places missing from the script tag, or no SDK in the page; ~20 s wait |
| SDK Maps senza il Geocoder | no SDK in the page at all |
| REQUEST_DENIED | product not enabled on the Cloud project, or referrer outside the key restrictions |
| OVER_QUERY_LIMIT | quota or billing on the Google project; transient, the source stays on |
| sorgente "google" non utilizzabile | Google refused for good; the source is off until the page is reloaded |
| sorgente "…" non ha risposto | a transient error; the next source answers this search, the next search retries |
| Nessuna sorgente di geocoding disponibile | no declared source answered this search — this is the error geocode throws |
Only a source that is not usable is switched off for the session: the Maps
SDK missing from the page (after the 10 s wait), a REQUEST_DENIED or a
PERMISSION_DENIED/SERVICE_DISABLED from Google, a 401, 403 or 404 from
Nominatim. It is not asked again until the page is reloaded, so a fix on the
Cloud console needs a reload to be seen.
Any other error is transient: the network dropped for a moment, a 429 from
the public Nominatim (easy to get with search-as-you-type), a 5xx, a response
that is not a list. That search goes on to the next source, or fails with
Nessuna sorgente di geocoding disponibile if there is none, and the next search
tries the source again. Debounce the input all the same: the public Nominatim
asks for one request per second.
Changes in 3.0.1
- A transient error no longer switches a source off for the session. Any
error used to: a
429from Nominatim or a moment offline, and with Nominatim last in the cascade every search failed until the page was reloaded. Now only a source that is not usable (SDK missing, product not enabled, key refused) is switched off; a transient error passes that search on to the next source. The same holds for the steps insidegoogle.OVER_QUERY_LIMITis transient. - The unit tests run (
nx test @geosdi/ngx-geocoding): the spec was written for Karma, usedTestBed.getand had never run here.
Changes in 3.0.0
NgxGeocodingModuleis gone. It was an emptyNgModule, kept only for compatibility: the service isprovidedIn: "root"and the configuration isprovideNgxGeocoding.- The three subjects are
readonlyand typed:subjectNoResultsandsubjectRemoveareSubject<null>(they wereSubject<unknown>), sonext()takesnull, which is what the library and its users already pass. - The Nominatim response is checked where it arrives instead of being read as
any: a response that is not a list is still a refusal of the source, andplace_idfrom Nominatim is now a string, asGeocodingLocationalways declared — it used to be the number Nominatim sends. - Italian JSDoc on the model, no
ascasts left in the sources.
Migrating from 2.x: remove NgxGeocodingModule from any imports (it
provided nothing), and if you compared Nominatim's place_id with a number,
compare it with a string.
Changes in 2.0.0
- A major version because the peer dependencies now ask for Angular 22: an application on an older Angular can no longer install it. The API is unchanged unless a point below says otherwise.
typescriptis no longer a peer dependency: nothing in the package imports it.- The Angular peer dependencies are
>=22.0.0: the library is compiled and tested with Angular 22 only, so it no longer claims to install on older versions. - Compiled with Angular 22. The peer dependencies were already correct and are unchanged.
- This README: the title of the package, which events the library emits, and what a transient error does to a source.
- The code is unchanged.
