geoverse-line-finder 0.1.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.
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ 🌐 [简体中文](CHANGELOG.md) | English
4
+
5
+ This project follows [Semantic Versioning](https://semver.org/); while in 0.x, minor versions may contain breaking changes.
6
+
7
+ ## 0.1.0 — 2026-09-11
8
+
9
+ First release, open-sourced under the Apache License 2.0.
10
+
11
+ ### Added
12
+
13
+ - `LineFinder`: weighted shortest paths on GeoJSON line networks (`LineString` / `MultiLineString`), between two points or through several waypoints in order.
14
+ - Weights: the geojson-path-finder weight-function contract (number / `{ forward, backward }` / falsy = impassable), plus `context.distance`;
15
+ `createPropertyWeight`, `createSpeedWeight` and `osmDirection` presets; negative weights throw `RangeError`.
16
+ - Engines: `AlgorithmRegistry` with the built-in `astar` and `dijkstra`; custom engines plug in through the `PathAlgorithm` / `SearchGraph` contract; the priority queue is replaceable.
17
+ - Metrics: `haversine` (default), `cheap-ruler`, `euclidean` or a custom `Metric`; the A\* heuristic is admissible for any weight.
18
+ - Connectivity repair: `tolerance` merges vertices by real distance, `snapDangles` connects dangling ends, `splitIntersections` splits crossings; degree-2 vertices are compacted into chains.
19
+ - Snapping: `edge` / `vertex` / `node` / `exact` modes, `maxDistance`, connectivity-aware assignment; a standalone `nearest()`.
20
+ - Results: `legs`, `sections` grouped by source feature, `waypoints`, failure reasons as a discriminated union, `toLineString()`.
21
+ - Builds: ESM, CommonJS, type declarations and an IIFE bundle (global `GeoVerseLineFinder`).
22
+ - Project: GitHub Actions CI (full gate on Node 20 / 22, dist smoke test on Node 18 / 20 / 22) and tag-triggered releases with npm provenance; documentation in Chinese (primary) and English.
package/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ 🌐 简体中文 | [English](CHANGELOG.en.md)
4
+
5
+ 本项目遵循[语义化版本](https://semver.org/lang/zh-CN/);0.x 期间,次版本号可能包含不兼容变更。
6
+
7
+ ## 0.1.0 — 2026-09-11
8
+
9
+ 首个版本,以 Apache-2.0 协议开源。
10
+
11
+ ### 新增
12
+
13
+ - `LineFinder`:GeoJSON 线网络(`LineString` / `MultiLineString`)上的带权最短路,支持两点与按顺序的多途经点。
14
+ - 权重:兼容 geojson-path-finder 的权重函数契约(数字 / `{ forward, backward }` / 假值不可通行),额外提供 `context.distance`;
15
+ `createPropertyWeight`、`createSpeedWeight`、`osmDirection` 预设;负权重抛 `RangeError`。
16
+ - 引擎:`AlgorithmRegistry` 与内置 `astar`、`dijkstra`;`PathAlgorithm` / `SearchGraph` 契约可接入自定义引擎;优先队列可替换。
17
+ - 度量:`haversine`(默认)、`cheap-ruler`、`euclidean` 或自定义 `Metric`;A\* 启发式对任意权重可采纳。
18
+ - 连通修复:`tolerance` 按真实距离合并顶点、`snapDangles` 连接悬挂端点、`splitIntersections` 打断交叉;度 2 顶点压缩成链。
19
+ - 吸附:`edge` / `vertex` / `node` / `exact` 四种模式、`maxDistance`、连通性感知分配;单独的 `nearest()`。
20
+ - 结果:`legs`、按来源要素聚合的 `sections`、`waypoints`、判别联合的失败原因、`toLineString()`。
21
+ - 产物:ESM、CommonJS、类型声明,以及 IIFE(全局 `GeoVerseLineFinder`)。
22
+ - 工程:GitHub Actions 的 CI(Node 20 / 22 全部门禁,Node 18 / 20 / 22 产物冒烟)与打 tag 发布(npm provenance);中英文文档,中文为主。
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,8 @@
1
+ geoverse-line-finder
2
+ Copyright 2026 DIY Liu
3
+
4
+ Licensed under the Apache License, Version 2.0; see the LICENSE file.
5
+
6
+ This product includes code adapted from third-party projects distributed under
7
+ the MIT and ISC licenses (terra-route, geojson-path-finder, cheap-ruler and
8
+ flatbush). Their attributions and license texts are in THIRD_PARTY_NOTICES.md.
package/README.en.md ADDED
@@ -0,0 +1,169 @@
1
+ # geoverse-line-finder
2
+
3
+ 🌐 [简体中文](README.md) | English
4
+
5
+ [![CI](https://github.com/GeoVerseLabs/geoverse-line-finder/actions/workflows/ci.yml/badge.svg)](https://github.com/GeoVerseLabs/geoverse-line-finder/actions/workflows/ci.yml)
6
+ [![npm](https://img.shields.io/npm/v/geoverse-line-finder)](https://www.npmjs.com/package/geoverse-line-finder)
7
+ [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
8
+
9
+ A zero-dependency TypeScript library for shortest paths on GeoJSON line networks (`LineString` / `MultiLineString`):
10
+
11
+ - **Configurable weights**: weight functions fully compatible with geojson-path-finder (the same cost both ways / `{ forward, backward }` per direction / falsy = impassable), plus a length context and declarative presets;
12
+ - **Switchable engines**: built-in A* and Dijkstra, selectable per query by name, and you can register your own;
13
+ - **Snapping and connectivity**: start and end points need not be network vertices (they are projected onto the nearest segment); at build time nearby vertices can be merged, dangling ends repaired and crossings split; at query time waypoints are snapped with the network's connected components in mind;
14
+ - **Two points or many waypoints**: one call returns the whole route, per-leg results and `sections` grouped by source feature.
15
+
16
+ The routing core follows [terra-route](https://github.com/JamesLMilner/terra-route) (CSR adjacency, 4-ary heap, reusable scratch buffers); the weight configuration follows [geojson-path-finder](https://github.com/perliedman/geojson-path-finder). Works in browsers, Web Workers and Node.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pnpm add geoverse-line-finder
22
+ ```
23
+
24
+ Ships both ESM and CommonJS (Node ≥ 18). Without a bundler, load it with a `<script>` tag; the global is `GeoVerseLineFinder`:
25
+
26
+ ```html
27
+ <script src="https://unpkg.com/geoverse-line-finder@0.1.0"></script>
28
+ <script>
29
+ const finder = new GeoVerseLineFinder.LineFinder(roads);
30
+ </script>
31
+ ```
32
+
33
+ ## Quick start
34
+
35
+ ```ts
36
+ import { LineFinder, toLineString } from 'geoverse-line-finder';
37
+
38
+ const finder = new LineFinder(roads); // roads: FeatureCollection<LineString>
39
+
40
+ // Two points: they need not be network vertices; by default they snap to the nearest segment
41
+ const route = finder.route([
42
+ [116.397, 39.908],
43
+ [116.41, 39.92],
44
+ ]);
45
+ if (route.ok) {
46
+ console.log(route.distance, 'm'); // length along the network
47
+ console.log(route.path); // coordinates
48
+ map.addGeoJSON(toLineString(route)); // GeoJSON LineString
49
+ } else {
50
+ console.warn(route.reason, route.message); // SNAP_FAILED / DISCONNECTED / UNREACHABLE / INVALID_INPUT
51
+ }
52
+
53
+ // Several waypoints, visited in the given order
54
+ const tour = finder.route([start, via1, via2, end], { algorithm: 'dijkstra' });
55
+ tour.ok && tour.legs.forEach((leg) => console.log(leg.from, '→', leg.to, leg.weight));
56
+ ```
57
+
58
+ ## Weights
59
+
60
+ The signature matches geojson-path-finder's, plus a `context` argument (`distance` is the precomputed segment length, in the metric's unit):
61
+
62
+ ```ts
63
+ const finder = new LineFinder(roads, {
64
+ weight: (a, b, props, { distance }) => {
65
+ if (props.highway === 'footway') return 0; // impassable
66
+ const seconds = distance / ((props.maxspeed ?? 30) / 3.6);
67
+ return props.oneway === 'yes' ? { forward: seconds } : seconds; // one-way
68
+ },
69
+ });
70
+ ```
71
+
72
+ | Return value | Meaning |
73
+ | --------------------------------------------------------- | ---------------------------------------------------------------------------- |
74
+ | positive number | the same cost in both directions |
75
+ | `{ forward, backward }` | forward = along the digitised a→b order; a missing direction is impassable |
76
+ | `0` / `NaN` / `Infinity` / `null` / `undefined` / `false` | impassable |
77
+ | negative number | throws `RangeError` (negative costs silently break shortest-path algorithms) |
78
+
79
+ Presets:
80
+
81
+ ```ts
82
+ import { createPropertyWeight, createSpeedWeight, osmDirection } from 'geoverse-line-finder';
83
+
84
+ createPropertyWeight({
85
+ factor: (p) => ({ primary: 0.8, residential: 1.2 })[p.highway] ?? 1,
86
+ direction: osmDirection,
87
+ });
88
+ createSpeedWeight({ speed: (p) => Number(p.maxspeed) || 30, direction: osmDirection }); // seconds
89
+ ```
90
+
91
+ ## Engines
92
+
93
+ ```ts
94
+ finder.route(points, { algorithm: 'astar' }); // default
95
+ finder.route(points, { algorithm: 'dijkstra' });
96
+
97
+ // Register a custom engine (implement PathAlgorithm, see docs/ARCHITECTURE.en.md §4)
98
+ finder.registerAlgorithm(myBidirectionalDijkstra);
99
+ finder.route(points, { algorithm: 'bidirectional-dijkstra' });
100
+ ```
101
+
102
+ The A* heuristic is admissible for **any** weight (metric embedding × the network-wide minimum cost-per-length ratio), so A* returns the same optimal cost as Dijkstra while expanding fewer nodes.
103
+
104
+ ## Snapping and connectivity
105
+
106
+ Build time (`new LineFinder(network, options)`):
107
+
108
+ | Option | Default | Description |
109
+ | -------------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------- |
110
+ | `metric` | `'haversine'` | `'haversine'` (lng/lat degrees, meters), `'cheap-ruler'`, `'euclidean'` (projected coordinates) or a custom metric |
111
+ | `tolerance` | `0` | vertices closer than this are merged into one (by real distance; geojson-path-finder's default of 1e-5° is about 1.1 m) |
112
+ | `snapDangles` | `0` | connect dangling ends to the nearest segment within this distance |
113
+ | `splitIntersections` | `false` | split lines where they cross or touch without a shared vertex (this also joins overpasses — enable deliberately) |
114
+ | `compact` | `true` | collapse degree-2 vertices into chains: identical results, faster search |
115
+
116
+ Query time (`route(points, { snap })`):
117
+
118
+ | Option | Default | Description |
119
+ | -------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
120
+ | `mode` | `'edge'` | `'edge'` project onto the nearest segment · `'vertex'` nearest vertex · `'node'` nearest junction / dead end · `'exact'` must be a vertex |
121
+ | `maxDistance` | `Infinity` | anything farther fails with `SNAP_FAILED` |
122
+ | `connectivity` | `'connected'` | when the waypoints' nearest locations lie in components that are not connected, use nearby locations in a component all of them can reach; `'nearest'` always takes the nearest |
123
+
124
+ `finder.nearest(point)` returns the nearest network location on its own, e.g. for interactive snapping hints.
125
+
126
+ ## Result
127
+
128
+ ```ts
129
+ interface RouteSuccess {
130
+ ok: true;
131
+ path: Position[]; // the whole route
132
+ weight: number; // total cost that was minimised
133
+ distance: number; // total length along the network
134
+ legs: RouteLeg[]; // per leg: path / weight / distance / sections / settled
135
+ waypoints: { input; location; distance; component; featureIndex }[];
136
+ algorithm: string;
137
+ }
138
+ ```
139
+
140
+ `leg.sections` groups the path by source feature (with `properties`, its index range in `leg.path`, length and cost) — handy for listing the streets along a route.
141
+
142
+ ## Migrating from geojson-path-finder
143
+
144
+ | geojson-path-finder | geoverse-line-finder |
145
+ | ------------------------------------------------------ | ---------------------------------------------------------------------------------- |
146
+ | `new PathFinder(geojson, { weight, tolerance: 1e-5 })` | `new LineFinder(geojson, { weight, tolerance: 1.1 })` (tolerance is now in meters) |
147
+ | `findPath(a, b)` → `{ path, weight } \| undefined` | `findPath(a, b)` / `route([a, b])` → `{ ok, path, weight, … }` |
148
+ | start and end must be vertices | segment snapping by default; `snap: { mode: 'exact' }` restores the old behaviour |
149
+ | default weight = kilometers | default weight = meters (the metric's unit) |
150
+ | `edgeDataReducer` / `edgeDataSeed` | `leg.sections` (no configuration needed) |
151
+ | `pathToGeoJSON(path)` | `toLineString(route)` |
152
+
153
+ ## Performance and correctness
154
+
155
+ - All structures are flat typed arrays; queries reuse scratch buffers and only touch the nodes they visit.
156
+ - The tests include randomized differential testing against a naive reference implementation, every assertion from geojson-path-finder's own suite, and pair-by-pair comparison with an independent referee on geojson-path-finder's 135k-coordinate one-way OSM network.
157
+ - CI (GitHub Actions) runs the full gate on Node 20 / 22 and loads the built package on Node 18 / 20 / 22; pushing a `vX.Y.Z` tag publishes to npm — see [docs/RELEASE.en.md](docs/RELEASE.en.md).
158
+ - Measurements and how to reproduce them: [docs/BENCHMARK.en.md](docs/BENCHMARK.en.md); design notes: [docs/ARCHITECTURE.en.md](docs/ARCHITECTURE.en.md).
159
+
160
+ ```bash
161
+ pnpm test # unit + differential + parity tests
162
+ pnpm bench # three-library benchmark (geojson-path-finder test data, ≥ 3 rounds)
163
+ pnpm bench:gpf # root-cause experiment for geojson-path-finder's non-shortest routes
164
+ pnpm check # typecheck + lint + format + tests (coverage ratchet) + build + dist smoke test
165
+ ```
166
+
167
+ ## License
168
+
169
+ [Apache-2.0](LICENSE); copyright and attribution in [NOTICE](NOTICE). Borrowed code and ideas (MIT / ISC) are listed in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
package/README.md ADDED
@@ -0,0 +1,169 @@
1
+ # geoverse-line-finder
2
+
3
+ 🌐 简体中文 | [English](README.en.md)
4
+
5
+ [![CI](https://github.com/GeoVerseLabs/geoverse-line-finder/actions/workflows/ci.yml/badge.svg)](https://github.com/GeoVerseLabs/geoverse-line-finder/actions/workflows/ci.yml)
6
+ [![npm](https://img.shields.io/npm/v/geoverse-line-finder)](https://www.npmjs.com/package/geoverse-line-finder)
7
+ [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
8
+
9
+ 在 GeoJSON 线网络(`LineString` / `MultiLineString`)上求最短路径的零依赖 TypeScript 库:
10
+
11
+ - **可配置权重**:与 geojson-path-finder 完全兼容的权重函数(双向同价 / `{ forward, backward }` 分方向 / 假值不可通行),外加长度上下文与声明式预设;
12
+ - **可切换引擎**:内置 A* 与 Dijkstra,按名称逐次切换,也可注册自己的引擎;
13
+ - **吸附与连通**:起终点可以不在路网顶点上(投影到最近线段),建图期可合并近点、修复悬挂端点、打断交叉,查询期按连通分量智能吸附;
14
+ - **两点与多途经点**:一次调用得到整条路线、分段结果与按要素聚合的 `sections`。
15
+
16
+ 路径主体借鉴 [terra-route](https://github.com/JamesLMilner/terra-route)(CSR 邻接、四叉堆、scratch 复用),权重配置借鉴 [geojson-path-finder](https://github.com/perliedman/geojson-path-finder)。浏览器、Web Worker、Node 通用。
17
+
18
+ ## 安装
19
+
20
+ ```bash
21
+ pnpm add geoverse-line-finder
22
+ ```
23
+
24
+ 同时提供 ESM 与 CommonJS(Node ≥ 18)。不经打包器时可直接用 `<script>` 引入,全局变量为 `GeoVerseLineFinder`:
25
+
26
+ ```html
27
+ <script src="https://unpkg.com/geoverse-line-finder@0.1.0"></script>
28
+ <script>
29
+ const finder = new GeoVerseLineFinder.LineFinder(roads);
30
+ </script>
31
+ ```
32
+
33
+ ## 快速开始
34
+
35
+ ```ts
36
+ import { LineFinder, toLineString } from 'geoverse-line-finder';
37
+
38
+ const finder = new LineFinder(roads); // roads: FeatureCollection<LineString>
39
+
40
+ // 两点:起终点不必是路网顶点,默认投影到最近线段
41
+ const route = finder.route([
42
+ [116.397, 39.908],
43
+ [116.41, 39.92],
44
+ ]);
45
+ if (route.ok) {
46
+ console.log(route.distance, 'm'); // 沿路网长度
47
+ console.log(route.path); // 坐标串
48
+ map.addGeoJSON(toLineString(route)); // GeoJSON LineString
49
+ } else {
50
+ console.warn(route.reason, route.message); // SNAP_FAILED / DISCONNECTED / UNREACHABLE / INVALID_INPUT
51
+ }
52
+
53
+ // 多途经点:按给定顺序依次经过
54
+ const tour = finder.route([start, via1, via2, end], { algorithm: 'dijkstra' });
55
+ tour.ok && tour.legs.forEach((leg) => console.log(leg.from, '→', leg.to, leg.weight));
56
+ ```
57
+
58
+ ## 权重
59
+
60
+ 权重函数签名与 geojson-path-finder 相同,多一个 `context` 参数(`distance` 为已算好的线段长度,单位同度量):
61
+
62
+ ```ts
63
+ const finder = new LineFinder(roads, {
64
+ weight: (a, b, props, { distance }) => {
65
+ if (props.highway === 'footway') return 0; // 不可通行
66
+ const seconds = distance / ((props.maxspeed ?? 30) / 3.6);
67
+ return props.oneway === 'yes' ? { forward: seconds } : seconds; // 单向
68
+ },
69
+ });
70
+ ```
71
+
72
+ | 返回值 | 含义 |
73
+ | --------------------------------------------------------- | ---------------------------------------------- |
74
+ | 正数 | 两个方向同价 |
75
+ | `{ forward, backward }` | forward = 沿数字化方向 a→b;缺省的方向不可通行 |
76
+ | `0` / `NaN` / `Infinity` / `null` / `undefined` / `false` | 不可通行 |
77
+ | 负数 | 抛 `RangeError`(负权会让最短路算法静默出错) |
78
+
79
+ 预设:
80
+
81
+ ```ts
82
+ import { createPropertyWeight, createSpeedWeight, osmDirection } from 'geoverse-line-finder';
83
+
84
+ createPropertyWeight({
85
+ factor: (p) => ({ primary: 0.8, residential: 1.2 })[p.highway] ?? 1,
86
+ direction: osmDirection,
87
+ });
88
+ createSpeedWeight({ speed: (p) => Number(p.maxspeed) || 30, direction: osmDirection }); // 秒
89
+ ```
90
+
91
+ ## 引擎
92
+
93
+ ```ts
94
+ finder.route(points, { algorithm: 'astar' }); // 默认
95
+ finder.route(points, { algorithm: 'dijkstra' });
96
+
97
+ // 注册自定义引擎(实现 PathAlgorithm 即可,见 docs/ARCHITECTURE.md §4)
98
+ finder.registerAlgorithm(myBidirectionalDijkstra);
99
+ finder.route(points, { algorithm: 'bidirectional-dijkstra' });
100
+ ```
101
+
102
+ A* 的启发式对**任意**权重都可采纳(度量嵌入 × 全网最小"代价/长度"比),因此与 Dijkstra 给出相同的最优代价,只是展开的节点更少。
103
+
104
+ ## 吸附与连通
105
+
106
+ 建图期(`new LineFinder(network, options)`):
107
+
108
+ | 选项 | 默认 | 说明 |
109
+ | -------------------- | ------------- | ------------------------------------------------------------------------------------------ |
110
+ | `metric` | `'haversine'` | `'haversine'`(经纬度,米)、`'cheap-ruler'`、`'euclidean'`(投影坐标)或自定义 |
111
+ | `tolerance` | `0` | 相距不超过该距离的顶点合并为一个(按真实距离判断;geojson-path-finder 默认 1e-5° ≈ 1.1 m) |
112
+ | `snapDangles` | `0` | 把悬挂端点接到该距离内最近的线段上 |
113
+ | `splitIntersections` | `false` | 在未共点的交叉/接触处打断(会把立交也接上,按需开启) |
114
+ | `compact` | `true` | 度 2 顶点压缩成链,结果不变、搜索更快 |
115
+
116
+ 查询期(`route(points, { snap })`):
117
+
118
+ | 选项 | 默认 | 说明 |
119
+ | -------------- | ------------- | --------------------------------------------------------------------------------------------- |
120
+ | `mode` | `'edge'` | `'edge'` 投影到最近线段 · `'vertex'` 最近顶点 · `'node'` 最近路口/端点 · `'exact'` 必须是顶点 |
121
+ | `maxDistance` | `Infinity` | 超出即 `SNAP_FAILED` |
122
+ | `connectivity` | `'connected'` | 途经点最近位置分属不连通的分量时,改用都能到达的分量里的附近位置;`'nearest'` 始终取最近 |
123
+
124
+ `finder.nearest(point)` 单独返回最近的路网位置,可用于交互式吸附提示。
125
+
126
+ ## 结果
127
+
128
+ ```ts
129
+ interface RouteSuccess {
130
+ ok: true;
131
+ path: Position[]; // 整条路线
132
+ weight: number; // 被最小化的总代价
133
+ distance: number; // 沿路网总长度
134
+ legs: RouteLeg[]; // 每段:path / weight / distance / sections / settled
135
+ waypoints: { input; location; distance; component; featureIndex }[];
136
+ algorithm: string;
137
+ }
138
+ ```
139
+
140
+ `leg.sections` 把路径按来源要素聚合(含 `properties`、在 `leg.path` 中的下标区间、长度与代价),可直接用来列出途经道路名。
141
+
142
+ ## 从 geojson-path-finder 迁移
143
+
144
+ | geojson-path-finder | geoverse-line-finder |
145
+ | ------------------------------------------------------ | ------------------------------------------------------------------- |
146
+ | `new PathFinder(geojson, { weight, tolerance: 1e-5 })` | `new LineFinder(geojson, { weight, tolerance: 1.1 })`(容差改为米) |
147
+ | `findPath(a, b)` → `{ path, weight } \| undefined` | `findPath(a, b)` / `route([a, b])` → `{ ok, path, weight, … }` |
148
+ | 起终点必须是顶点 | 默认线段吸附;要旧行为用 `snap: { mode: 'exact' }` |
149
+ | 默认权重 = 公里 | 默认权重 = 米(`metric` 单位) |
150
+ | `edgeDataReducer` / `edgeDataSeed` | `leg.sections`(无需配置) |
151
+ | `pathToGeoJSON(path)` | `toLineString(route)` |
152
+
153
+ ## 性能与正确性
154
+
155
+ - 全部结构为扁平 TypedArray;查询复用 scratch 缓冲,只触碰访问到的节点。
156
+ - 测试含与朴素参考实现的随机差分、GPF 自带测试的全部断言,以及在 GPF 的 13.5 万坐标 OSM 单向路网上与独立裁判逐对比对。
157
+ - CI(GitHub Actions)在 Node 20 / 22 上跑全部门禁,并在 Node 18 / 20 / 22 上直接加载构建产物;推送 `vX.Y.Z` tag 自动发布到 npm,见 [docs/RELEASE.md](docs/RELEASE.md)。
158
+ - 实测数据与复现方法见 [docs/BENCHMARK.md](docs/BENCHMARK.md);设计说明见 [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)。
159
+
160
+ ```bash
161
+ pnpm test # 单元 + 差分 + 对齐测试
162
+ pnpm bench # 三库基准(geojson-path-finder 测试数据,≥3 轮)
163
+ pnpm bench:gpf # geojson-path-finder 次优路线的根因实验
164
+ pnpm check # 类型检查 + lint + 格式 + 测试(覆盖率棘轮)+ 构建 + 产物冒烟
165
+ ```
166
+
167
+ ## 许可
168
+
169
+ [Apache-2.0](LICENSE),版权与归属说明见 [NOTICE](NOTICE)。借用的代码与思路(MIT / ISC)见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。
@@ -0,0 +1,50 @@
1
+ # Third-party notices
2
+
3
+ geoverse-line-finder is an independent implementation licensed under the Apache License 2.0
4
+ (see `LICENSE` and `NOTICE`). It adapts ideas and, where noted, small pieces of code from the
5
+ projects below; their licenses are reproduced as required and continue to apply to those portions.
6
+
7
+ | Project | License | What was adapted |
8
+ | -------------------------------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
9
+ | [terra-route](https://github.com/JamesLMilner/terra-route) — James Milner | MIT | 4-ary heap with stable tie-breaking (`src/heap/four-ary-heap.ts`); CSR adjacency layout and generation-stamped scratch buffers used by the search engines |
10
+ | [geojson-path-finder](https://github.com/perliedman/geojson-path-finder) — Per Liedman | ISC | Weight-function contract (`number` / `{ forward, backward }` / falsy = impassable), degree-2 compaction idea; small test fixtures under `test/fixtures/gpf/` |
11
+ | [cheap-ruler](https://github.com/mapbox/cheap-ruler) — Mapbox | ISC | Local-scale distance approximation (`src/geo/metric.ts`, `cheapRulerMetric`) |
12
+ | [flatbush](https://github.com/mourner/flatbush) — Vladimir Agafonkin | ISC | Packed Hilbert R-tree layout and the Hilbert-curve index function (`src/spatial/rtree.ts`) |
13
+
14
+ ---
15
+
16
+ ## MIT License (terra-route)
17
+
18
+ Copyright (c) James Milner
19
+
20
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this
21
+ software and associated documentation files (the "Software"), to deal in the Software
22
+ without restriction, including without limitation the rights to use, copy, modify,
23
+ merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
24
+ permit persons to whom the Software is furnished to do so, subject to the following
25
+ conditions:
26
+
27
+ The above copyright notice and this permission notice shall be included in all copies
28
+ or substantial portions of the Software.
29
+
30
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
31
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
32
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
33
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
34
+ CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
35
+ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36
+
37
+ ## ISC License (geojson-path-finder, cheap-ruler, flatbush)
38
+
39
+ Copyright (c) Per Liedman; Copyright (c) 2024, Mapbox; Copyright (c) 2018, Vladimir Agafonkin
40
+
41
+ Permission to use, copy, modify, and/or distribute this software for any purpose with
42
+ or without fee is hereby granted, provided that the above copyright notice and this
43
+ permission notice appear in all copies.
44
+
45
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
46
+ TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
47
+ NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
48
+ CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
49
+ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
50
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.