# KptMap (kpt-map) A map with configurable markers: categories carrying a color and an icon, clustering with a count, a details popup whose template depends on the category, a ready-made place card, a legend, an address search and adding locations with the right mouse button. The default engine is Leaflet + OpenStreetMap; the component's API knows nothing about the engine, so a second adapter (Google Maps) swaps in through the provider alone. Import: `import { KptMap, KptMapPoiCard, KptMapSearch } from '@konce-pt/angular/map';` ## Requirements (the application) What follows is for the default engine, Leaflet. The alternative - Google Maps - needs no package and no stylesheet, but it does need an API key and a `mapId`; see the "Engines" section. 1. The **optional** `leaflet` dependency - the library does not install it: pnpm add leaflet 2. Leaflet's stylesheet - like `@angular/cdk/overlay-prebuilt.css`, through `angular.json -> styles[]`, NOT as an `import` in `main.ts` (the Angular CLI would turn that into an orphaned chunk): node_modules/leaflet/dist/leaflet.css Vite/webpack: `import 'leaflet/dist/leaflet.css';` 3. The engine provider at bootstrap: bootstrapApplication(App, { providers: [provideKptLeafletMap()] }); Without the `leaflet` package installed the component still compiles and imports without error - only an attempt to render the map ends with a readable message and instructions. Leaflet is loaded with a dynamic `import()`, so it does not weigh down applications that use no map. ## Selector `kpt-map` - a block element. The height is set by `[height]` (default `480px`). ## Inputs - `locations`: `readonly KptMapLocation[]` - **required** - `categories`: `readonly KptMapCategory[]` - **required** - `country`: `string` = `'PL'` - the initial view preset; an unknown code falls back to Poland - `view`: `{ center, zoom } | null` - an explicit view; overrides `country` - `bounds`: `KptMapBounds | null` - explicit bounds; override `country` and `view` - `restrictToCountry`: `boolean` = `false` - blocks panning outside the country's bounds/`bounds` - `cluster`: `boolean` = `true` - `clusterOptions`: `{ gridSize?, maxZoom?, minPoints? }` - `60 / 16 / 2` by default - `clusterColorBy`: `'dominant' | 'none'` = `'none'` - whether a cluster takes the color of its most numerous category - `legend`: `boolean` = `true` - renders `kpt-map-legend` below the map - `legendCounts`: `boolean` = `true` - counters next to the legend entries - `showUserLocation`: `boolean` = `false` - `followUser`: `boolean` = `false` - recenters the map on every new position - `allowCreate`: `boolean` = `false` - an "Add location" menu under the right mouse button - `search`: `boolean` = `false` - the address search in the map's corner; it requires the `KPT_MAP_GEOCODER` port **with a `search()` method**, and without it the field does not render - `searchPlaceholder`: `string` = `''` - an empty value hands it over to the dictionary - `searchOptions`: `{ minLength?, debounce?, limit?, countryCodes? }` - `3 / 300 / 5` by default - `searchZoom`: `number` = `16` - the zoom for a result with no bounds of its own - `searchMarker`: `boolean` = `true` - a temporary pin at the found point - `searchSpeech` (and `speech` of `kpt-map-search`) needs `provideKptSpeech()` in the app. - `searchSpeech`: `boolean` = `false` - a microphone in the search field: a click clears the phrase and one spoken utterance becomes the query (same `debounce`/`minLength` as typing); `searchSpeechLang`: `string | null` - its language (BCP 47); `searchSpeechColor` - listening colour (theme colour by default). Hidden without browser support. `kpt-map-search` on its own takes `speech` / `speechLang` / `speechColor` - `geocoder`: `KptMapGeocoderPort | null` = `null` - **this** map's geocoder; it wins over `KPT_MAP_GEOCODER` from DI and serves both directions: the search and the address suggestions in the create form - `popupLayout`: `'plain' | 'card'` = `'plain'` - `card` hands the popup over to the content entirely: no padding, wider (`--kpt-map-popup-width-card`), scrolling once it exceeds `--kpt-map-popup-max-height`, and no built-in close button (the card supplies one) - `distanceFrom`: `KptLatLng | null` = `null` - the reference point for the distance handed to the popup template; `null` means "the user's position from `KPT_MAP_GEOLOCATION`" - `height`: `string` = `'480px'` - `tileUrl`: `string | null` - OSM tiles by default (see "Tiles" below); **irrelevant for the Google engine** - `attribution`: `string | null` - `© OpenStreetMap contributors` by default; likewise - `engine`: `KptMapEngineFactory | null` - this map's engine; it wins over `KPT_MAP_ENGINE` from DI (see "Engines") ## Model / events - `hiddenCategories`: `model` - the ids of categories hidden in the legend - `locationClick`: `KptMapLocation` - `clusterClick`: `KptMapCluster` - `locationCreate`: `{ at, categoryId, value }` - the component appends **nothing** to `locations`; the application is the source of truth - `searchSelect`: `KptMapSearchResult` - a suggestion was picked; the map has **already** moved the view itself - `viewChange`: `{ center, zoom, bounds }` - after the map's movement ends - `userPositionChange`: `KptMapUserPosition | null` - `userLocationError`: `KptMapGeolocationError` - `engineError`: `unknown` - the engine failed to start (no factory, no `leaflet` package, a rejected Google key); the error is also logged to the console, and destroying the component mid-`init()` waits for it to finish ## KptMapCategory { id: 'closure', label: 'Closure', color: 'danger', icon: 'lock', shape: 'pin', legend: true, fields: [ ... ] } `color` is a role from the semantic layer (`primary | success | warning | danger | info | muted`) or a ready `var(--kpt-*)`. Literals (`#c00`, `rgb(...)`) are blocked at the type level - the repo's contract requires tokens. A role yields **three** variables, depending on what the element is: | function | for what | `muted` gives | |---|---|---| | `colorVarOf()` | a background (a pin, a legend dot, a cluster) | `--kpt-color-muted` (neutral-100) | | `contrastVarOf()` | a glyph **on** that background | `--kpt-color-on-muted` (neutral-800) | | `foregroundVarOf()` | a glyph standing straight on the surface, with no background | `--kpt-color-on-surface-muted` | Getting it wrong only hurts with `muted`, because it is the only role whose `--kpt-color-*` is a background color rather than a content one - the rest are saturated and read fine in either function. Hence the third function: the place card paints the category icon straight onto the card's background, and `colorVarOf()` would give it neutral-100 on white. `icon` is a name from `KptIconRegistry` (the full Tabler set comes with `provideKptTablerIcons()`). `shape`: `pin` (the default, anchored at the tip), `dot`, `square`. ## KptMapLocation { id: 'w1', at: { lat: 51.11, lng: 17.04 }, categoryId: 'opening', title: '2210, Wrocław', data: { ... } } `title` is required - it goes into the marker's `aria-label`. `data` is arbitrary and is handed to the popup template. ## Templates `kptMapPopup` - the details popup, chosen by category. A template with no `category` attribute is the fallback; with no template at all the component shows the title and the category name. {{ loc.title }}

Closure, {{ d.status }}

Open the project card
{{ loc.title }}
Context: `$implicit` = the location, `data` = `location.data` (typed `T | undefined`, because `data` is optional), `category`, `distance`, `close()`. `distance` is the point's distance in **meters** from `[distanceFrom]`, or from the user's position without it. `null` when there is no reference point - geolocation is disabled or was refused. Format it with `formatDistance(meters, locale)` from the core; `kpt-map-poi-card` does it itself. The type of `data` is loose by default - Angular does not carry the generic from `kpt-map` onto a directive embedded in its content. If you want inference, bind `[kptMapPopupTypeFor]` to the same array you feed the map (the input exists solely for that and is unused at runtime):

{{ d?.address }}

A popup opened near the container's edge pans the map so that it fits (auto-pan measures it after the first render - before that we do not know its dimensions). `kptMapCreateForm` - your own create form. Its presence disables the form built from the category schema. ## KptMapPoiCard (kpt-map-poi-card) A ready-made place card for the popup: the distance, a 16:9 photo, a primary button + share + favorite, a category row, expandable opening hours with an open/closed status, and contact rows (phone, website, e-mail, coordinates) with actions and copy-to-clipboard. Inputs: - `poi`: `KptMapPoi` - **required** - `distance`: `number | null` = `null` - meters; `null` hides the distance row - `category`: `KptMapCategory | null` = `null` - the icon, the color and the label of the category row - `primaryLabel`: `string` = `''` - an empty value hides the primary button - `showShare`, `showFavourite`, `closable`: `boolean` = `true` - `favourite`: `model` = `false` - `hoursExpanded`: `model` = `false` Outputs: `primaryAction: KptMapPoi`, `closed: void`, `shared: KptMapPoi`. `KptMapPoi` is **separate from the domain model** - the `location.data -> KptMapPoi` mapping is done by the application. The library does not guess which field is the phone number: { title, address?, photo?, photoAlt?, hours?, phone?, email?, website?, at?, facts?: [{ icon?, label, value }] } `photo` takes a URL or a `data:` string - the card does not tell them apart. Without one it draws a placeholder with an icon instead of collapsing the frame to zero. `facts` are arbitrary "icon, label, value" rows below the contacts. Behaviors worth remembering: - **The photo** sits in a 16:9 frame with `object-fit: cover` on a plain ``, not on `kpt-image` - that one is `inline-block` with `height: auto` and will not hold the frame. - **The hours** are a native disclosure (`aria-expanded` + `aria-controls`), not a `kpt-accordion`: `KptAccordionPanel.title` accepts a plain string, while the header has to fit an icon, a colored status and a chevron. The status is computed by `isOpenAt()`; days are joined by `groupWeek()`. - **The row actions** are always in the DOM. They are hidden only by `@media (hover: hover) and (pointer: fine)`, and `:hover`/`:focus-within` reveals them - on touch and from the keyboard they are available without any tricks. - **Copying** goes through `navigator.clipboard`; without that API the button does not render. On success the icon changes to `check`, and a message goes to `aria-live`. - **Sharing** calls `navigator.share()`, and without it copies the address. The user canceling the sheet is not an error and emits no `shared`. - **The title is a `

`, not an `

`.** Component styles live in `@layer kpt.components`, and an application's CSS outside any layer always beats them - a plain `

` would catch every `h3 { ... }` rule from the page's layout (in the playground that turned the place title into 13-pixel uppercase). To a screen reader it is still a level 3 heading. - The card does not set its own `role` on the host - the `kpt-map` popup is already `role="dialog"`. Anatomy and scrolling: kpt-map-poi-card .kpt-map-poi__head title + close button - fixed .kpt-map-poi__meta distance + address - fixed .kpt-map-poi__scroll photo, actions, category, hours, contacts, aria-live The header stays put, and only `__scroll` scrolls. The distance and the address belong to the header block, because they are part of the place's identity - to make them scroll with the content, just move `__meta` into `__scroll`. The condition for this is that `popupLayout="card"` **hands scrolling to the card**: `.kpt-map__popup-body` then gets `display: flex` and `overflow: hidden`, and the card the popup's full height. As long as the parent container scrolls, the header cannot be pinned without `sticky` and negative margins. The popup itself does not get `overflow: hidden` - the `::after` arrow hangs at `top: 100%` and would be cut off. A card outside a popup (stories, any wrapper with no height limit) does not scroll at all: `__scroll` has `flex: 0 1 auto` and simply grows without a height ceiling. ## Adding locations Right-click -> a menu of categories -> a `kpt-dialog` with a form. By default the form is built from `category.fields` on Signal Forms. Field types and controls: | `type` | control | notes | |---|---|---| | `text` | `kpt-input` | | | `textarea` | `kpt-textarea` | | | `number` | `kpt-input-number` | `min`/`max` from the schema go through validators, not through `[min]` | | `date` | `kpt-datepicker` | `min`/`max` as ISO dates | | `select` / `multiselect` | `kpt-select` (`multiple`) | requires `options` | | `checkbox` | `kpt-checkbox` | `placeholder` serves as the label next to the field | | `tel` | `kpt-input type="tel"` | no format validation - phone numbers can be odd | | `email` | `kpt-input type="email"` | the `email()` validator | | `url` | `kpt-input type="url"` | the `https?://...` pattern | | `image` | `kpt-map-image-field` | a file picker **or** a pasted URL; the value is a `string` | | `hours` | `kpt-map-hours-field` | the value is a `KptMapOpeningHours` | The coordinates from the click are shown but not editable. `image` reads the file with `FileReader.readAsDataURL()` and **sends it nowhere** - the library knows nothing about the application's storage. The 2 MB limit is real, not decorative: a data URL swells by about a third, and the whole value travels in `locationCreate`. Typing a URL clears the chosen file and vice versa. `hours` gives seven rows starting on Monday (day names from `Intl`, not from the dictionary), two ranges per day, a "closed" marker and a "same all week" shortcut that copies Monday onto the rest. A day not marked as closed must have both times - otherwise the form is `invalid`. The time is picked on a `kpt-datepicker selectionMode="time"` (a clock dial, `minuteStep=5`), not on a native `` - that one renders its own system dropdown, which cannot be styled and looks alien among the library's controls. The value is the same: `HH:mm` or an empty string. **A limitation:** with a dynamic schema the model is a `Record`, so the fields are not statically typed. Anyone who needs types supplies their own `kptMapCreateForm`. The "do not scare people with red on a fresh form" gate lives in the presentation (`touched() && invalid()`), not in the validator - per this repo's Signal Forms contract. ## Address suggestions (reverse geocoding) The fields of the "add location" form can fill themselves in with the clicked point's address. Two conditions: the field has an `autofill` pointing at a part of the address, and the map has a port - from DI (`KPT_MAP_GEOCODER`) or from the `[geocoder]` input, which wins. { key: 'city', type: 'text', label: 'City', autofill: 'city' }, { key: 'address', type: 'text', label: 'Address', autofill: 'address' }, The address parts (`KptMapAddressPart`): `street`, `houseNumber`, `address` (street with number), `city`, `postcode`, `state`, `county`, `country`, `countryCode`, `label` (the full address as one string). It works only for `text` and `textarea` fields - a date or a number will not take a fragment of an address. **A suggestion never overwrites what the user typed** - only fields that are empty at the moment of the response are filled in. A missing port or a failed request does not block the form: the fields stay empty, and a note appears under the coordinates. The ready adapter (opt-in, NOT registered by default): providers: [provideKptLeafletMap(), provideKptNominatimGeocoder({ language: 'pl' })] **The Nominatim policy.** The public `nominatim.openstreetmap.org` instance allows at most one request per second, requires a recognizable `Referer`/`User-Agent` and forbids bulk querying; traffic can be blocked without notice, commercial traffic in particular. The adapter queues requests a second apart on its own and aborts them when the dialog closes, but for production put your own instance behind it (`baseUrl`) or a commercial provider through your own `KPT_MAP_GEOCODER`: export interface KptMapGeocoderPort { reverse(at: KptLatLng, options?): Observable; search?(query: string, options?): Observable; resolve?(suggestion: KptMapSuggestion, options?): Observable; } Only `reverse()` is mandatory. Without `search()` the map shows no search field; `resolve()` is described below, with suggestions that carry no coordinates. **The interval between requests (`minIntervalMs`).** The one-second gap is not a property of Nominatim, it is a requirement of the **public OSM instance's** terms - which is why the default depends on `baseUrl`: provideKptNominatimGeocoder() // 1000 ms provideKptNominatimGeocoder({ baseUrl: 'https://geo.local' }) // 0 ms provideKptNominatimGeocoder({ baseUrl: '...', minIntervalMs: 200 }) On your own server there is nothing to respect, and for as-you-type suggestions a one-second delay is the difference between "it works" and "it stutters". `0` also removes the queuing - the requests go out in parallel. When pointing at **someone else's shared** instance, set the value explicitly. Tests and Storybook: `provideKptMapGeocoderStub({ city: 'Warszawa', address: 'Marszałkowska 100' })`. ## Address search (forward geocoding) `[search]` puts a field with suggestions in the map's top right corner. Typing a phrase queries the geocoder port - the **same** one as the address suggestions in the create form, just in the other direction; from DI (`KPT_MAP_GEOCODER`) or from the `[geocoder]` input, which wins. The `search()` method is **optional** in the port: ports written before it existed still compile, and a map without it simply does not render the field. // main.ts - without this there will be no field providers: [provideKptLeafletMap(), provideKptNominatimGeocoder({ language: 'pl' })] Two types, deliberately kept apart: KptMapSuggestion = { id, label, at?, bounds?, address? } // an entry in the list KptMapSearchResult = KptMapSuggestion & { at: KptLatLng } // what comes out of the event `address` is the same `KptMapAddress` as in reverse geocoding - there is no second address model. ### Suggestions with no coordinates (`resolve()`) Most geocoders queried forward (Nominatim, Photon, the Google Geocoding API) give `lat`/`lng` right in the list. **Google Places Autocomplete does not**: it returns a `placeId` and text, and the coordinates come from a separate Place Details call. This is not one provider's quirk - it is what its session-based billing rests on, where a whole run of suggestions plus the final Place Details counts as one event. That is why `search()` returns a `KptMapSuggestion` (with `at` **optional**), and a port may add: resolve?(suggestion: KptMapSuggestion, options?: { language?, signal? }) : Observable; The rule fits in one sentence: **if your `search()` does not return `at`, you must implement `resolve()`.** Anyone returning coordinates right away does not need the method - the field will not even call it. The handling lives in `kpt-map-search`, not in `kpt-map`, so the guarantee holds just the same for a field standing on its own: - a suggestion with `at` -> `selected` fires **immediately**, with no extra request; - a suggestion without `at` -> `resolve()` once, **after the entry is picked**, never while typing; the panel stays open with a "Searching..." note, and `aria-busy` on the field carries that to a screen reader; - `null` or an error -> the label stays in the field, the list comes back (another entry can be picked), and `aria-live` says "no matching places"; - another pick or clearing the field aborts an in-flight request. **`selected` and `searchSelect` always carry coordinates.** The application never checks whether `at` is there. When a port **has no** `resolve()`, suggestions without `at` never reach the list at all: an entry whose click would have nowhere to fly is worse than no entry. The stub can pretend to be such a provider - without it there is no way to demo the path without an API key: provideKptMapGeocoderStub(address, results, { deferCoordinates: true }) **After a suggestion is picked the map moves the view itself.** A result with `bounds` (a city, a region, a province) gets `fitBounds`, and a result without them - `setView` at `[searchZoom]`. The `searchSelect` event fires after the movement and is there for the application's own purposes (moving `[distanceFrom]`, querying for nearby points), not for navigation. The Nominatim adapter **deliberately rejects an overly tight box** and returns the point alone in that case. A single address has a bounding box on the order of 0.0001° there, so `fitBounds` would jump to the top zoom limit on it and every address would land at a different zoom, depending on how the provider traced the building - with the threshold, addresses land at a repeatable `[searchZoom]`, while cities still fit into the frame whole. The rule is held by `isFittableBounds(bounds, minSpan?)` from the core (`KPT_MIN_FIT_SPAN` = 0.001°, that is ~100 m) - it is in the public API, it has tests and it applies to every adapter, not just Nominatim. The threshold only has to be exceeded on **one** axis: a long, narrow street has one microscopic dimension and still deserves `fitBounds`. **Geographic narrowing.** The query gets a `viewbox` from `[bounds]`, or from the `[country]` preset without them - that is bias only, it reorders the results and cuts nothing off. A hard `countrycodes` is only added with `restrictToCountry` (the map will not let the view move outside the country anyway, so a foreign address would be impossible to show) or explicitly through `searchOptions.countryCodes`. **The temporary pin** (`[searchMarker]`, on by default) travels the same path as the other markers - through `engine.setMarkers()` - so it moves with the map frame by frame. It does not belong to `entries()`, so clicking it opens nothing. It disappears once the field is cleared with the x and after a click on the map. The Nominatim policy is **stricter here than for `reverse()`**, because as-you-type suggestions generate series of requests by their nature. The adapter defends itself two ways: the field waits a `debounce` (300 ms) after the last character and does not query below `minLength` (3 characters), while the adapter itself keeps **one queue shared with `reverse()`** - one request per second for the whole client, not per method. An abandoned request (another character, the field closing) is aborted with an `AbortController`. For production, put your own instance or a commercial provider behind it anyway. The queue measures the interval **against the clock** rather than adding a fixed delay before each request: the first one after a quiet moment goes out immediately, and the next waits only for what is left of the second. The upper bound of one request per second stays intact, but the first suggestion no longer costs a second up front. ### KptMapSearch (kpt-map-search) The field itself is a separate component - like the legend, so that it can stand outside the map (an application toolbar, a side panel): Inputs: `placeholder`, `minLength` (3), `debounce` (300), `limit` (5), `countryCodes`, `viewbox`, `disabled`, `geocoder` (this field's port; it wins over DI - that is how `kpt-map` passes it in). Outputs: `selected: KptMapSearchResult`, `cleared: void`. Without a port that has `search()` the field renders **disabled**, rather than pretending it will find anything. **Why not `kpt-autocomplete`** - the question keeps coming back, so in writing: that one filters options client-side (`includes(q)`), so a geocoder result that tolerates typos or is phrased differently would drop off the list; its value is a plain `string`, so there is nothing to carry coordinates in; and it stands on CDK Overlay, which would add `@angular/cdk/overlay-prebuilt.css` to the map's requirements when it otherwise needs none. The suggestion panel is therefore drawn directly in the Angular layer over the map, just like the popup and the right-click menu. The debounce stands on a `setTimeout` inside an effect with `onCleanup`, not on rxjs operators: this package's ports use `Observable`/`of` exclusively, and rxjs is not declared as the library's `peerDependency` (it arrives transitively through `@angular/core`). The typed text and the phrase to query are **two separate signals**. Picking a suggestion writes its label into the field but does not touch the phrase - otherwise a pick would immediately fire another query for what we just found. ## Legend `kpt-map-legend` - a separate component, so that it can be placed outside the map. The entries are buttons with `aria-pressed`; a click hides the category (it also disappears from the clusters, and the counters drop). Inputs: `categories` (required), `hidden` (a model), `counts`, `orientation`, `interactive`. ## Geolocation `[showUserLocation]` enables the marker for the user's own position (the `user` icon) with an accuracy circle and a "center on me" control. The position comes through a DI port: KPT_MAP_GEOLOCATION -> KptBrowserGeolocation (by default) provideKptMapGeolocationStub({ lat: 52.23, lng: 21.01 }) // Storybook, tests The Geolocation API works **only in a secure context** (HTTPS or `localhost`). On `http://` with an IP address the browser refuses - that is not a bug in the component. A denied permission disables the control and emits `userLocationError`; the component shows no alert of its own, leaving the decision about a message to the application. Under SSR the port returns `null`. ## Engines The engine is supplied by a factory under the `KPT_MAP_ENGINE` token, and the component talks to it through the `KptMapEngine` interface (zero Leaflet types in the signatures). The split of rendering: - tiles, panning, zoom, **markers and clusters** -> the engine (`L.divIcon` with HTML from the core), - **the popup, the controls, the menu, the legend, the dialog** -> an Angular layer over the map container. Markers go through the engine because they have to move with the map frame by frame (Leaflet does that with a single `transform` on the pane). There is one popup at a time, so recomputing its position with `engine.project()` on every movement is cheap - and it buys full Angular in the content and one implementation for both engines. ### Two engines provideKptLeafletMap() // the default, no key and no account provideKptGoogleMap({ apiKey, mapId }) // the Google Maps JavaScript API Leaflet needs the (optional) `leaflet` package and `leaflet/dist/leaflet.css`. Google needs **no npm package at all** - the API is pulled in by a script with the first map - but it does need a key, a billing account with a card and a `mapId` from the console (*Map management -> Create Map ID*). Without `mapId` `AdvancedMarkerElement` does not work, which means there will be no markers. | | `leaflet` | `google` | | ---------------------- | ----------------------------- | ----------------------------------------- | | `[tileUrl]`/`[attribution]` | work, swappable on the fly | **ignored** - Google supplies the tiles | | attribution | Leaflet's control (ODbL) | the logo and ToS links are built in, **do not cover them** | | key / account | not needed | an API key + billing with a card | | cost | OSM tiles (no SLA) | the Dynamic Maps SKU: 10k loads/month free | | the Google geocoder | **not allowed** | allowed | | zoom | integer, max 19 | fractional on gestures, above 21 | **The last row is the reason this engine exists.** The Google Maps Platform Service Specific Terms §6.2 (Geocoding API) and §14.2 (Places API) forbid using their results "in conjunction with a non-Google map". A Google adapter under `KPT_MAP_GEOCODER` is therefore compliant **only** with the `google` engine - not with the default Leaflet. The library itself ships no such adapter; that is the application's decision and code. That is why the geocoder is per map rather than per application: the `[geocoder]` input (below) lets you put a Leaflet map with an OSM geocoder next to a Google map with a Google geocoder. A global provider could not settle that - it would have to break the rule on one of the two sides. ### `[engine]` - two maps, two engines, one page The input takes a factory and wins over `KPT_MAP_ENGINE` from DI. Without it nothing changes. readonly google: KptMapEngineFactory = () => createGoogleEngine({ apiKey, mapId }); It is read once, at initialization - swapping it after startup does not reload the map. No engine in either source produces a readable error with instructions, not a `NullInjectorError`. ### `[geocoder]` - the port follows the engine Symmetrical to `[engine]` and for the same reason: a Google geocoder may only be shown with a Google map, and that is a property of the **map**, not of the application. The input wins over `KPT_MAP_GEOCODER` from DI and reaches both the search and the create form. Unlike `[engine]` it is read **reactively**: swapping the port clears the suggestion list and queries the new provider from the next phrase on. `null` in both sources means what having no port means today: the search field does not render, and the form suggests no address. `kpt-map-search` and `kpt-map-create-dialog` have the same input when they stand outside a map. **When writing a Google adapter, go through the SDK, not through REST.** The `maps.googleapis.com/maps/api/geocode/json` web service rejects keys restricted by domain: { "status": "REQUEST_DENIED", "error_message": "API keys with referer restrictions cannot be used with this API." } and that is the only restriction that makes sense for a key sitting in plain sight in a browser bundle. CORS on that endpoint works, so there is not even a network error - a `200` arrives with `REQUEST_DENIED` in the body, easy to miss. `google.maps.Geocoder` from the loaded SDK authorizes the same way the map itself does, so it works with the same key - the same SKU, just a different route. Access to the API comes from the exported loader (the same one the engine uses): const maps = await loadGoogleMapsApi({ apiKey, language: 'pl' }); const { Geocoder } = await maps.importLibrary('geocoding'); const { results } = await new Geocoder().geocode({ address: 'Marszałkowska 100, Warszawa' }); Mind the shape of the response: the SDK returns `location` and `viewport` as objects with methods (`lat()`, `getNorthEast()`), not as fields the way REST does. An SDK request **cannot be aborted**, so the `signal` from the port's options has nothing behind it - unsubscribing merely stops listening. An adapter from start to finish: `apps/playground/src/pg-map.google-geocoder.ts`. The engine lands on the host as `[data-engine]` (`leaflet` | `google`) - that attribute is what the few differences are styled by, such as the accuracy circle (an SVG circle in Leaflet, an element with a background in Google, because `google.maps.Circle` takes colors in its options while tokens are the rule here). The Google adapter computes `project()`/`unproject()` **in the core** (`core/geo.ts`) rather than with `map.getProjection()`: that one can be `null` until the first `idle` and needs converting into container pixels anyway. As a result the popup lands pixel for pixel where it does with Leaflet, agrees with the clustering and copes with fractional zoom. ## Core (pure TS) `@konce-pt/angular/map` exports the computation core - with no Angular and no engine, portable to the React port: `clusterLocations`, `dominantCategory`, `countByCategory`, `isSplittable`, `project`/`unproject`/`boundsOf`/`haversine`/`metersPerPixel`/`zoomForBounds`/`isFittableBounds`, `KPT_MAP_COUNTRIES`/`countryPreset`/`resolveCountryView`, `renderMarkerHtml`/`renderClusterHtml`/`colorVarOf`/`contrastVarOf`/`foregroundVarOf`, `formatDistance`/`formatLatLng` and the opening hours: `parseTime`, `formatTime`, `isoWeekday`, `isOpenAt`, `isAlwaysOpen`, `nextChange`, `weekdayName`, `groupWeek`, `emptyWeek`. The hours model: `KptMapOpeningHours` = an array of `{ day: 1-7 (ISO), closed?, ranges: [{ from, to }] }` in `HH:MM` of the place's local time. A `to` lower than or equal to `from` means "past midnight"; `24:00` is a valid end of day and does **not** cross midnight. A missing day = closed. `isOpenAt()` checks two days - the current one and the previous one - because a `22:00-01:00` range covers the early hours of the next day. `groupWeek()` joins adjacent days with an identical schedule (`Mon-Fri`), but it does **not** wrap the week across the Sunday-Monday boundary: a week reads linearly and wrapping would be confusing. The core and both engine adapters live in `@konce-pt/map` - plain TypeScript, tested (`node --test`), shared with the React port. ## Clustering - how it works and what it does not do A grid in pixel space: points are projected onto world pixels for the current zoom and assigned to `gridSize` px cells. The algorithm is O(n) and deterministic - the same data set always yields the same clusters with the same ids. The cluster center is averaged **in pixels, not in degrees**: Mercator stretches degrees toward the poles, so an average in degrees lands beside the visual center of the dots on screen. The limitations (deliberate): - a cluster can "jump" when a cell boundary is crossed while zooming - that is the price for skipping the preprocessing hierarchical clustering requires; - **there is no spiderfy.** Points with identical coordinates stay together at every zoom, so clicking such a cluster opens a popup listing the entries instead of zooming forever (`isSplittable()` recognizes that case); - above `clusterMaxZoom` (16 by default) clustering is switched off. ## Tiles - the OSM policy The default `https://tile.openstreetmap.org/{z}/{x}/{y}.png` is a **best-effort service with no SLA**. The OSM Foundation requires visible attribution and a sensible `User-Agent`/`Referer`, forbids pre-fetching and reserves the right to block traffic without notice - commercial traffic in particular. The default source is there so that the demo works right away. **For production, put your own or a commercial tile server behind it** through `[tileUrl]` + `[attribution]`. Do not remove the attribution - it is a license requirement, not decoration. ## Tokens `--kpt-map-bg`, `--kpt-map-border`, `--kpt-map-radius`, `--kpt-map-popup-bg`, `--kpt-map-popup-shadow`, `--kpt-map-popup-width`, `--kpt-map-popup-width-card`, `--kpt-map-popup-max-height`, `--kpt-map-search-width`, `--kpt-map-search-panel-max-height`, `--kpt-map-poi-media-radius`, `--kpt-map-poi-row-hover`, `--kpt-map-cluster-bg`, `--kpt-map-cluster-fg`, `--kpt-map-marker-size`, `--kpt-map-height` (from `[height]`). Marker and cluster colors come from the category roles: `--kpt-color-{success,warning,danger, info,primary,muted}` and their `-contrast` variants. ## Leaflet's stacking context - do not touch `.kpt-map .leaflet-container` gets `z-index: 0`, to close Leaflet's z-index scale (panes 200-700, controls 800) inside its own stacking context. Without that the panes compete directly with the Angular layer stretched over the map - and the popup (`z-index: 3`), the zoom controls (2) and the right-click menu (4) lose and are **painted under the tiles**. The bug is insidious, because a hit test does not show it: the panes and tiles have `pointer-events: none`, so `document.elementFromPoint` returns the popup as the topmost element even though the user cannot see it. The only reliable test is a screenshot. The scale of the Angular layer over the map: zoom controls `2`, the popup `3`, the right-click menu `4`, the search `5` (an expanded suggestion panel has to cover everything above). ## The map does not style child components' hosts - do not "simplify" The search is positioned by a **wrapper**, `