google-maps-fetch 0.0.0-stage → 0.1.1
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.
- package/LICENSE +21 -0
- package/README.md +262 -2
- package/compat/package.json +5 -0
- package/dist/chunk-DU6WHR7R.cjs +246 -0
- package/dist/chunk-KSK2WERM.js +246 -0
- package/dist/compat.cjs +1215 -0
- package/dist/compat.d.cts +786 -0
- package/dist/compat.d.ts +786 -0
- package/dist/compat.js +1215 -0
- package/dist/index.cjs +127 -0
- package/dist/index.d.cts +108 -0
- package/dist/index.d.ts +108 -0
- package/dist/index.js +127 -0
- package/dist/types-FNou8i90.d.cts +629 -0
- package/dist/types-FNou8i90.d.ts +629 -0
- package/package.json +95 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ninad Sutrave
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,263 @@
|
|
|
1
|
-
#
|
|
1
|
+
# google-maps-fetch
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/google-maps-fetch)
|
|
4
|
+
[](https://github.com/ninadsutrave/google-maps-fetch/actions/workflows/ci.yml)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
A small client for Google Maps Platform's web APIs, built on `fetch`: Places API (New), Routes, Geocoding, Address Validation, Elevation, Time Zone, Geolocation and Roads, plus a `request()` for any other Maps REST API. It has no dependencies and runs on Node, Bun, Deno, Cloudflare Workers and Vercel Edge.
|
|
8
|
+
|
|
9
|
+
It also ships `google-maps-fetch/compat`, a replacement for `@googlemaps/google-maps-services-js` with the same methods and response shapes. Existing code can move to the new APIs by changing one import.
|
|
10
|
+
|
|
11
|
+
Building a search box in React? [google-places-autocomplete-hook](https://github.com/ninadsutrave/google-places-autocomplete-hook) is the browser-side companion: a hook for Places autocomplete on the same new API.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { createClient } from 'google-maps-fetch'
|
|
15
|
+
|
|
16
|
+
const maps = createClient({ key: process.env.GOOGLE_MAPS_KEY! })
|
|
17
|
+
|
|
18
|
+
const { suggestions } = await maps.places.autocomplete({ input: 'Shaniwar Wada', includedRegionCodes: ['in'] })
|
|
19
|
+
const { routes } = await maps.routes.compute({ origin: 'Pune', destination: 'Mumbai' })
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Why
|
|
23
|
+
|
|
24
|
+
- **The legacy APIs are closed to new projects.** Since October 2026, Places API (Legacy), Directions API (Legacy) and Distance Matrix API (Legacy) can no longer be enabled on new Google Cloud projects. `@googlemaps/google-maps-services-js` calls those APIs, so it doesn't work for a new project.
|
|
25
|
+
- **Google's replacements are heavy.** The official clients for the new APIs (`@googlemaps/places`, `@googlemaps/routing`) are built on gRPC. Installing those two adds 37 MB to `node_modules`. `google-maps-fetch` is about 4.4 kB gzipped, and the compat layer about 12 kB.
|
|
26
|
+
- **It runs where your code runs.** It only needs `fetch`, `AbortController` and `crypto.randomUUID`. It's tested on Node 20, 22, 24 and 26. Before release, the same build was run in Bun, Deno, Cloudflare's `workerd` and Vercel's Edge Runtime.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
npm install google-maps-fetch
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Enable the APIs you use on your Google Cloud project (**Places API (New)**, **Routes API**, **Geocoding API**). If your key has API restrictions, add them there too.
|
|
35
|
+
|
|
36
|
+
## Usage
|
|
37
|
+
|
|
38
|
+
### Places
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
// autocomplete and details in one billed session
|
|
42
|
+
const session = maps.places.session()
|
|
43
|
+
const { suggestions = [] } = await session.autocomplete({ input: 'Vaishali FC Road' })
|
|
44
|
+
const place = await session.get(suggestions[0].placePrediction!.placeId) // ends the session
|
|
45
|
+
|
|
46
|
+
place.formattedAddress // "1218/1, FC Road, ..."
|
|
47
|
+
place.location // { latitude: 18.52, longitude: 73.84 }
|
|
48
|
+
|
|
49
|
+
// more fields cost more; ask for what you need
|
|
50
|
+
await maps.places.get(placeId, { fields: ['displayName', 'rating', 'regularOpeningHours'] })
|
|
51
|
+
|
|
52
|
+
await maps.places.searchText({ textQuery: 'misal in Pune', pageSize: 10 })
|
|
53
|
+
await maps.places.searchNearby({
|
|
54
|
+
locationRestriction: { circle: { center: { latitude: 18.52, longitude: 73.85 }, radius: 800 } },
|
|
55
|
+
includedTypes: ['cafe'],
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
// a short-lived URL for a photo name from place.photos
|
|
59
|
+
const { photoUri } = await maps.places.photo(place.photos![0].name, { maxWidthPx: 600 })
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Routes
|
|
63
|
+
|
|
64
|
+
Waypoints can be an address string, coordinates (`{ lat, lng }`, `{ latitude, longitude }` or `[lat, lng]`) or a full `Waypoint`.
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
const { routes = [] } = await maps.routes.compute({
|
|
68
|
+
origin: 'Pune Railway Station',
|
|
69
|
+
destination: { lat: 19.076, lng: 72.8777 },
|
|
70
|
+
travelMode: 'DRIVE',
|
|
71
|
+
languageCode: 'en',
|
|
72
|
+
})
|
|
73
|
+
routes[0].distanceMeters // e.g. 151000
|
|
74
|
+
seconds(routes[0].duration) // e.g. 10800
|
|
75
|
+
routes[0].localizedValues?.distance?.text // "151 km"
|
|
76
|
+
|
|
77
|
+
// every origin to every destination; match results by index
|
|
78
|
+
const elements = await maps.routes.matrix({
|
|
79
|
+
origins: ['Pune', 'Nashik'],
|
|
80
|
+
destinations: ['Mumbai', [18.5204, 73.8567]],
|
|
81
|
+
})
|
|
82
|
+
for (const e of elements) console.log(e.originIndex, e.destinationIndex, e.distanceMeters)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Pass `languageCode` when you show `localizedValues` text. Without it, the Routes API picks a language from the origin: for a route from Pune it answered in Assamese script ("১৫১ কিল’মিটাৰ").
|
|
86
|
+
|
|
87
|
+
### Geocoding
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
const [result] = await maps.geocode({ address: 'FC Road, Pune', components: { country: 'IN' } })
|
|
91
|
+
const nearby = await maps.reverseGeocode({ location: { lat: 18.52, lng: 73.84 } })
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Address Validation
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
const { result, responseId } = await maps.addressValidation.validate({
|
|
98
|
+
address: { regionCode: 'IN', addressLines: ['Shaniwar Wada, Shaniwar Peth', 'Pune 411030'] },
|
|
99
|
+
})
|
|
100
|
+
result.verdict.possibleNextAction // "ACCEPT", "CONFIRM", "FIX", ...
|
|
101
|
+
result.address.formattedAddress
|
|
102
|
+
result.geocode?.location
|
|
103
|
+
|
|
104
|
+
// optional: tell Google which version you used
|
|
105
|
+
await maps.addressValidation.feedback({ responseId, conclusion: 'VALIDATED_VERSION_USED' })
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### Elevation, Time Zone, Geolocation and Roads
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
await maps.elevation({ locations: [[18.52, 73.85]] }) // [{ elevation: 560, location, resolution }]
|
|
112
|
+
await maps.elevation({ path: [pune, mumbai], samples: 20 })
|
|
113
|
+
|
|
114
|
+
await maps.timezone({ location: [18.52, 73.85] }) // { timeZoneId: 'Asia/Calcutta', rawOffset: 19800, ... }
|
|
115
|
+
|
|
116
|
+
await maps.geolocate({ considerIp: false, wifiAccessPoints }) // { location: { lat, lng }, accuracy }
|
|
117
|
+
|
|
118
|
+
await maps.roads.snap({ path: gpsTrace, interpolate: true }) // [{ location, originalIndex, placeId }]
|
|
119
|
+
await maps.roads.nearest({ points: [[18.52, 73.85]] })
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### Any other Maps API
|
|
123
|
+
|
|
124
|
+
`request()` sends any Google Maps Platform REST call with the same key handling, field masks, retries, timeouts and errors:
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
const forecast = await maps.request<{ dailyInfo: unknown[] }>({
|
|
128
|
+
method: 'POST',
|
|
129
|
+
url: 'https://pollen.googleapis.com/v1/forecast:lookup',
|
|
130
|
+
body: { location: { latitude: 18.52, longitude: 73.85 }, days: 3 },
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
// older JSON APIs take the key in the query string
|
|
134
|
+
await maps.request({
|
|
135
|
+
method: 'GET',
|
|
136
|
+
url: 'https://maps.googleapis.com/maps/api/streetview/metadata',
|
|
137
|
+
query: { location: '18.52,73.85' },
|
|
138
|
+
keyIn: 'query',
|
|
139
|
+
})
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### What's covered
|
|
143
|
+
|
|
144
|
+
| API | Methods |
|
|
145
|
+
| :--------------------------------------------------------------------------- | :----------------------------------------------------------------------------- |
|
|
146
|
+
| Places API (New) | `places.autocomplete`, `get`, `searchText`, `searchNearby`, `photo`, `session` |
|
|
147
|
+
| Routes API | `routes.compute`, `routes.matrix` |
|
|
148
|
+
| Geocoding API | `geocode`, `reverseGeocode` |
|
|
149
|
+
| Address Validation API | `addressValidation.validate`, `feedback` |
|
|
150
|
+
| Elevation API | `elevation` |
|
|
151
|
+
| Time Zone API | `timezone` |
|
|
152
|
+
| Geolocation API | `geolocate` |
|
|
153
|
+
| Roads API | `roads.snap`, `roads.nearest` |
|
|
154
|
+
| Anything else (Route Optimization, Solar, Air Quality, Pollen, Weather, ...) | `request` |
|
|
155
|
+
|
|
156
|
+
Typed methods are added when people ask for them; open an issue if you'd like one.
|
|
157
|
+
|
|
158
|
+
## Field masks and billing
|
|
159
|
+
|
|
160
|
+
Google bills Place Details and searches by the most expensive field you ask for, and the Places and Routes APIs need a field mask for most calls. `google-maps-fetch` defaults to the cheapest useful mask. Pass `fields` to change it.
|
|
161
|
+
|
|
162
|
+
| Call | Default fields | Billing tier |
|
|
163
|
+
| :-------------------- | :--------------------------------------------------------------- | :------------------------------------------------------------------------------------------- |
|
|
164
|
+
| `places.get` | `id, formattedAddress, location` | Essentials |
|
|
165
|
+
| `places.searchText` | `places.id, displayName, formattedAddress, location`, page token | Pro |
|
|
166
|
+
| `places.searchNearby` | `places.id, displayName, formattedAddress, location, types` | Pro |
|
|
167
|
+
| `places.autocomplete` | everything (no mask) | Session-based ([see Google](https://developers.google.com/maps/billing-and-pricing/pricing)) |
|
|
168
|
+
| `routes.compute` | distance, duration, polyline, localized text | Set by the request (traffic, waypoints), not the fields |
|
|
169
|
+
| `routes.matrix` | indexes, status, condition, distance, durations, localized text | Set by the request |
|
|
170
|
+
|
|
171
|
+
Use `places.session()` for autocomplete. It sends one session token with every keystroke and with the details call that ends the session. What Google then charges depends on the fields that details call asks for ([session pricing](https://developers.google.com/maps/documentation/places/web-service/session-pricing)):
|
|
172
|
+
|
|
173
|
+
- **Essentials fields only** (the `get` default): the first 12 autocomplete requests in the session are billed per request, any beyond that are free, and the details call is billed at Essentials.
|
|
174
|
+
- **Any Pro or Enterprise field** (`displayName`, `rating`, phone numbers, ...): every autocomplete request is free, and the details call is billed at Enterprise + Atmosphere, whatever else you asked for.
|
|
175
|
+
- **`fields: ['id']` only, or no details call**: every autocomplete request is billed per request.
|
|
176
|
+
|
|
177
|
+
So for a box that only needs an address and coordinates, the default is the cheapest. If you need a display name or more, one details call at the top tier buys free autocomplete.
|
|
178
|
+
|
|
179
|
+
## Options
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
createClient({
|
|
183
|
+
key: '...', // required
|
|
184
|
+
fetch, // default: globalThis.fetch
|
|
185
|
+
timeout: 10_000, // ms per attempt; 0 waits as long as it takes
|
|
186
|
+
retries: 2, // extra attempts after a network error, timeout, 429 or 5xx
|
|
187
|
+
headers: {}, // sent with every request
|
|
188
|
+
})
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Every method also takes `{ signal, timeout }`, and the field-masked ones take `fields`. Cancelling through `signal` is never retried. When Google answers with a `Retry-After` header, that wait is used instead of the backoff; if it asks for more than 30 seconds, the error is thrown straight away.
|
|
192
|
+
|
|
193
|
+
## Errors
|
|
194
|
+
|
|
195
|
+
Failures throw a `MapsError`:
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
import { MapsError } from 'google-maps-fetch'
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
await maps.places.get('not-a-place')
|
|
202
|
+
} catch (e) {
|
|
203
|
+
if (e instanceof MapsError) {
|
|
204
|
+
e.status // HTTP status, or 0 if there was no response
|
|
205
|
+
e.code // e.g. INVALID_ARGUMENT, PERMISSION_DENIED, RESOURCE_EXHAUSTED, TIMEOUT, NETWORK_ERROR
|
|
206
|
+
e.body // Google's error body
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
## Migrating from @googlemaps/google-maps-services-js
|
|
212
|
+
|
|
213
|
+
Change the import:
|
|
214
|
+
|
|
215
|
+
```diff
|
|
216
|
+
- import { Client, TravelMode } from '@googlemaps/google-maps-services-js'
|
|
217
|
+
+ import { Client, TravelMode } from 'google-maps-fetch/compat'
|
|
218
|
+
|
|
219
|
+
const client = new Client({})
|
|
220
|
+
const { data } = await client.directions({
|
|
221
|
+
params: { origin: 'Pune', destination: 'Mumbai', mode: TravelMode.driving, key },
|
|
222
|
+
})
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Requests take the same `params` and return `{ data, status, statusText, headers, config }`, with `data` in the legacy shape. Enable **Places API (New)** and **Routes API** on your project first.
|
|
226
|
+
|
|
227
|
+
| Method | Now calls |
|
|
228
|
+
| :----------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------ |
|
|
229
|
+
| `placeAutocomplete`, `placeQueryAutocomplete` | Places API (New) Autocomplete |
|
|
230
|
+
| `placeDetails` | Places API (New) Place Details |
|
|
231
|
+
| `findPlaceFromText`, `textSearch` | Places API (New) Text Search |
|
|
232
|
+
| `placesNearby` | Nearby Search (New), or Text Search when you use keyword/name/price/opennow/pagetoken |
|
|
233
|
+
| `placePhoto` | Places API (New) photo media |
|
|
234
|
+
| `directions` | Routes API `computeRoutes` |
|
|
235
|
+
| `distancematrix` | Routes API `computeRouteMatrix` |
|
|
236
|
+
| `geocode`, `reverseGeocode`, `elevation`, `timezone`, `geolocate`, `nearestRoads`, `snapToRoads` | The same APIs as before (they aren't legacy), unchanged |
|
|
237
|
+
|
|
238
|
+
### What's different
|
|
239
|
+
|
|
240
|
+
- **Errors.** API errors resolve with a legacy status in `data.status` (`REQUEST_DENIED`, `INVALID_REQUEST`, `OVER_QUERY_LIMIT`, `NOT_FOUND`, `UNKNOWN_ERROR`) and `data.error_message`, which is how the legacy APIs reported them. That holds for the pass-through methods too. Network errors and timeouts throw a `MapsError`, and so does `placePhoto` when the image can't be fetched.
|
|
241
|
+
- **Paging.** `next_page_token` works as before, including sending the token on its own: the client remembers the search that issued it. A token from another process needs the original parameters repeated.
|
|
242
|
+
- **`placeDetails` without `fields`.** The legacy API returned every field and billed for all of them. This defaults to `place_id, formatted_address, geometry, address_components` (Essentials). Pass `fields` for anything else; legacy field names are mapped.
|
|
243
|
+
- **Addresses in routes.** The Routes API doesn't geocode inputs back to addresses. `start_address`, `end_address`, `origin_addresses` and `destination_addresses` repeat what you passed: the address string, `"lat,lng"` for coordinates, or `""` for a place ID. `geocoded_waypoints` is empty.
|
|
244
|
+
- **Language.** `directions` and `distancematrix` ask for English unless you pass `language`, as the legacy APIs did. Left to itself, the Routes API picks a language from the origin.
|
|
245
|
+
- **Autocomplete `types`.** `(cities)` and `(regions)` work as before, and `address` becomes street-level types. `geocode` and `establishment` have no equivalent in the new API, so no type filter is applied.
|
|
246
|
+
- **`placesNearby` with keyword, name, price, open-now or a page token** runs a Text Search inside the circle, because Nearby Search (New) has none of those. That's a different billing SKU.
|
|
247
|
+
- **Photos.** `photo_reference` in results is now a photo name (`places/.../photos/...`). `placePhoto` accepts those and returns an `ArrayBuffer`. Old-style references don't work.
|
|
248
|
+
- **`findPlaceFromText`** returns one candidate, as the legacy API did.
|
|
249
|
+
- **Not supported:** `client_id` / URL signing, `enc:` polyline waypoints, and axios options other than `timeout`. Pass `config: { timeout, retries, headers }` to the constructor.
|
|
250
|
+
|
|
251
|
+
## Contributing
|
|
252
|
+
|
|
253
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md). The tests use a fake `fetch`, so they don't need a Google key.
|
|
254
|
+
|
|
255
|
+
## Maintainer
|
|
256
|
+
|
|
257
|
+
Maintained by [Ninad Sutrave](https://ninadsutrave.com).
|
|
258
|
+
|
|
259
|
+
## License
|
|
260
|
+
|
|
261
|
+
[MIT](LICENSE)
|
|
262
|
+
|
|
263
|
+
This is an independent project, not affiliated with or endorsed by Google. Google Maps is a trademark of Google LLC.
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/http.ts
|
|
2
|
+
var MapsError = class extends Error {
|
|
3
|
+
constructor(message, status, code, body) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.status = status;
|
|
6
|
+
this.code = code;
|
|
7
|
+
this.body = body;
|
|
8
|
+
this.name = "MapsError";
|
|
9
|
+
}
|
|
10
|
+
/** Same shape as an axios error's response, for code written against axios-based clients */
|
|
11
|
+
get response() {
|
|
12
|
+
return this.status ? { status: this.status, data: this.body } : void 0;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
var retryable = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
|
|
16
|
+
var httpCodes = {
|
|
17
|
+
400: "INVALID_ARGUMENT",
|
|
18
|
+
401: "UNAUTHENTICATED",
|
|
19
|
+
403: "PERMISSION_DENIED",
|
|
20
|
+
404: "NOT_FOUND",
|
|
21
|
+
429: "RESOURCE_EXHAUSTED",
|
|
22
|
+
500: "INTERNAL",
|
|
23
|
+
503: "UNAVAILABLE",
|
|
24
|
+
504: "DEADLINE_EXCEEDED"
|
|
25
|
+
};
|
|
26
|
+
var fieldMask = (fields) => Array.isArray(fields) ? fields.join(",") : fields;
|
|
27
|
+
var withQuery = (url, query = {}) => {
|
|
28
|
+
const params = new URLSearchParams();
|
|
29
|
+
for (const [k, v] of Object.entries(query)) if (v !== void 0) params.set(k, String(v));
|
|
30
|
+
const qs = params.toString();
|
|
31
|
+
return qs ? `${url}?${qs}` : url;
|
|
32
|
+
};
|
|
33
|
+
var parse = (text) => {
|
|
34
|
+
try {
|
|
35
|
+
return JSON.parse(text);
|
|
36
|
+
} catch (e2) {
|
|
37
|
+
return text;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
var wait = (ms, signal) => new Promise((resolve, reject) => {
|
|
41
|
+
if (_optionalChain([signal, 'optionalAccess', _ => _.aborted])) return reject(signal.reason);
|
|
42
|
+
const onAbort = () => {
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
reject(_optionalChain([signal, 'optionalAccess', _2 => _2.reason]));
|
|
45
|
+
};
|
|
46
|
+
const timer = setTimeout(() => {
|
|
47
|
+
_optionalChain([signal, 'optionalAccess', _3 => _3.removeEventListener, 'call', _4 => _4("abort", onAbort)]);
|
|
48
|
+
resolve();
|
|
49
|
+
}, ms);
|
|
50
|
+
_optionalChain([signal, 'optionalAccess', _5 => _5.addEventListener, 'call', _6 => _6("abort", onAbort, { once: true })]);
|
|
51
|
+
});
|
|
52
|
+
var backoff = (attempt) => 250 * 2 ** attempt + Math.random() * 100;
|
|
53
|
+
var maxRetryAfter = 3e4;
|
|
54
|
+
var retryAfter = (value) => {
|
|
55
|
+
if (!value) return void 0;
|
|
56
|
+
const s = Number(value);
|
|
57
|
+
if (!Number.isNaN(s)) return Math.max(0, s * 1e3);
|
|
58
|
+
const date = Date.parse(value);
|
|
59
|
+
return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
|
|
60
|
+
};
|
|
61
|
+
function createTransport({ key, fetch: f = globalThis.fetch, timeout = 1e4, retries = 2, headers = {} }) {
|
|
62
|
+
if (!key) throw new Error("google-maps-fetch: an API key is required");
|
|
63
|
+
if (typeof f !== "function") throw new Error("google-maps-fetch: no fetch available; pass one with the fetch option");
|
|
64
|
+
return async function send(request, call = {}) {
|
|
65
|
+
const { method, body, fields, keyIn = "header" } = request;
|
|
66
|
+
const url = withQuery(request.url, keyIn === "query" ? { ...request.query, key } : request.query);
|
|
67
|
+
const requestHeaders = { ...headers };
|
|
68
|
+
if (keyIn === "header") requestHeaders["X-Goog-Api-Key"] = key;
|
|
69
|
+
if (fields !== void 0) requestHeaders["X-Goog-FieldMask"] = fieldMask(fields);
|
|
70
|
+
if (body !== void 0) requestHeaders["Content-Type"] = "application/json";
|
|
71
|
+
const ms = _nullishCoalesce(call.timeout, () => ( timeout));
|
|
72
|
+
for (let attempt = 0; ; attempt++) {
|
|
73
|
+
if (_optionalChain([call, 'access', _7 => _7.signal, 'optionalAccess', _8 => _8.aborted])) throw call.signal.reason;
|
|
74
|
+
const controller = new AbortController();
|
|
75
|
+
let timedOut = false;
|
|
76
|
+
const timer = ms > 0 ? setTimeout(() => {
|
|
77
|
+
timedOut = true;
|
|
78
|
+
controller.abort();
|
|
79
|
+
}, ms) : void 0;
|
|
80
|
+
const onAbort = () => controller.abort();
|
|
81
|
+
_optionalChain([call, 'access', _9 => _9.signal, 'optionalAccess', _10 => _10.addEventListener, 'call', _11 => _11("abort", onAbort, { once: true })]);
|
|
82
|
+
let error;
|
|
83
|
+
let delay;
|
|
84
|
+
try {
|
|
85
|
+
const res = await f(url, {
|
|
86
|
+
method,
|
|
87
|
+
headers: requestHeaders,
|
|
88
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
89
|
+
signal: controller.signal
|
|
90
|
+
});
|
|
91
|
+
const text = await res.text();
|
|
92
|
+
const data = text ? parse(text) : void 0;
|
|
93
|
+
if (res.ok) return data;
|
|
94
|
+
const payload = Array.isArray(data) ? data[0] : data;
|
|
95
|
+
const e = _optionalChain([payload, 'optionalAccess', _12 => _12.error]);
|
|
96
|
+
error = new MapsError(
|
|
97
|
+
_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _13 => _13.message]), () => ( _optionalChain([payload, 'optionalAccess', _14 => _14.error_message]))), () => ( `HTTP ${res.status}`)),
|
|
98
|
+
res.status,
|
|
99
|
+
_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _15 => _15.status]), () => ( _optionalChain([payload, 'optionalAccess', _16 => _16.status]))), () => ( httpCodes[res.status])), () => ( "UNKNOWN")),
|
|
100
|
+
data
|
|
101
|
+
);
|
|
102
|
+
if (!retryable.has(res.status)) throw error;
|
|
103
|
+
delay = retryAfter(res.headers.get("retry-after"));
|
|
104
|
+
if (delay !== void 0 && delay > maxRetryAfter) throw error;
|
|
105
|
+
} catch (e) {
|
|
106
|
+
if (e instanceof MapsError) throw e;
|
|
107
|
+
if (_optionalChain([call, 'access', _17 => _17.signal, 'optionalAccess', _18 => _18.aborted])) throw call.signal.reason;
|
|
108
|
+
error = timedOut ? new MapsError(`google-maps-fetch: no response within ${ms}ms`, 0, "TIMEOUT") : new MapsError(`google-maps-fetch: ${_nullishCoalesce(_optionalChain([e, 'optionalAccess', _19 => _19.message]), () => ( "network error"))}`, 0, "NETWORK_ERROR", e);
|
|
109
|
+
} finally {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
_optionalChain([call, 'access', _20 => _20.signal, 'optionalAccess', _21 => _21.removeEventListener, 'call', _22 => _22("abort", onAbort)]);
|
|
112
|
+
}
|
|
113
|
+
if (attempt >= retries) throw error;
|
|
114
|
+
await wait(_nullishCoalesce(delay, () => ( backoff(attempt))), call.signal);
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/util.ts
|
|
120
|
+
var toLatLng = (value) => {
|
|
121
|
+
if (Array.isArray(value)) return { latitude: value[0], longitude: value[1] };
|
|
122
|
+
if ("lat" in value) return { latitude: value.lat, longitude: value.lng };
|
|
123
|
+
return { latitude: value.latitude, longitude: value.longitude };
|
|
124
|
+
};
|
|
125
|
+
var isWaypoint = (value) => "location" in value || "placeId" in value || "address" in value;
|
|
126
|
+
var toWaypoint = (value) => {
|
|
127
|
+
if (typeof value === "string") return { address: value };
|
|
128
|
+
if (!Array.isArray(value) && isWaypoint(value)) return value;
|
|
129
|
+
return { location: { latLng: toLatLng(value) } };
|
|
130
|
+
};
|
|
131
|
+
var seconds = (duration) => duration === void 0 ? void 0 : parseFloat(duration);
|
|
132
|
+
var newSessionToken = () => globalThis.crypto.randomUUID();
|
|
133
|
+
|
|
134
|
+
// src/places.ts
|
|
135
|
+
var base = "https://places.googleapis.com/v1";
|
|
136
|
+
var placeFields = ["id", "formattedAddress", "location"];
|
|
137
|
+
var searchTextFields = ["places.id", "places.displayName", "places.formattedAddress", "places.location", "nextPageToken"];
|
|
138
|
+
var searchNearbyFields = ["places.id", "places.displayName", "places.formattedAddress", "places.location", "places.types"];
|
|
139
|
+
var placePath = (id) => id.startsWith("places/") ? id : `places/${encodeURIComponent(id)}`;
|
|
140
|
+
function createPlaces(send) {
|
|
141
|
+
const autocomplete = ({ ...request }, { fields, ...call } = {}) => send({ method: "POST", url: `${base}/places:autocomplete`, body: request, fields }, call);
|
|
142
|
+
const get = (id, { fields = placeFields, languageCode, regionCode, sessionToken, ...call } = {}) => send({ method: "GET", url: `${base}/${placePath(id)}`, query: { languageCode, regionCode, sessionToken }, fields }, call);
|
|
143
|
+
const searchText = (request, { fields = searchTextFields, ...call } = {}) => send({ method: "POST", url: `${base}/places:searchText`, body: request, fields }, call);
|
|
144
|
+
const searchNearby = (request, { fields = searchNearbyFields, ...call } = {}) => send({ method: "POST", url: `${base}/places:searchNearby`, body: request, fields }, call);
|
|
145
|
+
const photo = (name, { maxWidthPx, maxHeightPx, ...call } = {}) => send(
|
|
146
|
+
{
|
|
147
|
+
method: "GET",
|
|
148
|
+
url: `${base}/${name}/media`,
|
|
149
|
+
// Google needs at least one size
|
|
150
|
+
query: { maxWidthPx: _nullishCoalesce(maxWidthPx, () => ( (maxHeightPx ? void 0 : 800))), maxHeightPx, skipHttpRedirect: true }
|
|
151
|
+
},
|
|
152
|
+
call
|
|
153
|
+
);
|
|
154
|
+
const session = () => {
|
|
155
|
+
let token = newSessionToken();
|
|
156
|
+
return {
|
|
157
|
+
get token() {
|
|
158
|
+
return token;
|
|
159
|
+
},
|
|
160
|
+
autocomplete: (request, options) => autocomplete({ ...request, sessionToken: token }, options),
|
|
161
|
+
get: async (id, options) => {
|
|
162
|
+
try {
|
|
163
|
+
return await get(id, { ...options, sessionToken: token });
|
|
164
|
+
} finally {
|
|
165
|
+
token = newSessionToken();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
};
|
|
170
|
+
return { autocomplete, get, searchText, searchNearby, photo, session };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// src/routes.ts
|
|
174
|
+
var routeFields = [
|
|
175
|
+
"routes.distanceMeters",
|
|
176
|
+
"routes.duration",
|
|
177
|
+
"routes.staticDuration",
|
|
178
|
+
"routes.polyline.encodedPolyline",
|
|
179
|
+
"routes.localizedValues"
|
|
180
|
+
];
|
|
181
|
+
var matrixFields = [
|
|
182
|
+
"originIndex",
|
|
183
|
+
"destinationIndex",
|
|
184
|
+
"status",
|
|
185
|
+
"condition",
|
|
186
|
+
"distanceMeters",
|
|
187
|
+
"duration",
|
|
188
|
+
"staticDuration",
|
|
189
|
+
"localizedValues"
|
|
190
|
+
];
|
|
191
|
+
var isMatrixEntry = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && "waypoint" in value;
|
|
192
|
+
var toOrigin = (value) => isMatrixEntry(value) ? value : { waypoint: toWaypoint(value) };
|
|
193
|
+
var toDestination = (value) => isMatrixEntry(value) ? value : { waypoint: toWaypoint(value) };
|
|
194
|
+
var has = (fields, field) => {
|
|
195
|
+
const list = (Array.isArray(fields) ? fields : fields.split(",")).map((f) => f.trim());
|
|
196
|
+
return list.includes("*") || list.includes(field);
|
|
197
|
+
};
|
|
198
|
+
function createRoutes(send) {
|
|
199
|
+
const compute = ({ origin, destination, intermediates, ...rest }, { fields = routeFields, ...call } = {}) => send(
|
|
200
|
+
{
|
|
201
|
+
method: "POST",
|
|
202
|
+
url: "https://routes.googleapis.com/directions/v2:computeRoutes",
|
|
203
|
+
body: {
|
|
204
|
+
...rest,
|
|
205
|
+
origin: toWaypoint(origin),
|
|
206
|
+
destination: toWaypoint(destination),
|
|
207
|
+
...intermediates ? { intermediates: intermediates.map(toWaypoint) } : {}
|
|
208
|
+
},
|
|
209
|
+
fields
|
|
210
|
+
},
|
|
211
|
+
call
|
|
212
|
+
);
|
|
213
|
+
const matrix = async ({ origins, destinations, ...rest }, { fields = matrixFields, ...call } = {}) => {
|
|
214
|
+
const elements = await send(
|
|
215
|
+
{
|
|
216
|
+
method: "POST",
|
|
217
|
+
url: "https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix",
|
|
218
|
+
body: { ...rest, origins: origins.map(toOrigin), destinations: destinations.map(toDestination) },
|
|
219
|
+
fields
|
|
220
|
+
},
|
|
221
|
+
call
|
|
222
|
+
);
|
|
223
|
+
return (_nullishCoalesce(elements, () => ( []))).map((e) => ({
|
|
224
|
+
...e,
|
|
225
|
+
...has(fields, "originIndex") ? { originIndex: _nullishCoalesce(e.originIndex, () => ( 0)) } : {},
|
|
226
|
+
...has(fields, "destinationIndex") ? { destinationIndex: _nullishCoalesce(e.destinationIndex, () => ( 0)) } : {}
|
|
227
|
+
}));
|
|
228
|
+
};
|
|
229
|
+
return { compute, matrix };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
exports.MapsError = MapsError; exports.createTransport = createTransport; exports.toLatLng = toLatLng; exports.toWaypoint = toWaypoint; exports.seconds = seconds; exports.newSessionToken = newSessionToken; exports.placeFields = placeFields; exports.searchTextFields = searchTextFields; exports.searchNearbyFields = searchNearbyFields; exports.createPlaces = createPlaces; exports.routeFields = routeFields; exports.matrixFields = matrixFields; exports.createRoutes = createRoutes;
|