@classic-homes/maps-core 0.2.16 → 0.3.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.
- package/dist/chunk-OPYY37LA.js +17 -0
- package/dist/geocoding/index.cjs +78 -0
- package/dist/geocoding/index.d.cts +106 -0
- package/dist/geocoding/index.d.ts +106 -0
- package/dist/geocoding/index.js +69 -0
- package/dist/route/index.cjs +243 -0
- package/dist/route/index.d.cts +143 -0
- package/dist/route/index.d.ts +143 -0
- package/dist/route/index.js +208 -0
- package/dist/types-1EVNQpng.d.ts +59 -0
- package/dist/types-DprSjGzT.d.cts +59 -0
- package/package.json +11 -1
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// src/route/types.ts
|
|
2
|
+
function toLngLat(point) {
|
|
3
|
+
return [point.lng, point.lat];
|
|
4
|
+
}
|
|
5
|
+
function fromLngLat(point) {
|
|
6
|
+
return { lat: point[1], lng: point[0] };
|
|
7
|
+
}
|
|
8
|
+
function isFiniteNumber(value) {
|
|
9
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
10
|
+
}
|
|
11
|
+
function isValidLatLng(point) {
|
|
12
|
+
if (!point || typeof point !== "object") return false;
|
|
13
|
+
const { lat, lng } = point;
|
|
14
|
+
return isFiniteNumber(lat) && isFiniteNumber(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export { fromLngLat, isFiniteNumber, isValidLatLng, toLngLat };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/route/types.ts
|
|
4
|
+
function isFiniteNumber(value) {
|
|
5
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
// src/geocoding/maptiler.ts
|
|
9
|
+
var DEFAULT_BASE_URL = "https://api.maptiler.com/geocoding";
|
|
10
|
+
function buildMapTilerGeocodeUrl(query, opts) {
|
|
11
|
+
const trimmed = query.trim();
|
|
12
|
+
if (!trimmed) throw new RangeError("geocode query must not be empty");
|
|
13
|
+
if (!opts.key) throw new RangeError("geocode key must not be empty");
|
|
14
|
+
const base = opts.baseUrl ?? DEFAULT_BASE_URL;
|
|
15
|
+
const params = new URLSearchParams({ key: opts.key });
|
|
16
|
+
if (opts.proximity) {
|
|
17
|
+
params.set("proximity", `${opts.proximity.lng},${opts.proximity.lat}`);
|
|
18
|
+
}
|
|
19
|
+
if (opts.country) params.set("country", opts.country);
|
|
20
|
+
if (opts.bbox) params.set("bbox", opts.bbox.join(","));
|
|
21
|
+
params.set("limit", String(opts.limit ?? 1));
|
|
22
|
+
return `${base}/${encodeURIComponent(trimmed)}.json?${params.toString()}`;
|
|
23
|
+
}
|
|
24
|
+
function parseFeature(feature) {
|
|
25
|
+
if (!feature || typeof feature !== "object") return null;
|
|
26
|
+
const center = feature.center;
|
|
27
|
+
if (!Array.isArray(center) || center.length < 2) return null;
|
|
28
|
+
const [lng, lat] = center;
|
|
29
|
+
if (!isFiniteNumber(lat) || !isFiniteNumber(lng)) return null;
|
|
30
|
+
const placeName = feature.place_name;
|
|
31
|
+
const text = feature.text;
|
|
32
|
+
const label = typeof placeName === "string" ? placeName : typeof text === "string" ? text : `${lat}, ${lng}`;
|
|
33
|
+
const coords = { lat, lng };
|
|
34
|
+
return { coords, label };
|
|
35
|
+
}
|
|
36
|
+
function parseMapTilerGeocodeResults(body) {
|
|
37
|
+
if (!body || typeof body !== "object") return [];
|
|
38
|
+
const features = body.features;
|
|
39
|
+
if (!Array.isArray(features)) return [];
|
|
40
|
+
return features.map(parseFeature).filter((result) => result !== null);
|
|
41
|
+
}
|
|
42
|
+
function parseMapTilerGeocodeResponse(body) {
|
|
43
|
+
return parseMapTilerGeocodeResults(body)[0] ?? null;
|
|
44
|
+
}
|
|
45
|
+
async function requestMapTiler(query, opts, fetchFn) {
|
|
46
|
+
let url;
|
|
47
|
+
try {
|
|
48
|
+
url = buildMapTilerGeocodeUrl(query, opts);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
opts.onError?.(error);
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
const response = await fetchFn(url, opts.signal ? { signal: opts.signal } : void 0);
|
|
55
|
+
if (!response.ok) {
|
|
56
|
+
opts.onError?.(new Error(`MapTiler geocoding failed: ${response.status}`));
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
return await response.json();
|
|
60
|
+
} catch (error) {
|
|
61
|
+
opts.onError?.(error);
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
async function geocodeForward(query, opts, fetchFn) {
|
|
66
|
+
const body = await requestMapTiler(query, opts, fetchFn);
|
|
67
|
+
return body === null ? null : parseMapTilerGeocodeResponse(body);
|
|
68
|
+
}
|
|
69
|
+
async function geocodeForwardMany(query, opts, fetchFn) {
|
|
70
|
+
const body = await requestMapTiler(query, opts, fetchFn);
|
|
71
|
+
return body === null ? [] : parseMapTilerGeocodeResults(body);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
exports.buildMapTilerGeocodeUrl = buildMapTilerGeocodeUrl;
|
|
75
|
+
exports.geocodeForward = geocodeForward;
|
|
76
|
+
exports.geocodeForwardMany = geocodeForwardMany;
|
|
77
|
+
exports.parseMapTilerGeocodeResponse = parseMapTilerGeocodeResponse;
|
|
78
|
+
exports.parseMapTilerGeocodeResults = parseMapTilerGeocodeResults;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { L as LatLng } from '../types-DprSjGzT.cjs';
|
|
2
|
+
import '../data-DCyEqgN0.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Types for forward geocoding
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** A bounding box in GeoJSON order: [minLng, minLat, maxLng, maxLat] */
|
|
9
|
+
type GeocodeBBox = [number, number, number, number];
|
|
10
|
+
interface GeocodeOptions {
|
|
11
|
+
/**
|
|
12
|
+
* The provider API key.
|
|
13
|
+
*
|
|
14
|
+
* Always injected by the caller, never baked into this package: a key
|
|
15
|
+
* compiled into a client bundle is a public key, and geocoding is billed per
|
|
16
|
+
* request. Callers should hold it server-side and expose their own endpoint.
|
|
17
|
+
*/
|
|
18
|
+
key: string;
|
|
19
|
+
/** Bias results toward this point - the single most effective relevance knob */
|
|
20
|
+
proximity?: LatLng;
|
|
21
|
+
/** ISO 3166-1 alpha-2 country filter, e.g. 'us' */
|
|
22
|
+
country?: string;
|
|
23
|
+
/** Restrict results to this box */
|
|
24
|
+
bbox?: GeocodeBBox;
|
|
25
|
+
/**
|
|
26
|
+
* Maximum results to request (default 1).
|
|
27
|
+
*
|
|
28
|
+
* `geocodeForward` returns only the best match however high this goes; use
|
|
29
|
+
* `geocodeForwardMany` to see the rest.
|
|
30
|
+
*/
|
|
31
|
+
limit?: number;
|
|
32
|
+
/** Override the provider base URL - for tests and self-hosted proxies */
|
|
33
|
+
baseUrl?: string;
|
|
34
|
+
/**
|
|
35
|
+
* Abort the request.
|
|
36
|
+
*
|
|
37
|
+
* Without one a hung provider holds the caller open until its own platform
|
|
38
|
+
* gives up, which on a Cloudflare Worker means the whole invocation. Pair
|
|
39
|
+
* with `AbortSignal.timeout(ms)`.
|
|
40
|
+
*/
|
|
41
|
+
signal?: AbortSignal;
|
|
42
|
+
/**
|
|
43
|
+
* Called with whatever went wrong before the geocode resolves null.
|
|
44
|
+
*
|
|
45
|
+
* A miss, a rejected key, a rate limit and a dead network are all `null` to
|
|
46
|
+
* the caller by design - an address box must not throw - but they are very
|
|
47
|
+
* different operationally, and without this hook a wrong key is
|
|
48
|
+
* indistinguishable from "no results" in production.
|
|
49
|
+
*/
|
|
50
|
+
onError?: (error: unknown) => void;
|
|
51
|
+
}
|
|
52
|
+
interface GeocodeResult {
|
|
53
|
+
coords: LatLng;
|
|
54
|
+
/** The provider's formatted name for the match */
|
|
55
|
+
label: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* MapTiler forward geocoding.
|
|
60
|
+
*
|
|
61
|
+
* https://docs.maptiler.com/cloud/api/geocoding/
|
|
62
|
+
*
|
|
63
|
+
* The request builder and the response parser are separate pure functions so
|
|
64
|
+
* both can be tested without a network, and so a caller can run the request
|
|
65
|
+
* through its own cache or retry layer.
|
|
66
|
+
*/
|
|
67
|
+
|
|
68
|
+
/** Build the MapTiler forward-geocoding URL for `query` */
|
|
69
|
+
declare function buildMapTilerGeocodeUrl(query: string, opts: GeocodeOptions): string;
|
|
70
|
+
/**
|
|
71
|
+
* Parse every usable feature of a MapTiler geocoding response, best first.
|
|
72
|
+
*
|
|
73
|
+
* MapTiler returns `features[i].center` as **[lng, lat]** - GeoJSON order,
|
|
74
|
+
* transposed relative to `LatLng`. Getting this backwards puts Colorado
|
|
75
|
+
* Springs in Antarctica, so the swap happens here, once, and is asserted in
|
|
76
|
+
* the tests.
|
|
77
|
+
*
|
|
78
|
+
* Returns [] for an empty or malformed payload rather than throwing: a geocode
|
|
79
|
+
* miss is an ordinary outcome, not an exception. Individual malformed features
|
|
80
|
+
* are skipped rather than failing the batch.
|
|
81
|
+
*/
|
|
82
|
+
declare function parseMapTilerGeocodeResults(body: unknown): GeocodeResult[];
|
|
83
|
+
/**
|
|
84
|
+
* Parse the best match out of a MapTiler geocoding response.
|
|
85
|
+
* Returns null for an empty or malformed payload. See
|
|
86
|
+
* `parseMapTilerGeocodeResults` for the rest of the matches.
|
|
87
|
+
*/
|
|
88
|
+
declare function parseMapTilerGeocodeResponse(body: unknown): GeocodeResult | null;
|
|
89
|
+
/**
|
|
90
|
+
* Forward-geocode `query`, returning the best match.
|
|
91
|
+
*
|
|
92
|
+
* `fetchFn` is injected so this runs in a Worker, a browser or a test without
|
|
93
|
+
* assuming a global. Resolves null on any failure - a miss, a non-2xx status,
|
|
94
|
+
* a malformed body, an abort or a network error - so an address box never
|
|
95
|
+
* blows up the page it sits on. Pass `onError` to see which of those it was,
|
|
96
|
+
* and `signal` to bound how long it can hang.
|
|
97
|
+
*/
|
|
98
|
+
declare function geocodeForward(query: string, opts: GeocodeOptions, fetchFn: typeof fetch): Promise<GeocodeResult | null>;
|
|
99
|
+
/**
|
|
100
|
+
* Forward-geocode `query`, returning every match MapTiler sent, best first.
|
|
101
|
+
* Resolves [] on the same failures `geocodeForward` resolves null on. Set
|
|
102
|
+
* `limit` above 1 or MapTiler sends a single feature.
|
|
103
|
+
*/
|
|
104
|
+
declare function geocodeForwardMany(query: string, opts: GeocodeOptions, fetchFn: typeof fetch): Promise<GeocodeResult[]>;
|
|
105
|
+
|
|
106
|
+
export { type GeocodeBBox, type GeocodeOptions, type GeocodeResult, buildMapTilerGeocodeUrl, geocodeForward, geocodeForwardMany, parseMapTilerGeocodeResponse, parseMapTilerGeocodeResults };
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { L as LatLng } from '../types-1EVNQpng.js';
|
|
2
|
+
import '../data-DCyEqgN0.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Types for forward geocoding
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** A bounding box in GeoJSON order: [minLng, minLat, maxLng, maxLat] */
|
|
9
|
+
type GeocodeBBox = [number, number, number, number];
|
|
10
|
+
interface GeocodeOptions {
|
|
11
|
+
/**
|
|
12
|
+
* The provider API key.
|
|
13
|
+
*
|
|
14
|
+
* Always injected by the caller, never baked into this package: a key
|
|
15
|
+
* compiled into a client bundle is a public key, and geocoding is billed per
|
|
16
|
+
* request. Callers should hold it server-side and expose their own endpoint.
|
|
17
|
+
*/
|
|
18
|
+
key: string;
|
|
19
|
+
/** Bias results toward this point - the single most effective relevance knob */
|
|
20
|
+
proximity?: LatLng;
|
|
21
|
+
/** ISO 3166-1 alpha-2 country filter, e.g. 'us' */
|
|
22
|
+
country?: string;
|
|
23
|
+
/** Restrict results to this box */
|
|
24
|
+
bbox?: GeocodeBBox;
|
|
25
|
+
/**
|
|
26
|
+
* Maximum results to request (default 1).
|
|
27
|
+
*
|
|
28
|
+
* `geocodeForward` returns only the best match however high this goes; use
|
|
29
|
+
* `geocodeForwardMany` to see the rest.
|
|
30
|
+
*/
|
|
31
|
+
limit?: number;
|
|
32
|
+
/** Override the provider base URL - for tests and self-hosted proxies */
|
|
33
|
+
baseUrl?: string;
|
|
34
|
+
/**
|
|
35
|
+
* Abort the request.
|
|
36
|
+
*
|
|
37
|
+
* Without one a hung provider holds the caller open until its own platform
|
|
38
|
+
* gives up, which on a Cloudflare Worker means the whole invocation. Pair
|
|
39
|
+
* with `AbortSignal.timeout(ms)`.
|
|
40
|
+
*/
|
|
41
|
+
signal?: AbortSignal;
|
|
42
|
+
/**
|
|
43
|
+
* Called with whatever went wrong before the geocode resolves null.
|
|
44
|
+
*
|
|
45
|
+
* A miss, a rejected key, a rate limit and a dead network are all `null` to
|
|
46
|
+
* the caller by design - an address box must not throw - but they are very
|
|
47
|
+
* different operationally, and without this hook a wrong key is
|
|
48
|
+
* indistinguishable from "no results" in production.
|
|
49
|
+
*/
|
|
50
|
+
onError?: (error: unknown) => void;
|
|
51
|
+
}
|
|
52
|
+
interface GeocodeResult {
|
|
53
|
+
coords: LatLng;
|
|
54
|
+
/** The provider's formatted name for the match */
|
|
55
|
+
label: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* MapTiler forward geocoding.
|
|
60
|
+
*
|
|
61
|
+
* https://docs.maptiler.com/cloud/api/geocoding/
|
|
62
|
+
*
|
|
63
|
+
* The request builder and the response parser are separate pure functions so
|
|
64
|
+
* both can be tested without a network, and so a caller can run the request
|
|
65
|
+
* through its own cache or retry layer.
|
|
66
|
+
*/
|
|
67
|
+
|
|
68
|
+
/** Build the MapTiler forward-geocoding URL for `query` */
|
|
69
|
+
declare function buildMapTilerGeocodeUrl(query: string, opts: GeocodeOptions): string;
|
|
70
|
+
/**
|
|
71
|
+
* Parse every usable feature of a MapTiler geocoding response, best first.
|
|
72
|
+
*
|
|
73
|
+
* MapTiler returns `features[i].center` as **[lng, lat]** - GeoJSON order,
|
|
74
|
+
* transposed relative to `LatLng`. Getting this backwards puts Colorado
|
|
75
|
+
* Springs in Antarctica, so the swap happens here, once, and is asserted in
|
|
76
|
+
* the tests.
|
|
77
|
+
*
|
|
78
|
+
* Returns [] for an empty or malformed payload rather than throwing: a geocode
|
|
79
|
+
* miss is an ordinary outcome, not an exception. Individual malformed features
|
|
80
|
+
* are skipped rather than failing the batch.
|
|
81
|
+
*/
|
|
82
|
+
declare function parseMapTilerGeocodeResults(body: unknown): GeocodeResult[];
|
|
83
|
+
/**
|
|
84
|
+
* Parse the best match out of a MapTiler geocoding response.
|
|
85
|
+
* Returns null for an empty or malformed payload. See
|
|
86
|
+
* `parseMapTilerGeocodeResults` for the rest of the matches.
|
|
87
|
+
*/
|
|
88
|
+
declare function parseMapTilerGeocodeResponse(body: unknown): GeocodeResult | null;
|
|
89
|
+
/**
|
|
90
|
+
* Forward-geocode `query`, returning the best match.
|
|
91
|
+
*
|
|
92
|
+
* `fetchFn` is injected so this runs in a Worker, a browser or a test without
|
|
93
|
+
* assuming a global. Resolves null on any failure - a miss, a non-2xx status,
|
|
94
|
+
* a malformed body, an abort or a network error - so an address box never
|
|
95
|
+
* blows up the page it sits on. Pass `onError` to see which of those it was,
|
|
96
|
+
* and `signal` to bound how long it can hang.
|
|
97
|
+
*/
|
|
98
|
+
declare function geocodeForward(query: string, opts: GeocodeOptions, fetchFn: typeof fetch): Promise<GeocodeResult | null>;
|
|
99
|
+
/**
|
|
100
|
+
* Forward-geocode `query`, returning every match MapTiler sent, best first.
|
|
101
|
+
* Resolves [] on the same failures `geocodeForward` resolves null on. Set
|
|
102
|
+
* `limit` above 1 or MapTiler sends a single feature.
|
|
103
|
+
*/
|
|
104
|
+
declare function geocodeForwardMany(query: string, opts: GeocodeOptions, fetchFn: typeof fetch): Promise<GeocodeResult[]>;
|
|
105
|
+
|
|
106
|
+
export { type GeocodeBBox, type GeocodeOptions, type GeocodeResult, buildMapTilerGeocodeUrl, geocodeForward, geocodeForwardMany, parseMapTilerGeocodeResponse, parseMapTilerGeocodeResults };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { isFiniteNumber } from '../chunk-OPYY37LA.js';
|
|
2
|
+
|
|
3
|
+
// src/geocoding/maptiler.ts
|
|
4
|
+
var DEFAULT_BASE_URL = "https://api.maptiler.com/geocoding";
|
|
5
|
+
function buildMapTilerGeocodeUrl(query, opts) {
|
|
6
|
+
const trimmed = query.trim();
|
|
7
|
+
if (!trimmed) throw new RangeError("geocode query must not be empty");
|
|
8
|
+
if (!opts.key) throw new RangeError("geocode key must not be empty");
|
|
9
|
+
const base = opts.baseUrl ?? DEFAULT_BASE_URL;
|
|
10
|
+
const params = new URLSearchParams({ key: opts.key });
|
|
11
|
+
if (opts.proximity) {
|
|
12
|
+
params.set("proximity", `${opts.proximity.lng},${opts.proximity.lat}`);
|
|
13
|
+
}
|
|
14
|
+
if (opts.country) params.set("country", opts.country);
|
|
15
|
+
if (opts.bbox) params.set("bbox", opts.bbox.join(","));
|
|
16
|
+
params.set("limit", String(opts.limit ?? 1));
|
|
17
|
+
return `${base}/${encodeURIComponent(trimmed)}.json?${params.toString()}`;
|
|
18
|
+
}
|
|
19
|
+
function parseFeature(feature) {
|
|
20
|
+
if (!feature || typeof feature !== "object") return null;
|
|
21
|
+
const center = feature.center;
|
|
22
|
+
if (!Array.isArray(center) || center.length < 2) return null;
|
|
23
|
+
const [lng, lat] = center;
|
|
24
|
+
if (!isFiniteNumber(lat) || !isFiniteNumber(lng)) return null;
|
|
25
|
+
const placeName = feature.place_name;
|
|
26
|
+
const text = feature.text;
|
|
27
|
+
const label = typeof placeName === "string" ? placeName : typeof text === "string" ? text : `${lat}, ${lng}`;
|
|
28
|
+
const coords = { lat, lng };
|
|
29
|
+
return { coords, label };
|
|
30
|
+
}
|
|
31
|
+
function parseMapTilerGeocodeResults(body) {
|
|
32
|
+
if (!body || typeof body !== "object") return [];
|
|
33
|
+
const features = body.features;
|
|
34
|
+
if (!Array.isArray(features)) return [];
|
|
35
|
+
return features.map(parseFeature).filter((result) => result !== null);
|
|
36
|
+
}
|
|
37
|
+
function parseMapTilerGeocodeResponse(body) {
|
|
38
|
+
return parseMapTilerGeocodeResults(body)[0] ?? null;
|
|
39
|
+
}
|
|
40
|
+
async function requestMapTiler(query, opts, fetchFn) {
|
|
41
|
+
let url;
|
|
42
|
+
try {
|
|
43
|
+
url = buildMapTilerGeocodeUrl(query, opts);
|
|
44
|
+
} catch (error) {
|
|
45
|
+
opts.onError?.(error);
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
const response = await fetchFn(url, opts.signal ? { signal: opts.signal } : void 0);
|
|
50
|
+
if (!response.ok) {
|
|
51
|
+
opts.onError?.(new Error(`MapTiler geocoding failed: ${response.status}`));
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
return await response.json();
|
|
55
|
+
} catch (error) {
|
|
56
|
+
opts.onError?.(error);
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async function geocodeForward(query, opts, fetchFn) {
|
|
61
|
+
const body = await requestMapTiler(query, opts, fetchFn);
|
|
62
|
+
return body === null ? null : parseMapTilerGeocodeResponse(body);
|
|
63
|
+
}
|
|
64
|
+
async function geocodeForwardMany(query, opts, fetchFn) {
|
|
65
|
+
const body = await requestMapTiler(query, opts, fetchFn);
|
|
66
|
+
return body === null ? [] : parseMapTilerGeocodeResults(body);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export { buildMapTilerGeocodeUrl, geocodeForward, geocodeForwardMany, parseMapTilerGeocodeResponse, parseMapTilerGeocodeResults };
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/route/types.ts
|
|
4
|
+
function toLngLat(point) {
|
|
5
|
+
return [point.lng, point.lat];
|
|
6
|
+
}
|
|
7
|
+
function fromLngLat(point) {
|
|
8
|
+
return { lat: point[1], lng: point[0] };
|
|
9
|
+
}
|
|
10
|
+
function isFiniteNumber(value) {
|
|
11
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
12
|
+
}
|
|
13
|
+
function isValidLatLng(point) {
|
|
14
|
+
if (!point || typeof point !== "object") return false;
|
|
15
|
+
const { lat, lng } = point;
|
|
16
|
+
return isFiniteNumber(lat) && isFiniteNumber(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// src/route/geo.ts
|
|
20
|
+
var EARTH_RADIUS_MILES = 3958.7613;
|
|
21
|
+
var EARTH_RADIUS_KM = 6371.0088;
|
|
22
|
+
function toRadians(degrees) {
|
|
23
|
+
return degrees * Math.PI / 180;
|
|
24
|
+
}
|
|
25
|
+
function haversineMiles(a, b) {
|
|
26
|
+
if (!isFiniteNumber(a?.lat) || !isFiniteNumber(a?.lng)) return NaN;
|
|
27
|
+
if (!isFiniteNumber(b?.lat) || !isFiniteNumber(b?.lng)) return NaN;
|
|
28
|
+
const dLat = toRadians(b.lat - a.lat);
|
|
29
|
+
const dLng = toRadians(b.lng - a.lng);
|
|
30
|
+
const lat1 = toRadians(a.lat);
|
|
31
|
+
const lat2 = toRadians(b.lat);
|
|
32
|
+
const sinDLat = Math.sin(dLat / 2);
|
|
33
|
+
const sinDLng = Math.sin(dLng / 2);
|
|
34
|
+
const h = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLng * sinDLng;
|
|
35
|
+
return 2 * EARTH_RADIUS_MILES * Math.asin(Math.min(1, Math.sqrt(h)));
|
|
36
|
+
}
|
|
37
|
+
function haversineKm(a, b) {
|
|
38
|
+
return haversineMiles(a, b) * EARTH_RADIUS_KM / EARTH_RADIUS_MILES;
|
|
39
|
+
}
|
|
40
|
+
function distanceMatrix(points) {
|
|
41
|
+
const n = points.length;
|
|
42
|
+
const matrix = Array.from({ length: n }, () => new Array(n).fill(0));
|
|
43
|
+
for (let i = 0; i < n; i++) {
|
|
44
|
+
for (let j = i + 1; j < n; j++) {
|
|
45
|
+
const d = haversineMiles(points[i], points[j]);
|
|
46
|
+
matrix[i][j] = d;
|
|
47
|
+
matrix[j][i] = d;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return matrix;
|
|
51
|
+
}
|
|
52
|
+
function legsFor(origin, points, order, matrix) {
|
|
53
|
+
const legMiles = [];
|
|
54
|
+
for (let i = 0; i < order.length; i++) {
|
|
55
|
+
legMiles.push(
|
|
56
|
+
i === 0 ? haversineMiles(origin, points[order[0]]) : matrix[order[i - 1]][order[i]]
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
order,
|
|
61
|
+
legMiles,
|
|
62
|
+
totalMiles: legMiles.reduce((sum, miles) => sum + (isFiniteNumber(miles) ? miles : 0), 0)
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function reverseSegment(order, i, j) {
|
|
66
|
+
let left = i;
|
|
67
|
+
let right = j;
|
|
68
|
+
while (left < right) {
|
|
69
|
+
const held = order[left];
|
|
70
|
+
order[left] = order[right];
|
|
71
|
+
order[right] = held;
|
|
72
|
+
left++;
|
|
73
|
+
right--;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function orderFrom(origin, points, matrix) {
|
|
77
|
+
const n = points.length;
|
|
78
|
+
const visited = new Array(n).fill(false);
|
|
79
|
+
const order = [];
|
|
80
|
+
for (let step = 0; step < n; step++) {
|
|
81
|
+
let best = -1;
|
|
82
|
+
let bestMiles = Infinity;
|
|
83
|
+
for (let i = 0; i < n; i++) {
|
|
84
|
+
if (visited[i]) continue;
|
|
85
|
+
const miles = step === 0 ? haversineMiles(origin, points[i]) : matrix[order[step - 1]][i];
|
|
86
|
+
if (isFiniteNumber(miles) && miles < bestMiles) {
|
|
87
|
+
bestMiles = miles;
|
|
88
|
+
best = i;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (best === -1) {
|
|
92
|
+
for (let i = 0; i < n; i++) {
|
|
93
|
+
if (!visited[i]) {
|
|
94
|
+
visited[i] = true;
|
|
95
|
+
order.push(i);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
break;
|
|
99
|
+
}
|
|
100
|
+
visited[best] = true;
|
|
101
|
+
order.push(best);
|
|
102
|
+
}
|
|
103
|
+
return order;
|
|
104
|
+
}
|
|
105
|
+
function nearestNeighborOrder(origin, points) {
|
|
106
|
+
const n = points.length;
|
|
107
|
+
if (n === 0) return { order: [], legMiles: [], totalMiles: 0 };
|
|
108
|
+
const matrix = distanceMatrix(points);
|
|
109
|
+
return legsFor(origin, points, orderFrom(origin, points, matrix), matrix);
|
|
110
|
+
}
|
|
111
|
+
function twoOptImprove(origin, points, order, matrix, opts = {}) {
|
|
112
|
+
const maxPasses = opts.maxPasses ?? 20;
|
|
113
|
+
if (order.length < 3) return [...order];
|
|
114
|
+
const best = [...order];
|
|
115
|
+
const last = best.length - 1;
|
|
116
|
+
const originMiles = points.map((point) => haversineMiles(origin, point));
|
|
117
|
+
for (let pass = 0; pass < maxPasses; pass++) {
|
|
118
|
+
let improved = false;
|
|
119
|
+
for (let i = 0; i <= last - 1; i++) {
|
|
120
|
+
for (let j = i + 1; j <= last; j++) {
|
|
121
|
+
const headOld = i === 0 ? originMiles[best[0]] : matrix[best[i - 1]][best[i]];
|
|
122
|
+
const headNew = i === 0 ? originMiles[best[j]] : matrix[best[i - 1]][best[j]];
|
|
123
|
+
const tailOld = j === last ? 0 : matrix[best[j]][best[j + 1]];
|
|
124
|
+
const tailNew = j === last ? 0 : matrix[best[i]][best[j + 1]];
|
|
125
|
+
if (headNew + tailNew - headOld - tailOld < -1e-4) {
|
|
126
|
+
reverseSegment(best, i, j);
|
|
127
|
+
improved = true;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (!improved) break;
|
|
132
|
+
}
|
|
133
|
+
return best;
|
|
134
|
+
}
|
|
135
|
+
function optimizeOrder(origin, points, opts = {}) {
|
|
136
|
+
const n = points.length;
|
|
137
|
+
if (n === 0) return { order: [], legMiles: [], totalMiles: 0 };
|
|
138
|
+
const matrix = distanceMatrix(points);
|
|
139
|
+
const greedy = orderFrom(origin, points, matrix);
|
|
140
|
+
if (opts.twoOpt === false || n < 3) return legsFor(origin, points, greedy, matrix);
|
|
141
|
+
const improved = twoOptImprove(origin, points, greedy, matrix, {
|
|
142
|
+
maxPasses: opts.maxPasses
|
|
143
|
+
});
|
|
144
|
+
return legsFor(origin, points, improved, matrix);
|
|
145
|
+
}
|
|
146
|
+
function measureOrder(origin, points, order) {
|
|
147
|
+
return legsFor(origin, points, order, distanceMatrix(points));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// src/route/mapsLinks.ts
|
|
151
|
+
var GOOGLE_MAX_WAYPOINTS = 9;
|
|
152
|
+
var GOOGLE_MAX_LEG_STOPS = GOOGLE_MAX_WAYPOINTS + 1;
|
|
153
|
+
var GOOGLE_DIR_BASE = "https://www.google.com/maps/dir/?api=1";
|
|
154
|
+
var GOOGLE_SEARCH_BASE = "https://www.google.com/maps/search/?api=1";
|
|
155
|
+
var APPLE_BASE = "https://maps.apple.com/";
|
|
156
|
+
function encodeTarget(target) {
|
|
157
|
+
const coords = target.coords;
|
|
158
|
+
if (coords && isFiniteNumber(coords.lat) && isFiniteNumber(coords.lng)) {
|
|
159
|
+
return `${coords.lat},${coords.lng}`;
|
|
160
|
+
}
|
|
161
|
+
if (target.address && target.address.trim()) {
|
|
162
|
+
return encodeURIComponent(target.address.trim());
|
|
163
|
+
}
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
function usableTargets(targets) {
|
|
167
|
+
return targets.map(encodeTarget).filter((value) => value !== null);
|
|
168
|
+
}
|
|
169
|
+
function googleDirectionsUrl(stops, origin, travelmode) {
|
|
170
|
+
const encoded = usableTargets(stops);
|
|
171
|
+
if (encoded.length === 0) return "";
|
|
172
|
+
const destination = encoded[encoded.length - 1];
|
|
173
|
+
const waypoints = encoded.slice(0, -1);
|
|
174
|
+
const encodedOrigin = origin ? encodeTarget(origin) : null;
|
|
175
|
+
let url = GOOGLE_DIR_BASE;
|
|
176
|
+
if (encodedOrigin) url += `&origin=${encodedOrigin}`;
|
|
177
|
+
url += `&destination=${destination}`;
|
|
178
|
+
if (waypoints.length > 0) url += `&waypoints=${waypoints.join("%7C")}`;
|
|
179
|
+
if (travelmode) url += `&travelmode=${encodeURIComponent(travelmode)}`;
|
|
180
|
+
return url;
|
|
181
|
+
}
|
|
182
|
+
function appleDirectionsUrl(stops, origin, dirflg = "d") {
|
|
183
|
+
const encoded = usableTargets(stops);
|
|
184
|
+
if (encoded.length === 0) return "";
|
|
185
|
+
const encodedOrigin = origin ? encodeTarget(origin) : null;
|
|
186
|
+
const daddr = encoded[0];
|
|
187
|
+
let url = `${APPLE_BASE}?`;
|
|
188
|
+
if (encodedOrigin) url += `saddr=${encodedOrigin}&`;
|
|
189
|
+
url += `daddr=${daddr}&dirflg=${encodeURIComponent(dirflg)}`;
|
|
190
|
+
return url;
|
|
191
|
+
}
|
|
192
|
+
function googleSearchUrl(query) {
|
|
193
|
+
return `${GOOGLE_SEARCH_BASE}&query=${encodeURIComponent(query)}`;
|
|
194
|
+
}
|
|
195
|
+
function splitIntoLegs(stops, maxPerLeg = GOOGLE_MAX_LEG_STOPS) {
|
|
196
|
+
if (maxPerLeg < 2) throw new RangeError("maxPerLeg must be at least 2");
|
|
197
|
+
if (stops.length === 0) return [];
|
|
198
|
+
if (stops.length <= maxPerLeg) return [[...stops]];
|
|
199
|
+
const legs = [];
|
|
200
|
+
let index = 0;
|
|
201
|
+
while (index < stops.length) {
|
|
202
|
+
const leg = stops.slice(index, index + maxPerLeg);
|
|
203
|
+
legs.push(leg);
|
|
204
|
+
index += maxPerLeg - 1;
|
|
205
|
+
if (index >= stops.length - 1) break;
|
|
206
|
+
}
|
|
207
|
+
return legs;
|
|
208
|
+
}
|
|
209
|
+
function googleDirectionsLegUrls(stops, origin, travelmode) {
|
|
210
|
+
const usable = stops.filter((stop) => encodeTarget(stop) !== null);
|
|
211
|
+
if (usable.length === 0) return [];
|
|
212
|
+
const legs = splitIntoLegs(usable, GOOGLE_MAX_LEG_STOPS);
|
|
213
|
+
return legs.map((leg, index) => {
|
|
214
|
+
if (index === 0) return googleDirectionsUrl(leg, origin, travelmode);
|
|
215
|
+
const [legOrigin, ...rest] = leg;
|
|
216
|
+
return googleDirectionsUrl(rest, legOrigin, travelmode);
|
|
217
|
+
}).filter((url) => url !== "");
|
|
218
|
+
}
|
|
219
|
+
function targetFromCoords(coords, address) {
|
|
220
|
+
return { coords, address };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
exports.EARTH_RADIUS_KM = EARTH_RADIUS_KM;
|
|
224
|
+
exports.EARTH_RADIUS_MILES = EARTH_RADIUS_MILES;
|
|
225
|
+
exports.GOOGLE_MAX_LEG_STOPS = GOOGLE_MAX_LEG_STOPS;
|
|
226
|
+
exports.GOOGLE_MAX_WAYPOINTS = GOOGLE_MAX_WAYPOINTS;
|
|
227
|
+
exports.appleDirectionsUrl = appleDirectionsUrl;
|
|
228
|
+
exports.distanceMatrix = distanceMatrix;
|
|
229
|
+
exports.fromLngLat = fromLngLat;
|
|
230
|
+
exports.googleDirectionsLegUrls = googleDirectionsLegUrls;
|
|
231
|
+
exports.googleDirectionsUrl = googleDirectionsUrl;
|
|
232
|
+
exports.googleSearchUrl = googleSearchUrl;
|
|
233
|
+
exports.haversineKm = haversineKm;
|
|
234
|
+
exports.haversineMiles = haversineMiles;
|
|
235
|
+
exports.isFiniteNumber = isFiniteNumber;
|
|
236
|
+
exports.isValidLatLng = isValidLatLng;
|
|
237
|
+
exports.measureOrder = measureOrder;
|
|
238
|
+
exports.nearestNeighborOrder = nearestNeighborOrder;
|
|
239
|
+
exports.optimizeOrder = optimizeOrder;
|
|
240
|
+
exports.splitIntoLegs = splitIntoLegs;
|
|
241
|
+
exports.targetFromCoords = targetFromCoords;
|
|
242
|
+
exports.toLngLat = toLngLat;
|
|
243
|
+
exports.twoOptImprove = twoOptImprove;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { L as LatLng, O as OrderResult, D as DirectionsTarget, T as TravelMode } from '../types-DprSjGzT.cjs';
|
|
2
|
+
export { f as fromLngLat, i as isFiniteNumber, a as isValidLatLng, t as toLngLat } from '../types-DprSjGzT.cjs';
|
|
3
|
+
import '../data-DCyEqgN0.cjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Great-circle distance math for route planning.
|
|
7
|
+
*
|
|
8
|
+
* These are crow-flies distances. They are good enough to decide a visit
|
|
9
|
+
* order, and they are NOT driving distances - anywhere a river, a highway or
|
|
10
|
+
* a one-way grid sits between two points, the real drive is longer. Label
|
|
11
|
+
* anything shown to a user as approximate.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Mean earth radius in statute miles */
|
|
15
|
+
declare const EARTH_RADIUS_MILES = 3958.7613;
|
|
16
|
+
/** Mean earth radius in kilometres */
|
|
17
|
+
declare const EARTH_RADIUS_KM = 6371.0088;
|
|
18
|
+
/**
|
|
19
|
+
* Great-circle distance between two points, in statute miles.
|
|
20
|
+
*
|
|
21
|
+
* Returns NaN for non-finite input rather than throwing: a bad coordinate is a
|
|
22
|
+
* data problem, and callers filter on `isNaN` alongside their other checks.
|
|
23
|
+
* `null`, `undefined` and a numeric string all count as non-finite here.
|
|
24
|
+
* Note that {lat: 0, lng: 0} is a real place in the Gulf of Guinea, not a
|
|
25
|
+
* sentinel - filtering placeholder zeroes is the caller's job, not this one's.
|
|
26
|
+
*/
|
|
27
|
+
declare function haversineMiles(a: LatLng, b: LatLng): number;
|
|
28
|
+
/** Great-circle distance between two points, in kilometres */
|
|
29
|
+
declare function haversineKm(a: LatLng, b: LatLng): number;
|
|
30
|
+
/**
|
|
31
|
+
* Symmetric distance matrix in miles, with a zero diagonal.
|
|
32
|
+
* O(n^2 / 2) haversine calls - each pair is computed once and mirrored.
|
|
33
|
+
*/
|
|
34
|
+
declare function distanceMatrix(points: LatLng[]): number[][];
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Stop ordering for multi-stop routes.
|
|
38
|
+
*
|
|
39
|
+
* Greedy nearest-neighbour, then an open-path 2-opt pass to remove the
|
|
40
|
+
* backtrack that greedy characteristically leaves on its final leg. Both work
|
|
41
|
+
* on crow-flies distance (see ./geo), so the result is a sensible visit order,
|
|
42
|
+
* not a provably optimal drive.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Greedy nearest-neighbour ordering from `origin`. O(n^2).
|
|
47
|
+
*
|
|
48
|
+
* Ties break on the lower index, so the result is deterministic for identical
|
|
49
|
+
* coordinates and stable across runs.
|
|
50
|
+
*/
|
|
51
|
+
declare function nearestNeighborOrder(origin: LatLng, points: LatLng[]): OrderResult;
|
|
52
|
+
/**
|
|
53
|
+
* Open-path 2-opt improvement.
|
|
54
|
+
*
|
|
55
|
+
* Repeatedly reverses `order[i..j]` when that shortens the path
|
|
56
|
+
* origin -> ... -> last. This is the OPEN-path formulation: there is no
|
|
57
|
+
* return edge to the origin, because a home tour ends at the last home. Using
|
|
58
|
+
* the usual closed-tour objective here would optimise for a trip nobody takes.
|
|
59
|
+
* Reversing a segment that ends at the final stop therefore changes one edge,
|
|
60
|
+
* not two.
|
|
61
|
+
*
|
|
62
|
+
* Each candidate is scored on the two edges the reversal actually touches -
|
|
63
|
+
* everything between them is symmetric and unchanged - so a pass is O(n^2)
|
|
64
|
+
* rather than O(n^2) reversals each re-walked in O(n). Stops on the first pass
|
|
65
|
+
* that finds no improvement, or after `maxPasses`.
|
|
66
|
+
*
|
|
67
|
+
* A non-finite leg makes every delta through it NaN, which never compares
|
|
68
|
+
* below -EPSILON, so a bad coordinate freezes the order instead of corrupting
|
|
69
|
+
* it.
|
|
70
|
+
*/
|
|
71
|
+
declare function twoOptImprove(origin: LatLng, points: LatLng[], order: number[], matrix: number[][], opts?: {
|
|
72
|
+
maxPasses?: number;
|
|
73
|
+
}): number[];
|
|
74
|
+
/**
|
|
75
|
+
* Order `points` from `origin`: nearest-neighbour, then 2-opt unless disabled.
|
|
76
|
+
* The one function most callers need.
|
|
77
|
+
*/
|
|
78
|
+
declare function optimizeOrder(origin: LatLng, points: LatLng[], opts?: {
|
|
79
|
+
twoOpt?: boolean;
|
|
80
|
+
maxPasses?: number;
|
|
81
|
+
}): OrderResult;
|
|
82
|
+
/** Leg distances for an order the caller chose - no reordering */
|
|
83
|
+
declare function measureOrder(origin: LatLng, points: LatLng[], order: number[]): OrderResult;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Deep links into Google Maps and Apple Maps.
|
|
87
|
+
*
|
|
88
|
+
* Both builders emit their query string by hand rather than through
|
|
89
|
+
* URLSearchParams, which percent-encodes the comma in "lat,lng" as %2C. Google
|
|
90
|
+
* accepts that, but it would change every URL this package emits byte-for-byte,
|
|
91
|
+
* including the single-destination form already shipped in consumer apps.
|
|
92
|
+
*
|
|
93
|
+
* Everything that is not a coordinate pair still goes through
|
|
94
|
+
* encodeURIComponent, so a JavaScript caller passing an off-contract travel
|
|
95
|
+
* mode cannot append query parameters of its own.
|
|
96
|
+
*/
|
|
97
|
+
|
|
98
|
+
/** Google's `api=1` directions URL accepts at most 9 intermediate waypoints */
|
|
99
|
+
declare const GOOGLE_MAX_WAYPOINTS = 9;
|
|
100
|
+
/** ...so a single leg holds at most 10 targets, counting the destination */
|
|
101
|
+
declare const GOOGLE_MAX_LEG_STOPS: number;
|
|
102
|
+
/**
|
|
103
|
+
* A Google Maps directions URL.
|
|
104
|
+
*
|
|
105
|
+
* With one stop and no origin this returns exactly
|
|
106
|
+
* `https://www.google.com/maps/dir/?api=1&destination=<lat>,<lng>` - the form
|
|
107
|
+
* consumer apps already link to. Extra stops become `waypoints`, joined by an
|
|
108
|
+
* encoded pipe (%7C). Returns '' when no target is usable.
|
|
109
|
+
*
|
|
110
|
+
* Google renders at most GOOGLE_MAX_WAYPOINTS intermediate stops; pass longer
|
|
111
|
+
* routes through `googleDirectionsLegUrls` instead of truncating here.
|
|
112
|
+
*/
|
|
113
|
+
declare function googleDirectionsUrl(stops: DirectionsTarget[], origin?: DirectionsTarget | null, travelmode?: TravelMode): string;
|
|
114
|
+
/**
|
|
115
|
+
* An Apple Maps URL.
|
|
116
|
+
*
|
|
117
|
+
* The maps.apple.com scheme has NO waypoint parameter - `saddr` and `daddr`
|
|
118
|
+
* only. For a multi-stop input this deliberately returns the leg to the FIRST
|
|
119
|
+
* stop rather than silently dropping the rest, and callers must label the
|
|
120
|
+
* affordance accordingly ("Apple Maps (first stop)"). Returns '' when no
|
|
121
|
+
* target is usable.
|
|
122
|
+
*/
|
|
123
|
+
declare function appleDirectionsUrl(stops: DirectionsTarget[], origin?: DirectionsTarget | null, dirflg?: 'd' | 'w' | 'r'): string;
|
|
124
|
+
/** A Google Maps search URL - the fallback for a stop with no coordinate */
|
|
125
|
+
declare function googleSearchUrl(query: string): string;
|
|
126
|
+
/**
|
|
127
|
+
* Chunk stops so each leg fits Google's waypoint budget.
|
|
128
|
+
*
|
|
129
|
+
* Each leg after the first repeats the previous leg's final stop as its own
|
|
130
|
+
* first entry, so the driver resumes where they stopped and no stop is lost at
|
|
131
|
+
* the seam.
|
|
132
|
+
*/
|
|
133
|
+
declare function splitIntoLegs<T>(stops: T[], maxPerLeg?: number): T[][];
|
|
134
|
+
/**
|
|
135
|
+
* One Google Maps URL per leg, for routes longer than Google renders at once.
|
|
136
|
+
* A route inside the budget yields a single URL, identical to
|
|
137
|
+
* `googleDirectionsUrl`.
|
|
138
|
+
*/
|
|
139
|
+
declare function googleDirectionsLegUrls(stops: DirectionsTarget[], origin?: DirectionsTarget | null, travelmode?: TravelMode): string[];
|
|
140
|
+
/** Convenience: a target from a coordinate */
|
|
141
|
+
declare function targetFromCoords(coords: LatLng, address?: string): DirectionsTarget;
|
|
142
|
+
|
|
143
|
+
export { DirectionsTarget, EARTH_RADIUS_KM, EARTH_RADIUS_MILES, GOOGLE_MAX_LEG_STOPS, GOOGLE_MAX_WAYPOINTS, LatLng, OrderResult, TravelMode, appleDirectionsUrl, distanceMatrix, googleDirectionsLegUrls, googleDirectionsUrl, googleSearchUrl, haversineKm, haversineMiles, measureOrder, nearestNeighborOrder, optimizeOrder, splitIntoLegs, targetFromCoords, twoOptImprove };
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { L as LatLng, O as OrderResult, D as DirectionsTarget, T as TravelMode } from '../types-1EVNQpng.js';
|
|
2
|
+
export { f as fromLngLat, i as isFiniteNumber, a as isValidLatLng, t as toLngLat } from '../types-1EVNQpng.js';
|
|
3
|
+
import '../data-DCyEqgN0.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Great-circle distance math for route planning.
|
|
7
|
+
*
|
|
8
|
+
* These are crow-flies distances. They are good enough to decide a visit
|
|
9
|
+
* order, and they are NOT driving distances - anywhere a river, a highway or
|
|
10
|
+
* a one-way grid sits between two points, the real drive is longer. Label
|
|
11
|
+
* anything shown to a user as approximate.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Mean earth radius in statute miles */
|
|
15
|
+
declare const EARTH_RADIUS_MILES = 3958.7613;
|
|
16
|
+
/** Mean earth radius in kilometres */
|
|
17
|
+
declare const EARTH_RADIUS_KM = 6371.0088;
|
|
18
|
+
/**
|
|
19
|
+
* Great-circle distance between two points, in statute miles.
|
|
20
|
+
*
|
|
21
|
+
* Returns NaN for non-finite input rather than throwing: a bad coordinate is a
|
|
22
|
+
* data problem, and callers filter on `isNaN` alongside their other checks.
|
|
23
|
+
* `null`, `undefined` and a numeric string all count as non-finite here.
|
|
24
|
+
* Note that {lat: 0, lng: 0} is a real place in the Gulf of Guinea, not a
|
|
25
|
+
* sentinel - filtering placeholder zeroes is the caller's job, not this one's.
|
|
26
|
+
*/
|
|
27
|
+
declare function haversineMiles(a: LatLng, b: LatLng): number;
|
|
28
|
+
/** Great-circle distance between two points, in kilometres */
|
|
29
|
+
declare function haversineKm(a: LatLng, b: LatLng): number;
|
|
30
|
+
/**
|
|
31
|
+
* Symmetric distance matrix in miles, with a zero diagonal.
|
|
32
|
+
* O(n^2 / 2) haversine calls - each pair is computed once and mirrored.
|
|
33
|
+
*/
|
|
34
|
+
declare function distanceMatrix(points: LatLng[]): number[][];
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Stop ordering for multi-stop routes.
|
|
38
|
+
*
|
|
39
|
+
* Greedy nearest-neighbour, then an open-path 2-opt pass to remove the
|
|
40
|
+
* backtrack that greedy characteristically leaves on its final leg. Both work
|
|
41
|
+
* on crow-flies distance (see ./geo), so the result is a sensible visit order,
|
|
42
|
+
* not a provably optimal drive.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Greedy nearest-neighbour ordering from `origin`. O(n^2).
|
|
47
|
+
*
|
|
48
|
+
* Ties break on the lower index, so the result is deterministic for identical
|
|
49
|
+
* coordinates and stable across runs.
|
|
50
|
+
*/
|
|
51
|
+
declare function nearestNeighborOrder(origin: LatLng, points: LatLng[]): OrderResult;
|
|
52
|
+
/**
|
|
53
|
+
* Open-path 2-opt improvement.
|
|
54
|
+
*
|
|
55
|
+
* Repeatedly reverses `order[i..j]` when that shortens the path
|
|
56
|
+
* origin -> ... -> last. This is the OPEN-path formulation: there is no
|
|
57
|
+
* return edge to the origin, because a home tour ends at the last home. Using
|
|
58
|
+
* the usual closed-tour objective here would optimise for a trip nobody takes.
|
|
59
|
+
* Reversing a segment that ends at the final stop therefore changes one edge,
|
|
60
|
+
* not two.
|
|
61
|
+
*
|
|
62
|
+
* Each candidate is scored on the two edges the reversal actually touches -
|
|
63
|
+
* everything between them is symmetric and unchanged - so a pass is O(n^2)
|
|
64
|
+
* rather than O(n^2) reversals each re-walked in O(n). Stops on the first pass
|
|
65
|
+
* that finds no improvement, or after `maxPasses`.
|
|
66
|
+
*
|
|
67
|
+
* A non-finite leg makes every delta through it NaN, which never compares
|
|
68
|
+
* below -EPSILON, so a bad coordinate freezes the order instead of corrupting
|
|
69
|
+
* it.
|
|
70
|
+
*/
|
|
71
|
+
declare function twoOptImprove(origin: LatLng, points: LatLng[], order: number[], matrix: number[][], opts?: {
|
|
72
|
+
maxPasses?: number;
|
|
73
|
+
}): number[];
|
|
74
|
+
/**
|
|
75
|
+
* Order `points` from `origin`: nearest-neighbour, then 2-opt unless disabled.
|
|
76
|
+
* The one function most callers need.
|
|
77
|
+
*/
|
|
78
|
+
declare function optimizeOrder(origin: LatLng, points: LatLng[], opts?: {
|
|
79
|
+
twoOpt?: boolean;
|
|
80
|
+
maxPasses?: number;
|
|
81
|
+
}): OrderResult;
|
|
82
|
+
/** Leg distances for an order the caller chose - no reordering */
|
|
83
|
+
declare function measureOrder(origin: LatLng, points: LatLng[], order: number[]): OrderResult;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Deep links into Google Maps and Apple Maps.
|
|
87
|
+
*
|
|
88
|
+
* Both builders emit their query string by hand rather than through
|
|
89
|
+
* URLSearchParams, which percent-encodes the comma in "lat,lng" as %2C. Google
|
|
90
|
+
* accepts that, but it would change every URL this package emits byte-for-byte,
|
|
91
|
+
* including the single-destination form already shipped in consumer apps.
|
|
92
|
+
*
|
|
93
|
+
* Everything that is not a coordinate pair still goes through
|
|
94
|
+
* encodeURIComponent, so a JavaScript caller passing an off-contract travel
|
|
95
|
+
* mode cannot append query parameters of its own.
|
|
96
|
+
*/
|
|
97
|
+
|
|
98
|
+
/** Google's `api=1` directions URL accepts at most 9 intermediate waypoints */
|
|
99
|
+
declare const GOOGLE_MAX_WAYPOINTS = 9;
|
|
100
|
+
/** ...so a single leg holds at most 10 targets, counting the destination */
|
|
101
|
+
declare const GOOGLE_MAX_LEG_STOPS: number;
|
|
102
|
+
/**
|
|
103
|
+
* A Google Maps directions URL.
|
|
104
|
+
*
|
|
105
|
+
* With one stop and no origin this returns exactly
|
|
106
|
+
* `https://www.google.com/maps/dir/?api=1&destination=<lat>,<lng>` - the form
|
|
107
|
+
* consumer apps already link to. Extra stops become `waypoints`, joined by an
|
|
108
|
+
* encoded pipe (%7C). Returns '' when no target is usable.
|
|
109
|
+
*
|
|
110
|
+
* Google renders at most GOOGLE_MAX_WAYPOINTS intermediate stops; pass longer
|
|
111
|
+
* routes through `googleDirectionsLegUrls` instead of truncating here.
|
|
112
|
+
*/
|
|
113
|
+
declare function googleDirectionsUrl(stops: DirectionsTarget[], origin?: DirectionsTarget | null, travelmode?: TravelMode): string;
|
|
114
|
+
/**
|
|
115
|
+
* An Apple Maps URL.
|
|
116
|
+
*
|
|
117
|
+
* The maps.apple.com scheme has NO waypoint parameter - `saddr` and `daddr`
|
|
118
|
+
* only. For a multi-stop input this deliberately returns the leg to the FIRST
|
|
119
|
+
* stop rather than silently dropping the rest, and callers must label the
|
|
120
|
+
* affordance accordingly ("Apple Maps (first stop)"). Returns '' when no
|
|
121
|
+
* target is usable.
|
|
122
|
+
*/
|
|
123
|
+
declare function appleDirectionsUrl(stops: DirectionsTarget[], origin?: DirectionsTarget | null, dirflg?: 'd' | 'w' | 'r'): string;
|
|
124
|
+
/** A Google Maps search URL - the fallback for a stop with no coordinate */
|
|
125
|
+
declare function googleSearchUrl(query: string): string;
|
|
126
|
+
/**
|
|
127
|
+
* Chunk stops so each leg fits Google's waypoint budget.
|
|
128
|
+
*
|
|
129
|
+
* Each leg after the first repeats the previous leg's final stop as its own
|
|
130
|
+
* first entry, so the driver resumes where they stopped and no stop is lost at
|
|
131
|
+
* the seam.
|
|
132
|
+
*/
|
|
133
|
+
declare function splitIntoLegs<T>(stops: T[], maxPerLeg?: number): T[][];
|
|
134
|
+
/**
|
|
135
|
+
* One Google Maps URL per leg, for routes longer than Google renders at once.
|
|
136
|
+
* A route inside the budget yields a single URL, identical to
|
|
137
|
+
* `googleDirectionsUrl`.
|
|
138
|
+
*/
|
|
139
|
+
declare function googleDirectionsLegUrls(stops: DirectionsTarget[], origin?: DirectionsTarget | null, travelmode?: TravelMode): string[];
|
|
140
|
+
/** Convenience: a target from a coordinate */
|
|
141
|
+
declare function targetFromCoords(coords: LatLng, address?: string): DirectionsTarget;
|
|
142
|
+
|
|
143
|
+
export { DirectionsTarget, EARTH_RADIUS_KM, EARTH_RADIUS_MILES, GOOGLE_MAX_LEG_STOPS, GOOGLE_MAX_WAYPOINTS, LatLng, OrderResult, TravelMode, appleDirectionsUrl, distanceMatrix, googleDirectionsLegUrls, googleDirectionsUrl, googleSearchUrl, haversineKm, haversineMiles, measureOrder, nearestNeighborOrder, optimizeOrder, splitIntoLegs, targetFromCoords, twoOptImprove };
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { isFiniteNumber } from '../chunk-OPYY37LA.js';
|
|
2
|
+
export { fromLngLat, isFiniteNumber, isValidLatLng, toLngLat } from '../chunk-OPYY37LA.js';
|
|
3
|
+
|
|
4
|
+
// src/route/geo.ts
|
|
5
|
+
var EARTH_RADIUS_MILES = 3958.7613;
|
|
6
|
+
var EARTH_RADIUS_KM = 6371.0088;
|
|
7
|
+
function toRadians(degrees) {
|
|
8
|
+
return degrees * Math.PI / 180;
|
|
9
|
+
}
|
|
10
|
+
function haversineMiles(a, b) {
|
|
11
|
+
if (!isFiniteNumber(a?.lat) || !isFiniteNumber(a?.lng)) return NaN;
|
|
12
|
+
if (!isFiniteNumber(b?.lat) || !isFiniteNumber(b?.lng)) return NaN;
|
|
13
|
+
const dLat = toRadians(b.lat - a.lat);
|
|
14
|
+
const dLng = toRadians(b.lng - a.lng);
|
|
15
|
+
const lat1 = toRadians(a.lat);
|
|
16
|
+
const lat2 = toRadians(b.lat);
|
|
17
|
+
const sinDLat = Math.sin(dLat / 2);
|
|
18
|
+
const sinDLng = Math.sin(dLng / 2);
|
|
19
|
+
const h = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLng * sinDLng;
|
|
20
|
+
return 2 * EARTH_RADIUS_MILES * Math.asin(Math.min(1, Math.sqrt(h)));
|
|
21
|
+
}
|
|
22
|
+
function haversineKm(a, b) {
|
|
23
|
+
return haversineMiles(a, b) * EARTH_RADIUS_KM / EARTH_RADIUS_MILES;
|
|
24
|
+
}
|
|
25
|
+
function distanceMatrix(points) {
|
|
26
|
+
const n = points.length;
|
|
27
|
+
const matrix = Array.from({ length: n }, () => new Array(n).fill(0));
|
|
28
|
+
for (let i = 0; i < n; i++) {
|
|
29
|
+
for (let j = i + 1; j < n; j++) {
|
|
30
|
+
const d = haversineMiles(points[i], points[j]);
|
|
31
|
+
matrix[i][j] = d;
|
|
32
|
+
matrix[j][i] = d;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return matrix;
|
|
36
|
+
}
|
|
37
|
+
function legsFor(origin, points, order, matrix) {
|
|
38
|
+
const legMiles = [];
|
|
39
|
+
for (let i = 0; i < order.length; i++) {
|
|
40
|
+
legMiles.push(
|
|
41
|
+
i === 0 ? haversineMiles(origin, points[order[0]]) : matrix[order[i - 1]][order[i]]
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
order,
|
|
46
|
+
legMiles,
|
|
47
|
+
totalMiles: legMiles.reduce((sum, miles) => sum + (isFiniteNumber(miles) ? miles : 0), 0)
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function reverseSegment(order, i, j) {
|
|
51
|
+
let left = i;
|
|
52
|
+
let right = j;
|
|
53
|
+
while (left < right) {
|
|
54
|
+
const held = order[left];
|
|
55
|
+
order[left] = order[right];
|
|
56
|
+
order[right] = held;
|
|
57
|
+
left++;
|
|
58
|
+
right--;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function orderFrom(origin, points, matrix) {
|
|
62
|
+
const n = points.length;
|
|
63
|
+
const visited = new Array(n).fill(false);
|
|
64
|
+
const order = [];
|
|
65
|
+
for (let step = 0; step < n; step++) {
|
|
66
|
+
let best = -1;
|
|
67
|
+
let bestMiles = Infinity;
|
|
68
|
+
for (let i = 0; i < n; i++) {
|
|
69
|
+
if (visited[i]) continue;
|
|
70
|
+
const miles = step === 0 ? haversineMiles(origin, points[i]) : matrix[order[step - 1]][i];
|
|
71
|
+
if (isFiniteNumber(miles) && miles < bestMiles) {
|
|
72
|
+
bestMiles = miles;
|
|
73
|
+
best = i;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (best === -1) {
|
|
77
|
+
for (let i = 0; i < n; i++) {
|
|
78
|
+
if (!visited[i]) {
|
|
79
|
+
visited[i] = true;
|
|
80
|
+
order.push(i);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
visited[best] = true;
|
|
86
|
+
order.push(best);
|
|
87
|
+
}
|
|
88
|
+
return order;
|
|
89
|
+
}
|
|
90
|
+
function nearestNeighborOrder(origin, points) {
|
|
91
|
+
const n = points.length;
|
|
92
|
+
if (n === 0) return { order: [], legMiles: [], totalMiles: 0 };
|
|
93
|
+
const matrix = distanceMatrix(points);
|
|
94
|
+
return legsFor(origin, points, orderFrom(origin, points, matrix), matrix);
|
|
95
|
+
}
|
|
96
|
+
function twoOptImprove(origin, points, order, matrix, opts = {}) {
|
|
97
|
+
const maxPasses = opts.maxPasses ?? 20;
|
|
98
|
+
if (order.length < 3) return [...order];
|
|
99
|
+
const best = [...order];
|
|
100
|
+
const last = best.length - 1;
|
|
101
|
+
const originMiles = points.map((point) => haversineMiles(origin, point));
|
|
102
|
+
for (let pass = 0; pass < maxPasses; pass++) {
|
|
103
|
+
let improved = false;
|
|
104
|
+
for (let i = 0; i <= last - 1; i++) {
|
|
105
|
+
for (let j = i + 1; j <= last; j++) {
|
|
106
|
+
const headOld = i === 0 ? originMiles[best[0]] : matrix[best[i - 1]][best[i]];
|
|
107
|
+
const headNew = i === 0 ? originMiles[best[j]] : matrix[best[i - 1]][best[j]];
|
|
108
|
+
const tailOld = j === last ? 0 : matrix[best[j]][best[j + 1]];
|
|
109
|
+
const tailNew = j === last ? 0 : matrix[best[i]][best[j + 1]];
|
|
110
|
+
if (headNew + tailNew - headOld - tailOld < -1e-4) {
|
|
111
|
+
reverseSegment(best, i, j);
|
|
112
|
+
improved = true;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (!improved) break;
|
|
117
|
+
}
|
|
118
|
+
return best;
|
|
119
|
+
}
|
|
120
|
+
function optimizeOrder(origin, points, opts = {}) {
|
|
121
|
+
const n = points.length;
|
|
122
|
+
if (n === 0) return { order: [], legMiles: [], totalMiles: 0 };
|
|
123
|
+
const matrix = distanceMatrix(points);
|
|
124
|
+
const greedy = orderFrom(origin, points, matrix);
|
|
125
|
+
if (opts.twoOpt === false || n < 3) return legsFor(origin, points, greedy, matrix);
|
|
126
|
+
const improved = twoOptImprove(origin, points, greedy, matrix, {
|
|
127
|
+
maxPasses: opts.maxPasses
|
|
128
|
+
});
|
|
129
|
+
return legsFor(origin, points, improved, matrix);
|
|
130
|
+
}
|
|
131
|
+
function measureOrder(origin, points, order) {
|
|
132
|
+
return legsFor(origin, points, order, distanceMatrix(points));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// src/route/mapsLinks.ts
|
|
136
|
+
var GOOGLE_MAX_WAYPOINTS = 9;
|
|
137
|
+
var GOOGLE_MAX_LEG_STOPS = GOOGLE_MAX_WAYPOINTS + 1;
|
|
138
|
+
var GOOGLE_DIR_BASE = "https://www.google.com/maps/dir/?api=1";
|
|
139
|
+
var GOOGLE_SEARCH_BASE = "https://www.google.com/maps/search/?api=1";
|
|
140
|
+
var APPLE_BASE = "https://maps.apple.com/";
|
|
141
|
+
function encodeTarget(target) {
|
|
142
|
+
const coords = target.coords;
|
|
143
|
+
if (coords && isFiniteNumber(coords.lat) && isFiniteNumber(coords.lng)) {
|
|
144
|
+
return `${coords.lat},${coords.lng}`;
|
|
145
|
+
}
|
|
146
|
+
if (target.address && target.address.trim()) {
|
|
147
|
+
return encodeURIComponent(target.address.trim());
|
|
148
|
+
}
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
function usableTargets(targets) {
|
|
152
|
+
return targets.map(encodeTarget).filter((value) => value !== null);
|
|
153
|
+
}
|
|
154
|
+
function googleDirectionsUrl(stops, origin, travelmode) {
|
|
155
|
+
const encoded = usableTargets(stops);
|
|
156
|
+
if (encoded.length === 0) return "";
|
|
157
|
+
const destination = encoded[encoded.length - 1];
|
|
158
|
+
const waypoints = encoded.slice(0, -1);
|
|
159
|
+
const encodedOrigin = origin ? encodeTarget(origin) : null;
|
|
160
|
+
let url = GOOGLE_DIR_BASE;
|
|
161
|
+
if (encodedOrigin) url += `&origin=${encodedOrigin}`;
|
|
162
|
+
url += `&destination=${destination}`;
|
|
163
|
+
if (waypoints.length > 0) url += `&waypoints=${waypoints.join("%7C")}`;
|
|
164
|
+
if (travelmode) url += `&travelmode=${encodeURIComponent(travelmode)}`;
|
|
165
|
+
return url;
|
|
166
|
+
}
|
|
167
|
+
function appleDirectionsUrl(stops, origin, dirflg = "d") {
|
|
168
|
+
const encoded = usableTargets(stops);
|
|
169
|
+
if (encoded.length === 0) return "";
|
|
170
|
+
const encodedOrigin = origin ? encodeTarget(origin) : null;
|
|
171
|
+
const daddr = encoded[0];
|
|
172
|
+
let url = `${APPLE_BASE}?`;
|
|
173
|
+
if (encodedOrigin) url += `saddr=${encodedOrigin}&`;
|
|
174
|
+
url += `daddr=${daddr}&dirflg=${encodeURIComponent(dirflg)}`;
|
|
175
|
+
return url;
|
|
176
|
+
}
|
|
177
|
+
function googleSearchUrl(query) {
|
|
178
|
+
return `${GOOGLE_SEARCH_BASE}&query=${encodeURIComponent(query)}`;
|
|
179
|
+
}
|
|
180
|
+
function splitIntoLegs(stops, maxPerLeg = GOOGLE_MAX_LEG_STOPS) {
|
|
181
|
+
if (maxPerLeg < 2) throw new RangeError("maxPerLeg must be at least 2");
|
|
182
|
+
if (stops.length === 0) return [];
|
|
183
|
+
if (stops.length <= maxPerLeg) return [[...stops]];
|
|
184
|
+
const legs = [];
|
|
185
|
+
let index = 0;
|
|
186
|
+
while (index < stops.length) {
|
|
187
|
+
const leg = stops.slice(index, index + maxPerLeg);
|
|
188
|
+
legs.push(leg);
|
|
189
|
+
index += maxPerLeg - 1;
|
|
190
|
+
if (index >= stops.length - 1) break;
|
|
191
|
+
}
|
|
192
|
+
return legs;
|
|
193
|
+
}
|
|
194
|
+
function googleDirectionsLegUrls(stops, origin, travelmode) {
|
|
195
|
+
const usable = stops.filter((stop) => encodeTarget(stop) !== null);
|
|
196
|
+
if (usable.length === 0) return [];
|
|
197
|
+
const legs = splitIntoLegs(usable, GOOGLE_MAX_LEG_STOPS);
|
|
198
|
+
return legs.map((leg, index) => {
|
|
199
|
+
if (index === 0) return googleDirectionsUrl(leg, origin, travelmode);
|
|
200
|
+
const [legOrigin, ...rest] = leg;
|
|
201
|
+
return googleDirectionsUrl(rest, legOrigin, travelmode);
|
|
202
|
+
}).filter((url) => url !== "");
|
|
203
|
+
}
|
|
204
|
+
function targetFromCoords(coords, address) {
|
|
205
|
+
return { coords, address };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export { EARTH_RADIUS_KM, EARTH_RADIUS_MILES, GOOGLE_MAX_LEG_STOPS, GOOGLE_MAX_WAYPOINTS, appleDirectionsUrl, distanceMatrix, googleDirectionsLegUrls, googleDirectionsUrl, googleSearchUrl, haversineKm, haversineMiles, measureOrder, nearestNeighborOrder, optimizeOrder, splitIntoLegs, targetFromCoords, twoOptImprove };
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { L as LngLat } from './data-DCyEqgN0.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Types for multi-stop route planning
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A geographic point in {lat, lng} object form.
|
|
9
|
+
*
|
|
10
|
+
* Deliberately NOT the `LngLat` tuple used by the rest of this package: route
|
|
11
|
+
* planning passes points through distance math, ordering and URL building, and
|
|
12
|
+
* a silently transposed tuple produces a plausible-looking route on the wrong
|
|
13
|
+
* side of the planet. The named fields make the mistake unrepresentable.
|
|
14
|
+
* Use `toLngLat` / `fromLngLat` at the map boundary.
|
|
15
|
+
*/
|
|
16
|
+
interface LatLng {
|
|
17
|
+
lat: number;
|
|
18
|
+
lng: number;
|
|
19
|
+
}
|
|
20
|
+
/** Convert to the tuple form MapLibre and the rest of maps-core expect */
|
|
21
|
+
declare function toLngLat(point: LatLng): LngLat;
|
|
22
|
+
/** Convert from the tuple form MapLibre and the rest of maps-core expect */
|
|
23
|
+
declare function fromLngLat(point: LngLat): LatLng;
|
|
24
|
+
/**
|
|
25
|
+
* True for a real, finite number - and only for one.
|
|
26
|
+
*
|
|
27
|
+
* `Number.isFinite`, never the global `isFinite`: the global coerces its
|
|
28
|
+
* argument first, so `isFinite(null)` and `isFinite('')` are both true. A null
|
|
29
|
+
* coordinate out of a JSON API or a nullable column would then sail through as
|
|
30
|
+
* 0, and 0,0 is a real place in the Gulf of Guinea rather than the miss it
|
|
31
|
+
* actually is.
|
|
32
|
+
*/
|
|
33
|
+
declare function isFiniteNumber(value: unknown): value is number;
|
|
34
|
+
/** True when both components are present, numeric, finite and in range */
|
|
35
|
+
declare function isValidLatLng(point: unknown): point is LatLng;
|
|
36
|
+
/** The result of ordering a set of points */
|
|
37
|
+
interface OrderResult {
|
|
38
|
+
/** Indices into the input array, in visit order */
|
|
39
|
+
order: number[];
|
|
40
|
+
/**
|
|
41
|
+
* Distance in miles for each visited leg. `legMiles[0]` is origin -> first
|
|
42
|
+
* stop; `legMiles[i]` is the leg arriving at `order[i]`.
|
|
43
|
+
*/
|
|
44
|
+
legMiles: number[];
|
|
45
|
+
/** Sum of `legMiles` */
|
|
46
|
+
totalMiles: number;
|
|
47
|
+
}
|
|
48
|
+
/** Travel modes Google Maps understands on the `api=1` directions URL */
|
|
49
|
+
type TravelMode = 'driving' | 'walking' | 'bicycling' | 'transit';
|
|
50
|
+
/**
|
|
51
|
+
* Something a maps app can navigate to: a coordinate, a text address, or both.
|
|
52
|
+
* When both are present the coordinate wins - it cannot be misgeocoded.
|
|
53
|
+
*/
|
|
54
|
+
interface DirectionsTarget {
|
|
55
|
+
coords?: LatLng | null;
|
|
56
|
+
address?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export { type DirectionsTarget as D, type LatLng as L, type OrderResult as O, type TravelMode as T, isValidLatLng as a, fromLngLat as f, isFiniteNumber as i, toLngLat as t };
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { L as LngLat } from './data-DCyEqgN0.cjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Types for multi-stop route planning
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A geographic point in {lat, lng} object form.
|
|
9
|
+
*
|
|
10
|
+
* Deliberately NOT the `LngLat` tuple used by the rest of this package: route
|
|
11
|
+
* planning passes points through distance math, ordering and URL building, and
|
|
12
|
+
* a silently transposed tuple produces a plausible-looking route on the wrong
|
|
13
|
+
* side of the planet. The named fields make the mistake unrepresentable.
|
|
14
|
+
* Use `toLngLat` / `fromLngLat` at the map boundary.
|
|
15
|
+
*/
|
|
16
|
+
interface LatLng {
|
|
17
|
+
lat: number;
|
|
18
|
+
lng: number;
|
|
19
|
+
}
|
|
20
|
+
/** Convert to the tuple form MapLibre and the rest of maps-core expect */
|
|
21
|
+
declare function toLngLat(point: LatLng): LngLat;
|
|
22
|
+
/** Convert from the tuple form MapLibre and the rest of maps-core expect */
|
|
23
|
+
declare function fromLngLat(point: LngLat): LatLng;
|
|
24
|
+
/**
|
|
25
|
+
* True for a real, finite number - and only for one.
|
|
26
|
+
*
|
|
27
|
+
* `Number.isFinite`, never the global `isFinite`: the global coerces its
|
|
28
|
+
* argument first, so `isFinite(null)` and `isFinite('')` are both true. A null
|
|
29
|
+
* coordinate out of a JSON API or a nullable column would then sail through as
|
|
30
|
+
* 0, and 0,0 is a real place in the Gulf of Guinea rather than the miss it
|
|
31
|
+
* actually is.
|
|
32
|
+
*/
|
|
33
|
+
declare function isFiniteNumber(value: unknown): value is number;
|
|
34
|
+
/** True when both components are present, numeric, finite and in range */
|
|
35
|
+
declare function isValidLatLng(point: unknown): point is LatLng;
|
|
36
|
+
/** The result of ordering a set of points */
|
|
37
|
+
interface OrderResult {
|
|
38
|
+
/** Indices into the input array, in visit order */
|
|
39
|
+
order: number[];
|
|
40
|
+
/**
|
|
41
|
+
* Distance in miles for each visited leg. `legMiles[0]` is origin -> first
|
|
42
|
+
* stop; `legMiles[i]` is the leg arriving at `order[i]`.
|
|
43
|
+
*/
|
|
44
|
+
legMiles: number[];
|
|
45
|
+
/** Sum of `legMiles` */
|
|
46
|
+
totalMiles: number;
|
|
47
|
+
}
|
|
48
|
+
/** Travel modes Google Maps understands on the `api=1` directions URL */
|
|
49
|
+
type TravelMode = 'driving' | 'walking' | 'bicycling' | 'transit';
|
|
50
|
+
/**
|
|
51
|
+
* Something a maps app can navigate to: a coordinate, a text address, or both.
|
|
52
|
+
* When both are present the coordinate wins - it cannot be misgeocoded.
|
|
53
|
+
*/
|
|
54
|
+
interface DirectionsTarget {
|
|
55
|
+
coords?: LatLng | null;
|
|
56
|
+
address?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export { type DirectionsTarget as D, type LatLng as L, type OrderResult as O, type TravelMode as T, isValidLatLng as a, fromLngLat as f, isFiniteNumber as i, toLngLat as t };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@classic-homes/maps-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Core utilities and theme for Classic Theme maps",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"maps",
|
|
@@ -34,6 +34,16 @@
|
|
|
34
34
|
"import": "./dist/types/index.js",
|
|
35
35
|
"require": "./dist/types/index.cjs"
|
|
36
36
|
},
|
|
37
|
+
"./route": {
|
|
38
|
+
"types": "./dist/route/index.d.ts",
|
|
39
|
+
"import": "./dist/route/index.js",
|
|
40
|
+
"require": "./dist/route/index.cjs"
|
|
41
|
+
},
|
|
42
|
+
"./geocoding": {
|
|
43
|
+
"types": "./dist/geocoding/index.d.ts",
|
|
44
|
+
"import": "./dist/geocoding/index.js",
|
|
45
|
+
"require": "./dist/geocoding/index.cjs"
|
|
46
|
+
},
|
|
37
47
|
"./utils": {
|
|
38
48
|
"types": "./dist/utils/index.d.ts",
|
|
39
49
|
"import": "./dist/utils/index.js",
|