@geolonia/maps-react 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +113 -3
  2. package/dist/index.d.ts +111 -12
  3. package/dist/index.js +644 -197
  4. package/package.json +11 -10
package/README.md CHANGED
@@ -71,12 +71,17 @@ Root component. Creates a Geolonia map instance and provides it to children via
71
71
  | `minZoom` / `maxZoom` | `number` | Zoom range |
72
72
  | `gestureHandling` | `boolean` | Gesture handling on scrollable pages |
73
73
  | `loader` | `boolean` | Loading animation |
74
- | `geojson` | `string \| FeatureCollection` | GeoJSON (or its URL) drawn with simplestyle. `<Map>` always passes a `center` (default `[0, 0]`), so the view is not fitted to the data: set `center` and `zoom` yourself |
74
+ | `geojson` | `string \| FeatureCollection` | GeoJSON (or its URL) drawn with simplestyle. Without `center`, the view is fitted to the data (`zoom` is only the starting zoom before the fit). With `center`, it is used as is |
75
75
  | `cluster` | `boolean` | Cluster the point features of `geojson` (default `true`). Ignored when `heatmap` or `circle` is set: those never cluster |
76
76
  | `clusterColor` | `string` | Color of the cluster markers |
77
77
  | `choropleth` | `string \| ChoroplethOptions` | Color the polygons of `geojson` by a property value. A property name, or `{ property, colors?, range? }` |
78
78
  | `heatmap` | `boolean \| string \| HeatmapOptions` | Draw the points of `geojson` as a heatmap. `true` for equal weight, a property name for its weight, or `{ weight?, colors? }` |
79
79
  | `circle` | `CircleOptions` | Size and color the points of `geojson` by property values: `{ size?, color?, colors? }` |
80
+ | `extrusion` | `string \| ExtrusionOptions` | Draw the polygons of `geojson` as columns whose height follows a property. A property name sets height and color; `{ height, color? }` sets them apart. Set `pitch` too, or it looks flat |
81
+ | `projection` | `'mercator' \| 'globe'` | Map projection. Changing it after the map exists switches it with `setProjection`, and it is applied again after each `setStyle` (a projection changed with `<GlobeControl>` goes back to the prop then). Removing the prop stops it being applied: the current projection stays until the next `setStyle`, after which maps-core's stored value or the style's own projection applies |
82
+ | `rasterTiles` | `RasterTilesOptions` | Lay another raster tile source under the labels: `{ url, attribution?, opacity? }`. `url` contains `{z}`, `{x}` and `{y}`. Read once when the map is created |
83
+ | `mask` | `string \| MaskOptions` | Darken everything outside a boundary (GeoJSON URL, or `{ geojson, color?, opacity?, outline?, beforeId? }`). Read once when the map is created. To change it on a live map, use `<Mask>` below |
84
+ | `transformRequest` | `RequestTransformFunction` | Rewrite a request before it is sent, as in MapLibre: `(url, resourceType?) => RequestParameters \| Promise<RequestParameters> \| undefined`. Called for Geolonia sources and sprites too (maps-core 0.7.0+), with the URL after maps-core's own changes (API key, session ID, stage host). What you return replaces maps-core's result, so keep those query parameters when you rewrite the URL. Read once when the map is created |
80
85
  | `3d` | `boolean` | Enable 3D mode |
81
86
  | `className` | `string` | CSS class for the container |
82
87
  | `containerStyle` | `CSSProperties` | Inline styles for the container |
@@ -86,7 +91,7 @@ Root component. Creates a Geolonia map instance and provides it to children via
86
91
 
87
92
  `ControlPosition` = `'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'`
88
93
 
89
- `geojson`, `cluster`, `clusterColor`, `choropleth`, `heatmap` and `circle` are read once when the map is created. Changing them afterwards has no effect, so remount `<Map>` with a `key` to change them. To update GeoJSON data on a live map, use `<Source>` and `<Layer>` below.
94
+ `geojson`, `cluster`, `clusterColor`, `choropleth`, `heatmap`, `circle` and `extrusion` are read once when the map is created. Changing them afterwards has no effect, so remount `<Map>` with a `key` to change them. To change them on a live map, use `<SimpleStyle>` below.
90
95
 
91
96
  ```tsx
92
97
  <Map apiKey="YOUR-API-KEY" center={[139.76, 35.68]} zoom={12} geojson={meshes} choropleth="population" />
@@ -129,6 +134,29 @@ Displays a standalone popup at the given coordinates.
129
134
  | `onClose` | `() => void` | Callback when the user closes the popup (close button, click on the map, or `closeOnMove`). Not called when the popup or the whole `<Map>` unmounts |
130
135
  | `children` | `ReactNode` | Popup content |
131
136
 
137
+ ### Controls
138
+
139
+ The controls below each have a component that adds the control to the map and removes it when it unmounts. Except for `<GeocoderControl>` (see [below](#geocodercontrol)), all of them take `position` (`'top-left'`, `'top-right'`, `'bottom-left'` or `'bottom-right'`) and the options of the MapLibre control (`<GlobeControl>` has no options besides `position`). Changing a prop adds the control again; object-valued props (such as `positionOptions`) are compared by reference, so define them outside the render or memoize them.
140
+
141
+ | Component | Default `position` | MapLibre control |
142
+ |---|---|---|
143
+ | `<NavigationControl>` | `'top-right'` | `NavigationControl` (zoom and compass) |
144
+ | `<GeolocateControl>` | `'top-right'` | `GeolocateControl` |
145
+ | `<FullscreenControl>` | `'top-right'` | `FullscreenControl` |
146
+ | `<GlobeControl>` | `'top-right'` | `GlobeControl` (switches the projection between mercator and globe) |
147
+ | `<GeocoderControl>` | `'top-left'` | A search box for Japanese addresses, not a MapLibre control. See [`<GeocoderControl>`](#geocodercontrol) |
148
+ | `<ScaleControl>` | `'bottom-left'` | `ScaleControl` |
149
+ | `<AttributionControl>` | `'bottom-right'` | `AttributionControl` |
150
+
151
+ ```tsx
152
+ <Map apiKey="YOUR-API-KEY">
153
+ <NavigationControl position="bottom-right" />
154
+ <GlobeControl position="bottom-left" />
155
+ </Map>
156
+ ```
157
+
158
+ For any other MapLibre control, use `useControl(() => new SomeControl(), { position })`. To put your own React elements in a control, use `<Control position onAdd onRemove>`: its `children` are rendered inside the control's container.
159
+
132
160
  ### `<Source>` / `<Layer>`
133
161
 
134
162
  Declaratively add MapLibre sources and layers. Nesting `<Layer>` inside `<Source>` automatically inherits the source ID.
@@ -143,7 +171,89 @@ Declaratively add MapLibre sources and layers. Nesting `<Layer>` inside `<Source
143
171
  </Source>
144
172
  ```
145
173
 
146
- `<Layer>` props match `LayerSpecification` from MapLibre GL, plus `beforeId` for insertion order.
174
+ `<Layer>` props match `LayerSpecification` from MapLibre GL, plus `beforeId` for insertion order. Inside `<Source>`, `source` can be omitted. Outside `<Source>`, pass `source` explicitly; a `<Layer>` without a source (except `type="background"`) throws an error that names the layer. When the map's `style` changes, `<Source>` and `<Layer>` are added back to the new style from their current props. A `<Layer>` outside `<Source>` is added back once its `source` exists in the new style.
175
+
176
+ ### `<SimpleStyle>`
177
+
178
+ Draws GeoJSON on the map the way `<Map geojson>` does, but as a child of `<Map>`, so it follows later changes without recreating the map.
179
+
180
+ ```tsx
181
+ <Map apiKey="YOUR-API-KEY" center={[139.76, 35.68]} zoom={12}>
182
+ <SimpleStyle geojson={spots} heatmap="weight" fitBounds />
183
+ </Map>
184
+ ```
185
+
186
+ | Prop | Type | Description |
187
+ |---|---|---|
188
+ | `geojson` | `string \| FeatureCollection` | GeoJSON, or its URL. Changing it updates the data on the live map (the view is not moved) |
189
+ | `id` | `string` | Prefix of the source and layer IDs. Default `'geolonia-simple-style'`, the one `<Map geojson>` uses: give each `<SimpleStyle>` on a map, and any `<Map geojson>`, its own |
190
+ | `cluster`, `clusterColor`, `choropleth`, `heatmap`, `circle`, `extrusion` | same as `<Map>` | Changing one rebuilds the layers from the current data. Object values are compared by content, so a new literal does not rebuild |
191
+ | `fitBounds` | `boolean` | Fit the view to the data when the layers are added (also when rebuilt). Default `false` |
192
+
193
+ The layers are removed when the component unmounts, and added again after the map's `style` changes.
194
+
195
+ `choropleth`, `circle` and `extrusion` colors also take a `ColorMap` (`{ [value]: color }`) in place of a color array, for one color per value. The option types (`ExtrusionOptions`, `ColorMap`, `MaskOptions`, `RasterTilesOptions` and so on) are exported.
196
+
197
+ ### `<Mask>`
198
+
199
+ Darkens everything outside a boundary, such as a city, on a live map. maps-core fixes the source and layer IDs, so a map holds one `<Mask>`.
200
+
201
+ ```tsx
202
+ <Map apiKey="YOUR-API-KEY" center={[139.76, 35.68]} zoom={11}>
203
+ <Mask geojson="/boundary.geojson" outline fitBounds />
204
+ </Map>
205
+ ```
206
+
207
+ | Prop | Type | Description |
208
+ |---|---|---|
209
+ | `geojson` | `string \| Feature \| FeatureCollection \| Polygon \| MultiPolygon \| GeometryCollection` | The boundary, or the URL of one |
210
+ | `color`, `opacity`, `outline`, `beforeId` | same as `MaskOptions` | Changing one rebuilds the mask. Object values are compared by content, so a new literal does not rebuild |
211
+ | `fitBounds` | `boolean` | Fit the view to the boundary when the mask is added (also when rebuilt). Default `false` |
212
+
213
+ The mask is removed when the component unmounts, and added again after the map's `style` changes.
214
+
215
+ ### `<GeocoderControl>`
216
+
217
+ A search box on the map for Japanese addresses. Submitting an address moves the map to it and puts a marker there. Addresses are read with [`@geolonia/normalize-japanese-addresses`](https://github.com/geolonia/normalize-japanese-addresses), a dependency of this package. It carries no address data: a search fetches what it needs from the address data API, and the package keeps what it fetched in memory, so repeated searches in the same city (or the same town, when the address includes a street number) may not hit the network.
218
+
219
+ ```tsx
220
+ <Map apiKey="YOUR-API-KEY" center={[139.76, 35.68]} zoom={10}>
221
+ <GeocoderControl
222
+ onResult={(result) => console.log(result.address, result.center)}
223
+ onError={(error) => console.warn(error.code)}
224
+ />
225
+ </Map>
226
+ ```
227
+
228
+ | Prop | Type | Description |
229
+ |---|---|---|
230
+ | `position` | `ControlPosition` | Default `'top-left'`. Read when the control is added: to change it later, change the component's `key` |
231
+ | `placeholder` | `string` | Placeholder and label of the input. Default `'住所を入力'` |
232
+ | `marker` | `boolean` | Put a marker at the result. Default `true` |
233
+ | `fitBounds` | `boolean` | Move the map to the bounds of the result. Default `true` |
234
+ | `onResult` | `(result: GeocodeResult, address: string) => void` | Called when an address is found. `address` is what was typed |
235
+ | `onError` | `(error: GeocodeError) => void` | Called when a search fails. `error.code` is `ZERO_RESULTS` (no position found), `INVALID_REQUEST` (empty input) or `ERROR` (the address data could not be loaded) |
236
+
237
+ The input has `aria-invalid` after a failed search, until it is edited. When searches overlap, only the latest one changes the map. The control and the marker are removed when the component unmounts.
238
+
239
+ To build your own search UI, call `geocode(address)`. It returns a `GeocodeResult` and rejects with a `GeocodeError`.
240
+
241
+ ```ts
242
+ import { geocode } from '@geolonia/maps-react';
243
+
244
+ const { center, bounds, level, address, partial } = await geocode('東京都台東区上野公園7-7');
245
+ map.fitBounds(bounds);
246
+ ```
247
+
248
+ | Field | Description |
249
+ |---|---|
250
+ | `center` | `[lng, lat]` |
251
+ | `bounds` | `[[west, south], [east, north]]`, to pass to `fitBounds()`. Its size follows `level` |
252
+ | `level` | Accuracy of `center`: `1` prefecture, `2` city, `3` town or chome, `8` house number or lot |
253
+ | `address` | The address down to what `center` stands for. For a town representative point, the street number is left out |
254
+ | `partial` | `true` when `center` is coarser than the input, or text that is not an address (a building name, for example) was left over |
255
+
256
+ Reverse geocoding is not supported.
147
257
 
148
258
  ### `useMap()`
149
259
 
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
+ import { GeoloniaMapOptions, GeoloniaMap, MaskOptions } from '@geolonia/maps-core';
2
+ export { ChoroplethOptions, CircleOptions, ColorMap, ExtrusionColorOptions, ExtrusionHeightOptions, ExtrusionOptions, HeatmapOptions, MaskOptions, RasterTilesOptions } from '@geolonia/maps-core';
1
3
  import * as react from 'react';
2
4
  import { ReactNode, CSSProperties } from 'react';
3
5
  import { Map as Map$1, AttributionControlOptions, FullscreenControlOptions, GeolocateControlOptions, NavigationControlOptions, ScaleControlOptions, IControl, LayerSpecification, PointLike, PositionAnchor, Alignment, SourceSpecification, CanvasSourceSpecification } from 'maplibre-gl';
4
- import { GeoloniaMapOptions, GeoloniaMap } from '@geolonia/maps-core';
5
6
  import * as react_jsx_runtime from 'react/jsx-runtime';
6
7
 
7
8
  type ControlPosition = "top-left" | "top-right" | "bottom-left" | "bottom-right";
@@ -13,31 +14,104 @@ type ControlProps = {
13
14
  };
14
15
  declare function Control({ position, onAdd, onRemove, children, }: ControlProps): react.ReactPortal | null;
15
16
 
16
- declare function useControl<T extends IControl>(factory: () => T, options?: {
17
+ type AttributionControlProps = AttributionControlOptions & {
17
18
  position?: ControlPosition;
18
- }): void;
19
- type NavigationControlProps = NavigationControlOptions & {
19
+ };
20
+ declare function AttributionControl({ position, compact, customAttribution, }?: AttributionControlProps): null;
21
+
22
+ type FullscreenControlProps = FullscreenControlOptions & {
20
23
  position?: ControlPosition;
21
24
  };
22
- declare function NavigationControl({ position, showCompass, showZoom, visualizePitch, }?: NavigationControlProps): null;
25
+ declare function FullscreenControl({ position, container, }?: FullscreenControlProps): null;
26
+
27
+ /** `geocode()` が reject するときの `code`。 */
28
+ type GeocodeErrorCode =
29
+ /** 入力が空です。 */
30
+ "INVALID_REQUEST"
31
+ /** 住所を特定できませんでした。 */
32
+ | "ZERO_RESULTS"
33
+ /** 住所データの取得に失敗しました。 */
34
+ | "ERROR";
35
+ /** `geocode()` が失敗したときに reject される Error です。 */
36
+ declare class GeocodeError extends Error {
37
+ readonly code: GeocodeErrorCode;
38
+ constructor(message: string, code: GeocodeErrorCode);
39
+ }
40
+ type GeocodeResult = {
41
+ /** 位置。[経度, 緯度] の順です。 */
42
+ center: [number, number];
43
+ /** 結果を表示するのに適した範囲。[[西, 南], [東, 北]] の順で、`fitBounds()` にそのまま渡せます。 */
44
+ bounds: [[number, number], [number, number]];
45
+ /**
46
+ * `center` の正確さ。1 都道府県、2 市区町村、3 丁目・町字、
47
+ * 8 住居表示住所・地番の代表点です。
48
+ */
49
+ level: number;
50
+ /** 位置が表す場所までの住所。たとえば位置が町字の代表点なら、番地は含みません。 */
51
+ address: string;
52
+ /**
53
+ * 入力の住所全体には一致しなかった場合に `true` です。位置が入力より粗い代表点
54
+ * だった場合や、住所として読めない文字列(建物名など)が残った場合です。
55
+ */
56
+ partial: boolean;
57
+ };
58
+ /**
59
+ * 日本の住所を検索して、位置と表示に適した範囲を返します。
60
+ *
61
+ * 住所の解釈には `@geolonia/normalize-japanese-addresses` を使います。住所データは
62
+ * 持たず、検索したときに、必要な分を住所データ API から取得します。取得した分は
63
+ * NJA がメモリに保持するので、同じ市区町村(番地まで含めるときは同じ町丁目)を続けて
64
+ * 検索すると、通信しないことがあります。
65
+ *
66
+ * 失敗すると、`code` を持つ {@link GeocodeError} で reject します。
67
+ */
68
+ declare function geocode(address: string): Promise<GeocodeResult>;
69
+
70
+ type GeocoderControlProps = {
71
+ position?: ControlPosition;
72
+ placeholder?: string;
73
+ /** 結果の位置にマーカーを置く。既定は true。 */
74
+ marker?: boolean;
75
+ /** 結果の範囲へ地図を動かす。既定は true。 */
76
+ fitBounds?: boolean;
77
+ /** 住所が見つかったときに呼ばれる。`address` は入力された文字列。 */
78
+ onResult?: (result: GeocodeResult, address: string) => void;
79
+ /** 検索に失敗したときに呼ばれる。`error.code` で原因を区別できる。 */
80
+ onError?: (error: GeocodeError) => void;
81
+ };
82
+ declare function GeocoderControl({ position, placeholder, marker, fitBounds, onResult, onError, }?: GeocoderControlProps): react_jsx_runtime.JSX.Element;
83
+
23
84
  type GeolocateControlProps = GeolocateControlOptions & {
24
85
  position?: ControlPosition;
25
86
  };
26
87
  declare function GeolocateControl({ position, positionOptions, fitBoundsOptions, trackUserLocation, showAccuracyCircle, showUserLocation, }?: GeolocateControlProps): null;
27
- type FullscreenControlProps = FullscreenControlOptions & {
88
+
89
+ type GlobeControlProps = {
28
90
  position?: ControlPosition;
29
91
  };
30
- declare function FullscreenControl({ position, container, }?: FullscreenControlProps): null;
92
+ /** A button that switches the map projection between mercator and globe. */
93
+ declare function GlobeControl({ position, }?: GlobeControlProps): null;
94
+
95
+ type NavigationControlProps = NavigationControlOptions & {
96
+ position?: ControlPosition;
97
+ };
98
+ declare function NavigationControl({ position, showCompass, showZoom, visualizePitch, }?: NavigationControlProps): null;
99
+
31
100
  type ScaleControlProps = ScaleControlOptions & {
32
101
  position?: ControlPosition;
33
102
  };
34
103
  declare function ScaleControl({ position, maxWidth, unit, }?: ScaleControlProps): null;
35
- type AttributionControlProps = AttributionControlOptions & {
104
+
105
+ declare function useControl<T extends IControl>(factory: () => T, options?: {
36
106
  position?: ControlPosition;
37
- };
38
- declare function AttributionControl({ position, compact, customAttribution, }?: AttributionControlProps): null;
107
+ }): void;
39
108
 
40
- type LayerProps = LayerSpecification & {
109
+ type OptionalSource<T> = T extends {
110
+ source: unknown;
111
+ } ? Omit<T, "source"> & {
112
+ source?: string;
113
+ } : T;
114
+ type LayerProps = OptionalSource<LayerSpecification> & {
41
115
  beforeId?: string;
42
116
  };
43
117
  declare function Layer({ beforeId, ...layerSpec }: LayerProps): null;
@@ -135,6 +209,16 @@ type MarkerProps = {
135
209
  };
136
210
  declare function Marker(props: MarkerProps): react.ReactPortal | null;
137
211
 
212
+ type MaskProps = MaskOptions & {
213
+ /** Fit the view to the boundary when the mask is added. Default `false`. */
214
+ fitBounds?: boolean;
215
+ };
216
+ /**
217
+ * Darkens everything outside a boundary (a city, for example). A map holds one
218
+ * `<Mask>`: maps-core fixes the source and layer IDs.
219
+ */
220
+ declare function Mask({ fitBounds, ...options }: MaskProps): null;
221
+
138
222
  type PopupProps = {
139
223
  lat: number;
140
224
  lng: number;
@@ -150,6 +234,20 @@ type PopupProps = {
150
234
  };
151
235
  declare function Popup(props: PopupProps): react.ReactPortal;
152
236
 
237
+ type SimpleStyleOptions = Pick<GeoloniaMapOptions, "cluster" | "clusterColor" | "choropleth" | "heatmap" | "circle" | "extrusion">;
238
+ type SimpleStyleProps = SimpleStyleOptions & {
239
+ /** GeoJSON to draw, or the URL of one. Changing it updates the data on the live map. */
240
+ geojson: NonNullable<GeoloniaMapOptions["geojson"]>;
241
+ /**
242
+ * Prefix of the source and layer IDs. Give each `<SimpleStyle>` on a map its
243
+ * own. Default `"geolonia-simple-style"`, the one `<Map geojson>` uses.
244
+ */
245
+ id?: string;
246
+ /** Fit the view to the data when it is added to the map. Default `false`. */
247
+ fitBounds?: boolean;
248
+ };
249
+ declare function SimpleStyle({ geojson, id, cluster, clusterColor, choropleth, heatmap, circle, extrusion, fitBounds, }: SimpleStyleProps): null;
250
+
153
251
  type SourceProps = (SourceSpecification | CanvasSourceSpecification) & {
154
252
  id: string;
155
253
  children?: ReactNode;
@@ -173,4 +271,5 @@ declare function useMaps(): MapCollection;
173
271
  declare const SourceContext: react.Context<string | null>;
174
272
  declare function useSourceId(): string | null;
175
273
 
176
- export { AttributionControl, type AttributionControlProps, Control, type ControlPosition, type ControlProps, FullscreenControl, type FullscreenControlProps, GeolocateControl, type GeolocateControlProps, Layer, type LayerProps, Map, type MapCollection, MapContext, type MapEventProps, type MapProps, MapProvider, MapProviderContext, type MapProviderProps, type MapRegistry, Marker, type MarkerProps, NavigationControl, type NavigationControlProps, Popup, type PopupProps, ScaleControl, type ScaleControlProps, Source, SourceContext, type SourceProps, useControl, useMap, useMaps, useSourceId };
274
+ export { AttributionControl, Control, FullscreenControl, GeocodeError, GeocoderControl, GeolocateControl, GlobeControl, Layer, Map, MapContext, MapProvider, MapProviderContext, Marker, Mask, NavigationControl, Popup, ScaleControl, SimpleStyle, Source, SourceContext, geocode, useControl, useMap, useMaps, useSourceId };
275
+ export type { AttributionControlProps, ControlPosition, ControlProps, FullscreenControlProps, GeocodeErrorCode, GeocodeResult, GeocoderControlProps, GeolocateControlProps, GlobeControlProps, LayerProps, MapCollection, MapEventProps, MapProps, MapProviderProps, MapRegistry, MarkerProps, MaskProps, NavigationControlProps, PopupProps, ScaleControlProps, SimpleStyleProps, SourceProps };