terra-route 0.0.6 → 0.0.8

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Terra Route
2
2
 
3
- Terra Route aims to be a fast library for routing on GeoJSON LineStrings networks, where LineStrings share identical coordinates. Terra Routes main aim is currently performance - it uses bidirectional A* to help achieve this.
3
+ Terra Route aims to be a fast library for routing on GeoJSON LineStrings networks, where LineStrings share identical coordinates. Terra Routes main aim is currently performance - it uses A* to help achieve this.
4
4
 
5
5
  ## Install
6
6
 
@@ -91,14 +91,16 @@ npm run benchmark
91
91
 
92
92
  Here is an example output of a benchmark run for routing:
93
93
 
94
- TerraRoute with CheapRuler | █ 26ms
95
- TerraRoute | ██ 42ms
96
- GeoJSON Path Finder | █████████████████████████ 609ms
97
- ngraph.graph | ██████████████████████████████████████████████████ 1227ms
94
+ <pre>
95
+ Terra Route with CheapRuler | ███████ 220ms
96
+ Terra Route | ███████████ 360ms
97
+ GeoJSON Path Finder | ███████████████████ 592ms
98
+ ngraph.graph | ██████████████████████████████████████████████████ 1587ms
99
+ </pre>
98
100
 
99
- Using default Haversine distance, Terra Route is approximately 13x faster than GeoJSON Path Finder with Haversine distance for A -> B path finding. If you pass in the CheapRuler distance metric (you can use the exposed `createCheapRuler` function), it is about 22x faster.
101
+ Using default Haversine distance, Terra Route is approximately 1.6x faster than GeoJSON Path Finder with Haversine distance for A -> B path finding. If you pass in the CheapRuler distance metric (you can use the exposed `createCheapRuler` function), it is about x2.75 faster.
100
102
 
101
- For initialisation of the network, Terra Route is about 9x faster with Haversine and 14x faster with CheapRuler than GeoJSON Path Finder. Terra Draw splits out instantiating the Class of the library from the actual graph building, which is done via `buildRouteGraph`. This allows you to defer graph creation to an appropriate time.
103
+ For initialisation of the network, Terra Route is about 10x faster with Haversine than GeoJSON Path Finder. Terra Draw splits out instantiating the Class of the library from the actual graph building, which is done via `buildRouteGraph`. This allows you to defer graph creation to an appropriate time.
102
104
 
103
105
  ## Limitations
104
106
 
@@ -1,2 +1,3 @@
1
1
  import { Position } from "geojson";
2
+ /** Distance measured in kilometers */
2
3
  export declare const haversineDistance: (pointOne: Position, pointTwo: Position) => number;
@@ -0,0 +1,9 @@
1
+ import { Heap } from "./heap";
2
+ export declare class MinHeap implements Heap {
3
+ private heap;
4
+ private insertCounter;
5
+ insert(key: number, value: number): void;
6
+ extractMin(): number | null;
7
+ size(): number;
8
+ private bubbleDown;
9
+ }
@@ -1,2 +1,2 @@
1
- function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function e(e,n){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,n){if(e){if("string"==typeof e)return t(e,n);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(e,n):void 0}}(e))||n&&e&&"number"==typeof e.length){r&&(e=r);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n=/*#__PURE__*/function(){function t(){this.nodeCount=0,this.minNode=null}var n=t.prototype;return n.insert=function(t,e){var n={key:t,value:e,degree:0,mark:!1,parent:null,child:null,left:null,right:null};n.left=n,n.right=n,this.minNode=this.mergeLists(this.minNode,n),this.nodeCount++},n.extractMin=function(){var t=this.minNode;if(!t)return null;if(t.child){var e=t.child;do{e.parent=null,e=e.right}while(e!==t.child);this.minNode=this.mergeLists(this.minNode,t.child)}return this.removeFromList(t),t===t.right?this.minNode=null:(this.minNode=t.right,this.consolidate()),this.nodeCount--,t.value},n.size=function(){return this.nodeCount},n.consolidate=function(){var t=Math.floor(Math.log2(this.nodeCount))+1,n=new Array(t).fill(null),r=[],i=this.minNode;do{r.push(i),i=i.right}while(i!==this.minNode);for(var o=0,a=r;o<a.length;o++){for(var s=a[o],h=s.degree;n[h];){var d=n[h];if(s.key>d.key){var c=s;s=d,d=c}this.link(d,s),n[h]=null,h++}n[h]=s}this.minNode=null;for(var u,l=e(n);!(u=l()).done;){var f=u.value;f&&(this.minNode=this.mergeLists(this.minNode,f))}},n.link=function(t,e){this.removeFromList(t),t.left=t.right=t,e.child=this.mergeLists(e.child,t),t.parent=e,e.degree++,t.mark=!1},n.mergeLists=function(t,e){if(!t)return e;if(!e)return t;var n=t.right,r=e.right;return t.right=r,r.left=t,e.right=n,n.left=e,t.key<e.key?t:e},n.removeFromList=function(t){t.left.right=t.right,t.right.left=t.left},t}(),r=function(t,e){var n=function(t){return t*Math.PI/180},r=n(t[1]),i=n(t[0]),o=n(e[1]),a=o-r,s=n(e[0])-i,h=Math.sin(a/2)*Math.sin(a/2)+Math.cos(r)*Math.cos(o)*Math.sin(s/2)*Math.sin(s/2);return 2*Math.atan2(Math.sqrt(h),Math.sqrt(1-h))*6371e3/1e3};exports.TerraRoute=/*#__PURE__*/function(){function t(t){this.network=void 0,this.distanceMeasurement=void 0,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map,this.distanceMeasurement=t||r}var i=t.prototype;return i.coordinateIndex=function(t){var e=t[0],n=t[1];this.coordMap.has(e)||this.coordMap.set(e,new Map);var r=this.coordMap.get(e);if(r.has(n))return r.get(n);var i=this.coords.length;return this.coords.push(t),r.set(n,i),i},i.buildRouteGraph=function(t){this.network=t,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map;for(var n,r=e(this.network.features);!(n=r()).done;)for(var i=n.value.geometry.coordinates,o=0;o<i.length-1;o++){var a=this.coordinateIndex(i[o]),s=this.coordinateIndex(i[o+1]),h=this.distanceMeasurement(i[o],i[o+1]);this.adjacencyList.has(a)||this.adjacencyList.set(a,[]),this.adjacencyList.has(s)||this.adjacencyList.set(s,[]),this.adjacencyList.get(a).push({node:s,distance:h}),this.adjacencyList.get(s).push({node:a,distance:h})}},i.getRoute=function(t,r){if(!this.network)throw new Error("Network not built. Please call buildRouteGraph(network) first.");var i=this.coordinateIndex(t.geometry.coordinates),o=this.coordinateIndex(r.geometry.coordinates);if(i===o)return null;var a=new n,s=new n;a.insert(0,i),s.insert(0,o);for(var h=new Map,d=new Map,c=new Map([[i,0]]),u=new Map([[o,0]]),l=new Set,f=new Set,v=null;a.size()>0&&s.size()>0;){var g=a.extractMin();if(l.add(g),f.has(g)){v=g;break}for(var m,p=e(this.adjacencyList.get(g)||[]);!(m=p()).done;){var y,M,w=m.value,L=(null!=(y=c.get(g))?y:Infinity)+w.distance;if(L<(null!=(M=c.get(w.node))?M:Infinity)){h.set(w.node,g),c.set(w.node,L);var k=L+this.distanceMeasurement(this.coords[w.node],this.coords[o]);a.insert(k,w.node)}}var b=s.extractMin();if(f.add(b),l.has(b)){v=b;break}for(var I,N=e(this.adjacencyList.get(b)||[]);!(I=N()).done;){var j,x,S=I.value,A=(null!=(j=u.get(b))?j:Infinity)+S.distance;if(A<(null!=(x=u.get(S.node))?x:Infinity)){d.set(S.node,b),u.set(S.node,A);var C=A+this.distanceMeasurement(this.coords[S.node],this.coords[i]);s.insert(C,S.node)}}}if(null===v)return null;for(var R=[],q=v;void 0!==q;)R.unshift(this.coords[q]),q=h.get(q);var F=[];for(q=d.get(v);void 0!==q;)F.push(this.coords[q]),q=d.get(q);return{type:"Feature",geometry:{type:"LineString",coordinates:[].concat(R,F)},properties:{}}},t}(),exports.createCheapRuler=function(t){var e=1/298.257223563,n=e*(2-e),r=Math.PI/180,i=Math.cos(t*r),o=1/(1-n*(1-i*i)),a=Math.sqrt(o),s=6378.137*r,h=s*a*i,d=s*a*o*(1-n);return function(t,e){for(var n=t[0]-e[0];n<-180;)n+=360;for(;n>180;)n-=360;var r=n*h,i=(t[1]-e[1])*d;return Math.sqrt(r*r+i*i)}},exports.haversineDistance=r;
1
+ function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function e(e,r){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,r){if(e){if("string"==typeof e)return t(e,r);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?t(e,r):void 0}}(e))||r&&e&&"number"==typeof e.length){n&&(e=n);var a=0;return function(){return a>=e.length?{done:!0}:{done:!1,value:e[a++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r=function(t,e){var r=function(t){return t*Math.PI/180},n=r(t[1]),a=r(t[0]),i=r(e[1]),o=i-n,s=r(e[0])-a,h=Math.sin(o/2)*Math.sin(o/2)+Math.cos(n)*Math.cos(i)*Math.sin(s/2)*Math.sin(s/2);return 2*Math.atan2(Math.sqrt(h),Math.sqrt(1-h))*6371e3/1e3},n=/*#__PURE__*/function(){function t(){this.heap=[],this.insertCounter=0}var e=t.prototype;return e.insert=function(t,e){var r={key:t,value:e,index:this.insertCounter++},n=this.heap.length;for(this.heap.push(r);n>0;){var a=n-1>>>1,i=this.heap[a];if(t>i.key||t===i.key&&r.index>i.index)break;this.heap[n]=i,n=a}this.heap[n]=r},e.extractMin=function(){var t=this.heap,e=t.length;if(0===e)return null;var r=t[0],n=t.pop();return e>1&&(t[0]=n,this.bubbleDown(0)),r.value},e.size=function(){return this.heap.length},e.bubbleDown=function(t){for(var e=this.heap,r=e.length,n=e[t],a=n.key,i=n.index;;){var o=1+(t<<1);if(o>=r)break;var s=o,h=e[o],u=o+1;if(u<r){var c=e[u];(c.key<h.key||c.key===h.key&&c.index<h.index)&&(s=u,h=c)}if(!(h.key<a||h.key===a&&h.index<i))break;e[t]=h,t=s}e[t]=n},t}();exports.TerraRoute=/*#__PURE__*/function(){function t(t){var e,a;this.network=null,this.distanceMeasurement=void 0,this.heapConstructor=void 0,this.coordinateIndexMap=new Map,this.coordinates=[],this.adjacencyList=[],this.distanceMeasurement=null!=(e=null==t?void 0:t.distanceMeasurement)?e:r,this.heapConstructor=null!=(a=null==t?void 0:t.heap)?a:n}var a=t.prototype;return a.buildRouteGraph=function(t){this.network=t,this.coordinateIndexMap=new Map,this.coordinates=[],this.adjacencyList=[];for(var r,n=this.coordinateIndexMap,a=this.coordinates,i=this.adjacencyList,o=this.distanceMeasurement,s=e(t.features);!(r=s()).done;)for(var h=r.value.geometry.coordinates,u=0;u<h.length-1;u++){var c=h[u],d=c[0],l=c[1],f=h[u+1],v=f[0],p=f[1],y=n.get(d);y||(y=new Map,n.set(d,y));var M=y.get(l);void 0===M&&(M=a.length,a.push(h[u]),y.set(l,M),i[M]=[]);var g=n.get(v);g||(g=new Map,n.set(v,g));var b=g.get(p);void 0===b&&(b=a.length,a.push(h[u+1]),g.set(p,b),i[b]=[]);var x=o(h[u],h[u+1]);i[M].push({node:b,distance:x}),i[b].push({node:M,distance:x})}},a.getRoute=function(t,r){if(!this.network)throw new Error("Network not built. Please call buildRouteGraph(network) first.");var n=this.getOrCreateIndex(t.geometry.coordinates),a=this.getOrCreateIndex(r.geometry.coordinates);if(n===a)return null;var i=new this.heapConstructor;i.insert(0,n);var o=this.coordinates.length,s=new Array(o).fill(Infinity),h=new Array(o).fill(-1),u=new Array(o).fill(!1);for(s[n]=0;i.size()>0;){var c=i.extractMin();if(!u[c]){if(c===a)break;u[c]=!0;for(var d,l=e(this.adjacencyList[c]||[]);!(d=l()).done;){var f=d.value,v=s[c]+f.distance;if(v<s[f.node]){s[f.node]=v,h[f.node]=c;var p=this.distanceMeasurement(this.coordinates[f.node],this.coordinates[a]);i.insert(v+p,f.node)}}}}if(h[a]<0)return null;for(var y=[],M=a;M!==n;)y.unshift(this.coordinates[M]),M=h[M];return y.unshift(this.coordinates[n]),{type:"Feature",geometry:{type:"LineString",coordinates:y},properties:{}}},a.getOrCreateIndex=function(t){var e=t[0],r=t[1],n=this.coordinateIndexMap.get(e);n||(n=new Map,this.coordinateIndexMap.set(e,n));var a=n.get(r);return void 0===a&&(a=this.coordinates.length,this.coordinates.push(t),n.set(r,a),this.adjacencyList[a]=[]),a},t}(),exports.createCheapRuler=function(t){var e=1/298.257223563,r=e*(2-e),n=Math.PI/180,a=Math.cos(t*n),i=1/(1-r*(1-a*a)),o=Math.sqrt(i),s=6378.137*n,h=s*o*a,u=s*o*i*(1-r);return function(t,e){for(var r=t[0]-e[0];r<-180;)r+=360;for(;r>180;)r-=360;var n=r*h,a=(t[1]-e[1])*u;return Math.sqrt(n*n+a*a)}},exports.haversineDistance=r;
2
2
  //# sourceMappingURL=terra-route.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"terra-route.cjs","sources":["../src/fibonacci-heap.ts","../src/distance/haversine.ts","../src/terra-route.ts","../src/distance/cheap-ruler.ts"],"sourcesContent":["type FibNode = {\n key: number;\n value: number;\n degree: number;\n mark: boolean;\n parent: FibNode | null;\n child: FibNode | null;\n left: FibNode;\n right: FibNode;\n};\n\nexport class FibonacciHeap {\n private nodeCount = 0;\n private minNode: FibNode | null = null;\n\n insert(key: number, value: number): void {\n const node: FibNode = {\n key,\n value,\n degree: 0,\n mark: false,\n parent: null,\n child: null,\n left: null as any,\n right: null as any,\n };\n node.left = node;\n node.right = node;\n\n this.minNode = this.mergeLists(this.minNode, node);\n this.nodeCount++;\n }\n\n extractMin(): number | null {\n const z = this.minNode;\n if (!z) return null;\n\n // Add children to root list\n if (z.child) {\n let child = z.child;\n do {\n child.parent = null;\n child = child.right!;\n } while (child !== z.child);\n this.minNode = this.mergeLists(this.minNode, z.child);\n }\n\n this.removeFromList(z);\n\n if (z === z.right) {\n this.minNode = null;\n } else {\n this.minNode = z.right;\n this.consolidate();\n }\n\n this.nodeCount--;\n return z.value;\n }\n\n size(): number {\n return this.nodeCount;\n }\n\n // ========== Internal Methods ==========\n\n private consolidate(): void {\n const maxDegree = Math.floor(Math.log2(this.nodeCount)) + 1;\n const A = new Array<FibNode | null>(maxDegree).fill(null);\n\n const rootList: FibNode[] = [];\n let curr = this.minNode!;\n do {\n rootList.push(curr);\n curr = curr.right!;\n } while (curr !== this.minNode);\n\n for (const w of rootList) {\n let x = w;\n let d = x.degree;\n while (A[d]) {\n let y = A[d]!;\n if (x.key > y.key) {\n const temp = x;\n x = y;\n y = temp;\n }\n this.link(y, x);\n A[d] = null;\n d++;\n }\n A[d] = x;\n }\n\n this.minNode = null;\n for (const node of A) {\n if (node) {\n this.minNode = this.mergeLists(this.minNode, node);\n }\n }\n }\n\n private link(y: FibNode, x: FibNode): void {\n this.removeFromList(y);\n y.left = y.right = y;\n x.child = this.mergeLists(x.child, y);\n y.parent = x;\n x.degree++;\n y.mark = false;\n }\n\n private mergeLists(a: FibNode | null, b: FibNode | null): FibNode {\n if (!a) return b!;\n if (!b) return a;\n\n const aRight = a.right!;\n const bRight = b.right!;\n\n a.right = bRight;\n bRight.left = a;\n b.right = aRight;\n aRight.left = b;\n\n return a.key < b.key ? a : b;\n }\n\n private removeFromList(node: FibNode): void {\n node.left.right = node.right;\n node.right.left = node.left;\n }\n}\n","import { Position } from \"geojson\";\n\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { FibonacciHeap } from \"./fibonacci-heap\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\n\n/**\n * TerraRoute is a routing utility for finding the shortest path\n * between two geographic points over a given GeoJSON LineString network.\n *\n * The class builds an internal graph structure based on the provided network,\n * then applies A* algorithm to compute the shortest route.\n */\nclass TerraRoute {\n private network: FeatureCollection<LineString> | undefined;\n private distanceMeasurement: (positionA: Position, positionB: Position) => number;\n private adjacencyList: Map<number, Array<{ node: number; distance: number }>> = new Map();\n private coords: Position[] = []\n private coordMap: Map<number, Map<number, number>> = new Map();\n\n /**\n * Creates a new instance of TerraRoute.\n * \n * @param distanceMeasurement - Optional custom distance measurement function (defaults to haversine distance).\n */\n constructor(\n distanceMeasurement?: (positionA: Position, positionB: Position) => number\n ) {\n this.distanceMeasurement = distanceMeasurement ? distanceMeasurement : haversineDistance;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n private coordinateIndex(coord: Position): number {\n const [lng, lat] = coord;\n if (!this.coordMap.has(lng)) this.coordMap.set(lng, new Map());\n\n const latMap = this.coordMap.get(lng)!;\n if (latMap.has(lat)) {\n return latMap.get(lat)!;\n }\n\n const index = this.coords.length;\n this.coords.push(coord);\n latMap.set(lat, index);\n\n return index;\n }\n\n /**\n * Builds the internal graph representation (adjacency list) from the input network.\n * Each LineString segment is translated into bidirectional graph edges with associated distances.\n * Assumes that the network is a connected graph of LineStrings with shared coordinates. Calling this \n * method with a new network overwrite any existing network and reset all internal data structures.\n * \n * @param network - A GeoJSON FeatureCollection of LineStrings representing the road network.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n this.adjacencyList = new Map();\n this.coords = [];\n this.coordMap = new Map();\n\n for (const feature of this.network.features) {\n const coords = feature.geometry.coordinates;\n for (let i = 0; i < coords.length - 1; i++) {\n const aIndex = this.coordinateIndex(coords[i]);\n const bIndex = this.coordinateIndex(coords[i + 1]);\n const distance = this.distanceMeasurement(coords[i], coords[i + 1]);\n\n if (!this.adjacencyList.has(aIndex)) this.adjacencyList.set(aIndex, []);\n if (!this.adjacencyList.has(bIndex)) this.adjacencyList.set(bIndex, []);\n\n this.adjacencyList.get(aIndex)!.push({ node: bIndex, distance });\n this.adjacencyList.get(bIndex)!.push({ node: aIndex, distance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using bidirectional A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildRouteGraph(network) first.\");\n }\n\n const startIndex = this.coordinateIndex(start.geometry.coordinates);\n const endIndex = this.coordinateIndex(end.geometry.coordinates);\n\n if (startIndex === endIndex) {\n return null;\n }\n\n const openSetForward = new FibonacciHeap();\n const openSetBackward = new FibonacciHeap();\n openSetForward.insert(0, startIndex);\n openSetBackward.insert(0, endIndex);\n\n const cameFromForward = new Map<number, number>();\n const cameFromBackward = new Map<number, number>();\n const gScoreForward = new Map<number, number>([[startIndex, 0]]);\n const gScoreBackward = new Map<number, number>([[endIndex, 0]]);\n\n const visitedForward = new Set<number>();\n const visitedBackward = new Set<number>();\n\n let meetingNode: number | null = null;\n\n while (openSetForward.size() > 0 && openSetBackward.size() > 0) {\n const currentForward = openSetForward.extractMin()!;\n visitedForward.add(currentForward);\n\n if (visitedBackward.has(currentForward)) {\n meetingNode = currentForward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentForward) || []) {\n const tentativeG = (gScoreForward.get(currentForward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreForward.get(neighbor.node) ?? Infinity)) {\n cameFromForward.set(neighbor.node, currentForward);\n gScoreForward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[endIndex]);\n openSetForward.insert(fScore, neighbor.node);\n }\n }\n\n const currentBackward = openSetBackward.extractMin()!;\n visitedBackward.add(currentBackward);\n\n if (visitedForward.has(currentBackward)) {\n meetingNode = currentBackward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentBackward) || []) {\n const tentativeG = (gScoreBackward.get(currentBackward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreBackward.get(neighbor.node) ?? Infinity)) {\n cameFromBackward.set(neighbor.node, currentBackward);\n gScoreBackward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[startIndex]);\n openSetBackward.insert(fScore, neighbor.node);\n }\n }\n }\n\n if (meetingNode === null) {\n return null;\n }\n\n // Reconstruct forward path\n const pathForward: Position[] = [];\n let node = meetingNode;\n while (node !== undefined) {\n pathForward.unshift(this.coords[node]);\n node = cameFromForward.get(node)!;\n }\n\n // Reconstruct backward path (omit meeting node to avoid duplication)\n const pathBackward: Position[] = [];\n node = cameFromBackward.get(meetingNode)!;\n while (node !== undefined) {\n pathBackward.push(this.coords[node]);\n node = cameFromBackward.get(node)!;\n }\n\n const fullPath = [...pathForward, ...pathBackward];\n\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: fullPath },\n properties: {},\n };\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}"],"names":["FibonacciHeap","this","nodeCount","minNode","_proto","prototype","insert","key","value","node","degree","mark","parent","child","left","right","mergeLists","extractMin","z","removeFromList","consolidate","size","maxDegree","Math","floor","log2","A","Array","fill","rootList","curr","push","_i","_rootList","length","x","d","y","temp","link","_step","_iterator","_createForOfIteratorHelperLoose","done","a","b","aRight","bRight","haversineDistance","pointOne","pointTwo","toRadians","latOrLng","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","sin","cos","atan2","sqrt","TerraRoute","distanceMeasurement","network","adjacencyList","Map","coords","coordMap","coordinateIndex","coord","lng","lat","has","set","latMap","get","index","buildRouteGraph","features","geometry","coordinates","i","aIndex","bIndex","distance","getRoute","start","end","Error","startIndex","endIndex","openSetForward","openSetBackward","cameFromForward","cameFromBackward","gScoreForward","gScoreBackward","visitedForward","Set","visitedBackward","meetingNode","currentForward","add","_iterator2","_step2","_gScoreForward$get","_gScoreForward$get2","neighbor","tentativeG","Infinity","fScore","currentBackward","_step3","_iterator3","_gScoreBackward$get","_gScoreBackward$get2","pathForward","undefined","unshift","pathBackward","type","concat","properties","FE","E2","RAD","cosLat","w2","w","m","kx","ky","deltaLng","dx","dy"],"mappings":"oyBAWA,IAAaA,eAAa,WAAA,SAAAA,IAAAC,KACdC,UAAY,EACZC,KAAAA,QAA0B,IAAI,CAAA,IAAAC,EAAAJ,EAAAK,iBAAAD,EAEtCE,OAAA,SAAOC,EAAaC,GAChB,IAAMC,EAAgB,CAClBF,IAAAA,EACAC,MAAAA,EACAE,OAAQ,EACRC,MAAM,EACNC,OAAQ,KACRC,MAAO,KACPC,KAAM,KACNC,MAAO,MAEXN,EAAKK,KAAOL,EACZA,EAAKM,MAAQN,EAEbR,KAAKE,QAAUF,KAAKe,WAAWf,KAAKE,QAASM,GAC7CR,KAAKC,WACT,EAACE,EAEDa,WAAA,WACI,IAAMC,EAAIjB,KAAKE,QACf,IAAKe,EAAG,OAAW,KAGnB,GAAIA,EAAEL,MAAO,CACT,IAAIA,EAAQK,EAAEL,MACd,GACIA,EAAMD,OAAS,KACfC,EAAQA,EAA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MsD,GACxBE,EAAK,GAAK,EAAIH,GAAM,EAAIE,EAASA,IACjCE,EAAI3G,KAAKuC,KAAKmE,GAEdE,EATK,SASDJ,EACJK,EAAKD,EAAID,EAAIF,EACbK,EAAKF,EAAID,EAAID,GAAM,EAAIH,GAE7B,OAAgB,SAASlF,EAAaC,GAGlC,IAFA,IAAIyF,EAAW1F,EAAE,GAAKC,EAAE,GAEjByF,GAAY,KAAKA,GAAY,IACpC,KAAOA,EAAW,KAAKA,GAAY,IAEnC,IAAMC,EAAKD,EAAWF,EAChBI,GAAM5F,EAAE,GAAKC,EAAE,IAAMwF,EAE3B,OAAO9G,KAAKuC,KAAKyE,EAAKA,EAAKC,EAAKA,EACpC,CACJ"}
1
+ {"version":3,"file":"terra-route.cjs","sources":["../src/distance/haversine.ts","../src/heap/min-heap.ts","../src/terra-route.ts","../src/distance/cheap-ruler.ts"],"sourcesContent":["import { Position } from \"geojson\";\n\n/** Distance measured in kilometers */\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}\n","import { Heap } from \"./heap\";\n\nexport class MinHeap implements Heap {\n private heap: Array<{ key: number; value: number; index: number }> = [];\n private insertCounter = 0;\n\n insert(key: number, value: number): void {\n const node = { key, value, index: this.insertCounter++ };\n let currentIndex = this.heap.length;\n this.heap.push(node);\n\n while (currentIndex > 0) {\n const parentIndex = (currentIndex - 1) >>> 1;\n const parent = this.heap[parentIndex];\n\n if (\n key > parent.key ||\n (key === parent.key && node.index > parent.index)\n ) {\n break;\n }\n\n this.heap[currentIndex] = parent;\n currentIndex = parentIndex;\n }\n\n this.heap[currentIndex] = node;\n }\n\n extractMin(): number | null {\n const heap = this.heap;\n const length = heap.length;\n\n if (length === 0) {\n return null;\n }\n\n const minNode = heap[0];\n const endNode = heap.pop()!;\n\n if (length > 1) {\n heap[0] = endNode;\n this.bubbleDown(0);\n }\n\n return minNode.value;\n }\n\n size(): number {\n return this.heap.length;\n }\n\n private bubbleDown(index: number): void {\n const heap = this.heap;\n const length = heap.length;\n const node = heap[index];\n const nodeKey = node.key;\n const nodeIndex = node.index;\n\n while (true) {\n const leftChildIndex = (index << 1) + 1;\n if (leftChildIndex >= length) {\n break;\n }\n\n let smallestIndex = leftChildIndex;\n let smallest = heap[leftChildIndex];\n\n const rightChildIndex = leftChildIndex + 1;\n if (rightChildIndex < length) {\n const right = heap[rightChildIndex];\n if (\n right.key < smallest.key ||\n (right.key === smallest.key && right.index < smallest.index)\n ) {\n smallestIndex = rightChildIndex;\n smallest = right;\n }\n }\n\n if (\n smallest.key < nodeKey ||\n (smallest.key === nodeKey && smallest.index < nodeIndex)\n ) {\n heap[index] = smallest;\n index = smallestIndex;\n } else {\n break;\n }\n }\n\n heap[index] = node;\n }\n}\n","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\nimport { MinHeap } from \"./heap/min-heap\";\nimport { HeapConstructor } from \"./heap/heap\";\n\ninterface Router {\n buildRouteGraph(network: FeatureCollection<LineString>): void;\n getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null;\n}\n\nclass TerraRoute implements Router {\n private network: FeatureCollection<LineString> | null = null;\n private distanceMeasurement: (a: Position, b: Position) => number;\n private heapConstructor: HeapConstructor;\n\n // Map from longitude → (map from latitude → index)\n private coordinateIndexMap: Map<number, Map<number, number>> = new Map();\n private coordinates: Position[] = [];\n private adjacencyList: Array<Array<{ node: number; distance: number }>> = [];\n\n constructor(options?: {\n distanceMeasurement?: (a: Position, b: Position) => number;\n heap?: HeapConstructor;\n }) {\n this.distanceMeasurement = options?.distanceMeasurement ?? haversineDistance;\n this.heapConstructor = options?.heap ?? MinHeap;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n\n // Reset everything\n this.coordinateIndexMap = new Map();\n this.coordinates = [];\n this.adjacencyList = [];\n\n // Hoist to locals for speed\n const coordIndexMapLocal = this.coordinateIndexMap;\n const coordsLocal = this.coordinates;\n const adjListLocal = this.adjacencyList;\n const measureDistance = this.distanceMeasurement;\n\n for (const feature of network.features) {\n const lineCoords = feature.geometry.coordinates;\n\n for (let i = 0; i < lineCoords.length - 1; i++) {\n const [lngA, latA] = lineCoords[i];\n const [lngB, latB] = lineCoords[i + 1];\n\n // get or assign index for A \n let latMapA = coordIndexMapLocal.get(lngA);\n if (!latMapA) {\n latMapA = new Map<number, number>();\n coordIndexMapLocal.set(lngA, latMapA);\n }\n let indexA = latMapA.get(latA);\n if (indexA === undefined) {\n indexA = coordsLocal.length;\n coordsLocal.push(lineCoords[i]);\n latMapA.set(latA, indexA);\n adjListLocal[indexA] = [];\n }\n\n // get or assign index for B \n let latMapB = coordIndexMapLocal.get(lngB);\n if (!latMapB) {\n latMapB = new Map<number, number>();\n coordIndexMapLocal.set(lngB, latMapB);\n }\n let indexB = latMapB.get(latB);\n if (indexB === undefined) {\n indexB = coordsLocal.length;\n coordsLocal.push(lineCoords[i + 1]);\n latMapB.set(latB, indexB);\n adjListLocal[indexB] = [];\n }\n\n // record the bidirectional edge \n const segmentDistance = measureDistance(lineCoords[i], lineCoords[i + 1]);\n adjListLocal[indexA].push({ node: indexB, distance: segmentDistance });\n adjListLocal[indexB].push({ node: indexA, distance: segmentDistance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using the A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(\n start: Feature<Point>,\n end: Feature<Point>\n ): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildRouteGraph(network) first.\");\n }\n\n // ensure start/end are in the index maps\n const startIndex = this.getOrCreateIndex(start.geometry.coordinates);\n const endIndex = this.getOrCreateIndex(end.geometry.coordinates);\n\n if (startIndex === endIndex) {\n return null;\n }\n\n const openSet = new this.heapConstructor();\n openSet.insert(0, startIndex);\n\n const nodeCount = this.coordinates.length;\n const gScore = new Array<number>(nodeCount).fill(Infinity);\n const cameFrom = new Array<number>(nodeCount).fill(-1);\n const visited = new Array<boolean>(nodeCount).fill(false);\n\n gScore[startIndex] = 0;\n\n while (openSet.size() > 0) {\n const current = openSet.extractMin()!;\n if (visited[current]) {\n continue;\n }\n if (current === endIndex) {\n break;\n }\n visited[current] = true;\n\n for (const neighbor of this.adjacencyList[current] || []) {\n const tentativeG = gScore[current] + neighbor.distance;\n if (tentativeG < gScore[neighbor.node]) {\n gScore[neighbor.node] = tentativeG;\n cameFrom[neighbor.node] = current;\n const heuristic = this.distanceMeasurement(\n this.coordinates[neighbor.node],\n this.coordinates[endIndex]\n );\n openSet.insert(tentativeG + heuristic, neighbor.node);\n }\n }\n }\n\n if (cameFrom[endIndex] < 0) {\n return null;\n }\n\n // Reconstruct path\n const path: Position[] = [];\n let current = endIndex;\n while (current !== startIndex) {\n path.unshift(this.coordinates[current]);\n current = cameFrom[current];\n }\n path.unshift(this.coordinates[startIndex]);\n\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: path },\n properties: {},\n };\n }\n\n /**\n * Helper to index start/end in getRoute.\n */\n private getOrCreateIndex(coord: Position): number {\n const [lng, lat] = coord;\n let latMap = this.coordinateIndexMap.get(lng);\n if (!latMap) {\n latMap = new Map<number, number>();\n this.coordinateIndexMap.set(lng, latMap);\n }\n let index = latMap.get(lat);\n if (index === undefined) {\n index = this.coordinates.length;\n this.coordinates.push(coord);\n latMap.set(lat, index);\n // ensure adjacencyList covers this new node\n this.adjacencyList[index] = [];\n }\n return index;\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}"],"names":["haversineDistance","pointOne","pointTwo","toRadians","latOrLng","Math","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","a","sin","cos","atan2","sqrt","MinHeap","heap","this","insertCounter","_proto","prototype","insert","key","value","node","index","currentIndex","length","push","parentIndex","parent","extractMin","minNode","endNode","pop","bubbleDown","size","nodeKey","nodeIndex","leftChildIndex","smallestIndex","smallest","rightChildIndex","right","TerraRoute","options","_options$distanceMeas","_options$heap","network","distanceMeasurement","heapConstructor","coordinateIndexMap","Map","coordinates","adjacencyList","buildRouteGraph","_step","coordIndexMapLocal","coordsLocal","adjListLocal","measureDistance","_iterator","_createForOfIteratorHelperLoose","features","done","lineCoords","geometry","i","_lineCoords$i","lngA","latA","_lineCoords","lngB","latB","latMapA","get","set","indexA","undefined","latMapB","indexB","segmentDistance","distance","getRoute","start","end","Error","startIndex","getOrCreateIndex","endIndex","openSet","nodeCount","gScore","Array","fill","Infinity","cameFrom","visited","current","_iterator2","_step2","neighbor","tentativeG","heuristic","path","unshift","type","properties","coord","lng","lat","latMap","FE","E2","RAD","cosLat","w2","w","m","kx","ky","b","deltaLng","dx","dy"],"mappings":"oyBAGa,IAAAA,EAAoB,SAACC,EAAoBC,GAClD,I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KAAM,aAAcrD,YAAamD,GAC7CG,WAAY,GAEpB,EAACxF,EAKOqE,iBAAA,SAAiBoB,GACrB,IAAOC,EAAYD,EAAK,GAAZE,EAAOF,EAAK,GACpBG,EAAS9F,KAAKkC,mBAAmBwB,IAAIkC,GACpCE,IACDA,EAAS,IAAI3D,IACbnC,KAAKkC,mBAAmByB,IAAIiC,EAAKE,IAErC,IAAItF,EAAQsF,EAAOpC,IAAImC,GAQvB,YAPchC,IAAVrD,IACAA,EAAQR,KAAKoC,YAAY1B,OACzBV,KAAKoC,YAAYzB,KAAKgF,GACtBG,EAAOnC,IAAIkC,EAAKrF,GAEhBR,KAAKqC,cAAc7B,GAAS,IAEzBA,CACX,EAACmB,CAAA,CApLW,4BCqBV,SAA2BkE,GAC7B,IACME,EAAK,EAAI,cACTC,EAAKD,GAAM,EAAIA,GACfE,EAAM/G,KAAKC,GAAK,IAEhB+G,EAAShH,KAAKS,IAAIkG,EAAMI,GACxBE,EAAK,GAAK,EAAIH,GAAM,EAAIE,EAASA,IACjCE,EAAIlH,KAAKW,KAAKsG,GAEdE,EATK,SASDJ,EACJK,EAAKD,EAAID,EAAIF,EACbK,EAAKF,EAAID,EAAID,GAAM,EAAIH,GAE7B,OAAgB,SAASvG,EAAa+G,GAGlC,IAFA,IAAIC,EAAWhH,EAAE,GAAK+G,EAAE,GAEjBC,GAAY,KAAKA,GAAY,IACpC,KAAOA,EAAW,KAAKA,GAAY,IAEnC,IAAMC,EAAKD,EAAWH,EAChBK,GAAMlH,EAAE,GAAK+G,EAAE,IAAMD,EAE3B,OAAOrH,KAAKW,KAAK6G,EAAKA,EAAKC,EAAKA,EACpC,CACJ"}
@@ -1,25 +1,22 @@
1
1
  import { FeatureCollection, LineString, Point, Feature, Position } from "geojson";
2
2
  import { haversineDistance } from "./distance/haversine";
3
3
  import { createCheapRuler } from "./distance/cheap-ruler";
4
- /**
5
- * TerraRoute is a routing utility for finding the shortest path
6
- * between two geographic points over a given GeoJSON LineString network.
7
- *
8
- * The class builds an internal graph structure based on the provided network,
9
- * then applies A* algorithm to compute the shortest route.
10
- */
11
- declare class TerraRoute {
4
+ import { HeapConstructor } from "./heap/heap";
5
+ interface Router {
6
+ buildRouteGraph(network: FeatureCollection<LineString>): void;
7
+ getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null;
8
+ }
9
+ declare class TerraRoute implements Router {
12
10
  private network;
13
11
  private distanceMeasurement;
12
+ private heapConstructor;
13
+ private coordinateIndexMap;
14
+ private coordinates;
14
15
  private adjacencyList;
15
- private coords;
16
- private coordMap;
17
- /**
18
- * Creates a new instance of TerraRoute.
19
- *
20
- * @param distanceMeasurement - Optional custom distance measurement function (defaults to haversine distance).
21
- */
22
- constructor(distanceMeasurement?: (positionA: Position, positionB: Position) => number);
16
+ constructor(options?: {
17
+ distanceMeasurement?: (a: Position, b: Position) => number;
18
+ heap?: HeapConstructor;
19
+ });
23
20
  /**
24
21
  * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.
25
22
  * Otherwise, assigns a new index and stores the coordinate.
@@ -27,18 +24,9 @@ declare class TerraRoute {
27
24
  * @param coord - A GeoJSON Position array representing [longitude, latitude].
28
25
  * @returns A unique numeric index for the coordinate.
29
26
  */
30
- private coordinateIndex;
31
- /**
32
- * Builds the internal graph representation (adjacency list) from the input network.
33
- * Each LineString segment is translated into bidirectional graph edges with associated distances.
34
- * Assumes that the network is a connected graph of LineStrings with shared coordinates. Calling this
35
- * method with a new network overwrite any existing network and reset all internal data structures.
36
- *
37
- * @param network - A GeoJSON FeatureCollection of LineStrings representing the road network.
38
- */
39
27
  buildRouteGraph(network: FeatureCollection<LineString>): void;
40
28
  /**
41
- * Computes the shortest route between two points in the network using bidirectional A* algorithm.
29
+ * Computes the shortest route between two points in the network using the A* algorithm.
42
30
  *
43
31
  * @param start - A GeoJSON Point Feature representing the start location.
44
32
  * @param end - A GeoJSON Point Feature representing the end location.
@@ -47,5 +35,9 @@ declare class TerraRoute {
47
35
  * @throws Error if the network has not been built yet with buildRouteGraph(network).
48
36
  */
49
37
  getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null;
38
+ /**
39
+ * Helper to index start/end in getRoute.
40
+ */
41
+ private getOrCreateIndex;
50
42
  }
51
43
  export { TerraRoute, createCheapRuler, haversineDistance };
@@ -1,2 +1,2 @@
1
- class t{constructor(){this.nodeCount=0,this.minNode=null}insert(t,e){const n={key:t,value:e,degree:0,mark:!1,parent:null,child:null,left:null,right:null};n.left=n,n.right=n,this.minNode=this.mergeLists(this.minNode,n),this.nodeCount++}extractMin(){const t=this.minNode;if(!t)return null;if(t.child){let e=t.child;do{e.parent=null,e=e.right}while(e!==t.child);this.minNode=this.mergeLists(this.minNode,t.child)}return this.removeFromList(t),t===t.right?this.minNode=null:(this.minNode=t.right,this.consolidate()),this.nodeCount--,t.value}size(){return this.nodeCount}consolidate(){const t=Math.floor(Math.log2(this.nodeCount))+1,e=new Array(t).fill(null),n=[];let s=this.minNode;do{n.push(s),s=s.right}while(s!==this.minNode);for(const t of n){let n=t,s=n.degree;for(;e[s];){let t=e[s];if(n.key>t.key){const e=n;n=t,t=e}this.link(t,n),e[s]=null,s++}e[s]=n}this.minNode=null;for(const t of e)t&&(this.minNode=this.mergeLists(this.minNode,t))}link(t,e){this.removeFromList(t),t.left=t.right=t,e.child=this.mergeLists(e.child,t),t.parent=e,e.degree++,t.mark=!1}mergeLists(t,e){if(!t)return e;if(!e)return t;const n=t.right,s=e.right;return t.right=s,s.left=t,e.right=n,n.left=e,t.key<e.key?t:e}removeFromList(t){t.left.right=t.right,t.right.left=t.left}}const e=(t,e)=>{const n=t=>t*Math.PI/180,s=n(t[1]),i=n(t[0]),o=n(e[1]),r=o-s,h=n(e[0])-i,a=Math.sin(r/2)*Math.sin(r/2)+Math.cos(s)*Math.cos(o)*Math.sin(h/2)*Math.sin(h/2);return 2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))*6371e3/1e3};function n(t){const e=1/298.257223563,n=e*(2-e),s=Math.PI/180,i=Math.cos(t*s),o=1/(1-n*(1-i*i)),r=Math.sqrt(o),h=6378.137*s,a=h*r*i,c=h*r*o*(1-n);return function(t,e){let n=t[0]-e[0];for(;n<-180;)n+=360;for(;n>180;)n-=360;const s=n*a,i=(t[1]-e[1])*c;return Math.sqrt(s*s+i*i)}}class s{constructor(t){this.network=void 0,this.distanceMeasurement=void 0,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map,this.distanceMeasurement=t||e}coordinateIndex(t){const[e,n]=t;this.coordMap.has(e)||this.coordMap.set(e,new Map);const s=this.coordMap.get(e);if(s.has(n))return s.get(n);const i=this.coords.length;return this.coords.push(t),s.set(n,i),i}buildRouteGraph(t){this.network=t,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map;for(const t of this.network.features){const e=t.geometry.coordinates;for(let t=0;t<e.length-1;t++){const n=this.coordinateIndex(e[t]),s=this.coordinateIndex(e[t+1]),i=this.distanceMeasurement(e[t],e[t+1]);this.adjacencyList.has(n)||this.adjacencyList.set(n,[]),this.adjacencyList.has(s)||this.adjacencyList.set(s,[]),this.adjacencyList.get(n).push({node:s,distance:i}),this.adjacencyList.get(s).push({node:n,distance:i})}}}getRoute(e,n){if(!this.network)throw new Error("Network not built. Please call buildRouteGraph(network) first.");const s=this.coordinateIndex(e.geometry.coordinates),i=this.coordinateIndex(n.geometry.coordinates);if(s===i)return null;const o=new t,r=new t;o.insert(0,s),r.insert(0,i);const h=new Map,a=new Map,c=new Map([[s,0]]),d=new Map([[i,0]]),l=new Set,u=new Set;let f=null;for(;o.size()>0&&r.size()>0;){const t=o.extractMin();if(l.add(t),u.has(t)){f=t;break}for(const e of this.adjacencyList.get(t)||[]){var g,M;const n=(null!=(g=c.get(t))?g:Infinity)+e.distance;if(n<(null!=(M=c.get(e.node))?M:Infinity)){h.set(e.node,t),c.set(e.node,n);const s=n+this.distanceMeasurement(this.coords[e.node],this.coords[i]);o.insert(s,e.node)}}const e=r.extractMin();if(u.add(e),l.has(e)){f=e;break}for(const t of this.adjacencyList.get(e)||[]){var m,p;const n=(null!=(m=d.get(e))?m:Infinity)+t.distance;if(n<(null!=(p=d.get(t.node))?p:Infinity)){a.set(t.node,e),d.set(t.node,n);const i=n+this.distanceMeasurement(this.coords[t.node],this.coords[s]);r.insert(i,t.node)}}}if(null===f)return null;const y=[];let w=f;for(;void 0!==w;)y.unshift(this.coords[w]),w=h.get(w);const L=[];for(w=a.get(f);void 0!==w;)L.push(this.coords[w]),w=a.get(w);return{type:"Feature",geometry:{type:"LineString",coordinates:[...y,...L]},properties:{}}}}export{s as TerraRoute,n as createCheapRuler,e as haversineDistance};
1
+ const t=(t,e)=>{const n=t=>t*Math.PI/180,s=n(t[1]),i=n(t[0]),o=n(e[1]),r=o-s,a=n(e[0])-i,h=Math.sin(r/2)*Math.sin(r/2)+Math.cos(s)*Math.cos(o)*Math.sin(a/2)*Math.sin(a/2);return 2*Math.atan2(Math.sqrt(h),Math.sqrt(1-h))*6371e3/1e3};function e(t){const e=1/298.257223563,n=e*(2-e),s=Math.PI/180,i=Math.cos(t*s),o=1/(1-n*(1-i*i)),r=Math.sqrt(o),a=6378.137*s,h=a*r*i,c=a*r*o*(1-n);return function(t,e){let n=t[0]-e[0];for(;n<-180;)n+=360;for(;n>180;)n-=360;const s=n*h,i=(t[1]-e[1])*c;return Math.sqrt(s*s+i*i)}}class n{constructor(){this.heap=[],this.insertCounter=0}insert(t,e){const n={key:t,value:e,index:this.insertCounter++};let s=this.heap.length;for(this.heap.push(n);s>0;){const e=s-1>>>1,i=this.heap[e];if(t>i.key||t===i.key&&n.index>i.index)break;this.heap[s]=i,s=e}this.heap[s]=n}extractMin(){const t=this.heap,e=t.length;if(0===e)return null;const n=t[0],s=t.pop();return e>1&&(t[0]=s,this.bubbleDown(0)),n.value}size(){return this.heap.length}bubbleDown(t){const e=this.heap,n=e.length,s=e[t],i=s.key,o=s.index;for(;;){const s=1+(t<<1);if(s>=n)break;let r=s,a=e[s];const h=s+1;if(h<n){const t=e[h];(t.key<a.key||t.key===a.key&&t.index<a.index)&&(r=h,a=t)}if(!(a.key<i||a.key===i&&a.index<o))break;e[t]=a,t=r}e[t]=s}}class s{constructor(e){var s,i;this.network=null,this.distanceMeasurement=void 0,this.heapConstructor=void 0,this.coordinateIndexMap=new Map,this.coordinates=[],this.adjacencyList=[],this.distanceMeasurement=null!=(s=null==e?void 0:e.distanceMeasurement)?s:t,this.heapConstructor=null!=(i=null==e?void 0:e.heap)?i:n}buildRouteGraph(t){this.network=t,this.coordinateIndexMap=new Map,this.coordinates=[],this.adjacencyList=[];const e=this.coordinateIndexMap,n=this.coordinates,s=this.adjacencyList,i=this.distanceMeasurement;for(const o of t.features){const t=o.geometry.coordinates;for(let o=0;o<t.length-1;o++){const[r,a]=t[o],[h,c]=t[o+1];let d=e.get(r);d||(d=new Map,e.set(r,d));let l=d.get(a);void 0===l&&(l=n.length,n.push(t[o]),d.set(a,l),s[l]=[]);let u=e.get(h);u||(u=new Map,e.set(h,u));let p=u.get(c);void 0===p&&(p=n.length,n.push(t[o+1]),u.set(c,p),s[p]=[]);const f=i(t[o],t[o+1]);s[l].push({node:p,distance:f}),s[p].push({node:l,distance:f})}}}getRoute(t,e){if(!this.network)throw new Error("Network not built. Please call buildRouteGraph(network) first.");const n=this.getOrCreateIndex(t.geometry.coordinates),s=this.getOrCreateIndex(e.geometry.coordinates);if(n===s)return null;const i=new this.heapConstructor;i.insert(0,n);const o=this.coordinates.length,r=new Array(o).fill(Infinity),a=new Array(o).fill(-1),h=new Array(o).fill(!1);for(r[n]=0;i.size()>0;){const t=i.extractMin();if(!h[t]){if(t===s)break;h[t]=!0;for(const e of this.adjacencyList[t]||[]){const n=r[t]+e.distance;if(n<r[e.node]){r[e.node]=n,a[e.node]=t;const o=this.distanceMeasurement(this.coordinates[e.node],this.coordinates[s]);i.insert(n+o,e.node)}}}}if(a[s]<0)return null;const c=[];let d=s;for(;d!==n;)c.unshift(this.coordinates[d]),d=a[d];return c.unshift(this.coordinates[n]),{type:"Feature",geometry:{type:"LineString",coordinates:c},properties:{}}}getOrCreateIndex(t){const[e,n]=t;let s=this.coordinateIndexMap.get(e);s||(s=new Map,this.coordinateIndexMap.set(e,s));let i=s.get(n);return void 0===i&&(i=this.coordinates.length,this.coordinates.push(t),s.set(n,i),this.adjacencyList[i]=[]),i}}export{s as TerraRoute,e as createCheapRuler,t as haversineDistance};
2
2
  //# sourceMappingURL=terra-route.modern.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"terra-route.modern.js","sources":["../src/fibonacci-heap.ts","../src/distance/haversine.ts","../src/distance/cheap-ruler.ts","../src/terra-route.ts"],"sourcesContent":["type FibNode = {\n key: number;\n value: number;\n degree: number;\n mark: boolean;\n parent: FibNode | null;\n child: FibNode | null;\n left: FibNode;\n right: FibNode;\n};\n\nexport class FibonacciHeap {\n private nodeCount = 0;\n private minNode: FibNode | null = null;\n\n insert(key: number, value: number): void {\n const node: FibNode = {\n key,\n value,\n degree: 0,\n mark: false,\n parent: null,\n child: null,\n left: null as any,\n right: null as any,\n };\n node.left = node;\n node.right = node;\n\n this.minNode = this.mergeLists(this.minNode, node);\n this.nodeCount++;\n }\n\n extractMin(): number | null {\n const z = this.minNode;\n if (!z) return null;\n\n // Add children to root list\n if (z.child) {\n let child = z.child;\n do {\n child.parent = null;\n child = child.right!;\n } while (child !== z.child);\n this.minNode = this.mergeLists(this.minNode, z.child);\n }\n\n this.removeFromList(z);\n\n if (z === z.right) {\n this.minNode = null;\n } else {\n this.minNode = z.right;\n this.consolidate();\n }\n\n this.nodeCount--;\n return z.value;\n }\n\n size(): number {\n return this.nodeCount;\n }\n\n // ========== Internal Methods ==========\n\n private consolidate(): void {\n const maxDegree = Math.floor(Math.log2(this.nodeCount)) + 1;\n const A = new Array<FibNode | null>(maxDegree).fill(null);\n\n const rootList: FibNode[] = [];\n let curr = this.minNode!;\n do {\n rootList.push(curr);\n curr = curr.right!;\n } while (curr !== this.minNode);\n\n for (const w of rootList) {\n let x = w;\n let d = x.degree;\n while (A[d]) {\n let y = A[d]!;\n if (x.key > y.key) {\n const temp = x;\n x = y;\n y = temp;\n }\n this.link(y, x);\n A[d] = null;\n d++;\n }\n A[d] = x;\n }\n\n this.minNode = null;\n for (const node of A) {\n if (node) {\n this.minNode = this.mergeLists(this.minNode, node);\n }\n }\n }\n\n private link(y: FibNode, x: FibNode): void {\n this.removeFromList(y);\n y.left = y.right = y;\n x.child = this.mergeLists(x.child, y);\n y.parent = x;\n x.degree++;\n y.mark = false;\n }\n\n private mergeLists(a: FibNode | null, b: FibNode | null): FibNode {\n if (!a) return b!;\n if (!b) return a;\n\n const aRight = a.right!;\n const bRight = b.right!;\n\n a.right = bRight;\n bRight.left = a;\n b.right = aRight;\n aRight.left = b;\n\n return a.key < b.key ? a : b;\n }\n\n private removeFromList(node: FibNode): void {\n node.left.right = node.right;\n node.right.left = node.left;\n }\n}\n","import { Position } from \"geojson\";\n\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { FibonacciHeap } from \"./fibonacci-heap\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\n\n/**\n * TerraRoute is a routing utility for finding the shortest path\n * between two geographic points over a given GeoJSON LineString network.\n *\n * The class builds an internal graph structure based on the provided network,\n * then applies A* algorithm to compute the shortest route.\n */\nclass TerraRoute {\n private network: FeatureCollection<LineString> | undefined;\n private distanceMeasurement: (positionA: Position, positionB: Position) => number;\n private adjacencyList: Map<number, Array<{ node: number; distance: number }>> = new Map();\n private coords: Position[] = []\n private coordMap: Map<number, Map<number, number>> = new Map();\n\n /**\n * Creates a new instance of TerraRoute.\n * \n * @param distanceMeasurement - Optional custom distance measurement function (defaults to haversine distance).\n */\n constructor(\n distanceMeasurement?: (positionA: Position, positionB: Position) => number\n ) {\n this.distanceMeasurement = distanceMeasurement ? distanceMeasurement : haversineDistance;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n private coordinateIndex(coord: Position): number {\n const [lng, lat] = coord;\n if (!this.coordMap.has(lng)) this.coordMap.set(lng, new Map());\n\n const latMap = this.coordMap.get(lng)!;\n if (latMap.has(lat)) {\n return latMap.get(lat)!;\n }\n\n const index = this.coords.length;\n this.coords.push(coord);\n latMap.set(lat, index);\n\n return index;\n }\n\n /**\n * Builds the internal graph representation (adjacency list) from the input network.\n * Each LineString segment is translated into bidirectional graph edges with associated distances.\n * Assumes that the network is a connected graph of LineStrings with shared coordinates. Calling this \n * method with a new network overwrite any existing network and reset all internal data structures.\n * \n * @param network - A GeoJSON FeatureCollection of LineStrings representing the road network.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n this.adjacencyList = new Map();\n this.coords = [];\n this.coordMap = new Map();\n\n for (const feature of this.network.features) {\n const coords = feature.geometry.coordinates;\n for (let i = 0; i < coords.length - 1; i++) {\n const aIndex = this.coordinateIndex(coords[i]);\n const bIndex = this.coordinateIndex(coords[i + 1]);\n const distance = this.distanceMeasurement(coords[i], coords[i + 1]);\n\n if (!this.adjacencyList.has(aIndex)) this.adjacencyList.set(aIndex, []);\n if (!this.adjacencyList.has(bIndex)) this.adjacencyList.set(bIndex, []);\n\n this.adjacencyList.get(aIndex)!.push({ node: bIndex, distance });\n this.adjacencyList.get(bIndex)!.push({ node: aIndex, distance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using bidirectional A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildRouteGraph(network) first.\");\n }\n\n const startIndex = this.coordinateIndex(start.geometry.coordinates);\n const endIndex = this.coordinateIndex(end.geometry.coordinates);\n\n if (startIndex === endIndex) {\n return null;\n }\n\n const openSetForward = new FibonacciHeap();\n const openSetBackward = new FibonacciHeap();\n openSetForward.insert(0, startIndex);\n openSetBackward.insert(0, endIndex);\n\n const cameFromForward = new Map<number, number>();\n const cameFromBackward = new Map<number, number>();\n const gScoreForward = new Map<number, number>([[startIndex, 0]]);\n const gScoreBackward = new Map<number, number>([[endIndex, 0]]);\n\n const visitedForward = new Set<number>();\n const visitedBackward = new Set<number>();\n\n let meetingNode: number | null = null;\n\n while (openSetForward.size() > 0 && openSetBackward.size() > 0) {\n const currentForward = openSetForward.extractMin()!;\n visitedForward.add(currentForward);\n\n if (visitedBackward.has(currentForward)) {\n meetingNode = currentForward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentForward) || []) {\n const tentativeG = (gScoreForward.get(currentForward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreForward.get(neighbor.node) ?? Infinity)) {\n cameFromForward.set(neighbor.node, currentForward);\n gScoreForward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[endIndex]);\n openSetForward.insert(fScore, neighbor.node);\n }\n }\n\n const currentBackward = openSetBackward.extractMin()!;\n visitedBackward.add(currentBackward);\n\n if (visitedForward.has(currentBackward)) {\n meetingNode = currentBackward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentBackward) || []) {\n const tentativeG = (gScoreBackward.get(currentBackward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreBackward.get(neighbor.node) ?? Infinity)) {\n cameFromBackward.set(neighbor.node, currentBackward);\n gScoreBackward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[startIndex]);\n openSetBackward.insert(fScore, neighbor.node);\n }\n }\n }\n\n if (meetingNode === null) {\n return null;\n }\n\n // Reconstruct forward path\n const pathForward: Position[] = [];\n let node = meetingNode;\n while (node !== undefined) {\n pathForward.unshift(this.coords[node]);\n node = cameFromForward.get(node)!;\n }\n\n // Reconstruct backward path (omit meeting node to avoid duplication)\n const pathBackward: Position[] = [];\n node = cameFromBackward.get(meetingNode)!;\n while (node !== undefined) {\n pathBackward.push(this.coords[node]);\n node = cameFromBackward.get(node)!;\n }\n\n const fullPath = [...pathForward, ...pathBackward];\n\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: fullPath },\n properties: {},\n };\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }"],"names":["FibonacciHeap","constructor","nodeCount","minNode","insert","key","value","node","degree","mark","parent","child","left","right","this","mergeLists","extractMin","z","removeFromList","consolidate","size","maxDegree","Math","floor","log2","A","Array","fill","rootList","curr","push","w","x","d","y","temp","link","a","b","aRight","bRight","haversineDistance","pointOne","pointTwo","toRadians","latOrLng","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","sin","cos","atan2","sqrt","createCheapRuler","lat","FE","E2","RAD","cosLat","w2","m","kx","ky","deltaLng","dx","dy","TerraRoute","distanceMeasurement","network","adjacencyList","Map","coords","coordMap","coordinateIndex","coord","lng","has","set","latMap","get","index","length","buildRouteGraph","feature","features","geometry","coordinates","i","aIndex","bIndex","distance","getRoute","start","end","Error","startIndex","endIndex","openSetForward","openSetBackward","cameFromForward","cameFromBackward","gScoreForward","gScoreBackward","visitedForward","Set","visitedBackward","meetingNode","currentForward","add","neighbor","_gScoreForward$get","_gScoreForward$get2","tentativeG","Infinity","fScore","currentBackward","_gScoreBackward$get","_gScoreBackward$get2","pathForward","undefined","unshift","pathBackward","type","properties"],"mappings":"AAWa,MAAAA,EAAaC,WAAAA,GACdC,KAAAA,UAAY,EACZC,KAAAA,QAA0B,IAAI,CAEtCC,MAAAA,CAAOC,EAAaC,GAChB,MAAMC,EAAgB,CAClBF,MACAC,QACAE,OAAQ,EACRC,MAAM,EACNC,OAAQ,KACRC,MAAO,KACPC,KAAM,KACNC,MAAO,MAEXN,EAAKK,KAAOL,EACZA,EAAKM,MAAQN,EAEbO,KAAKX,QAAUW,KAAKC,WAAWD,KAAKX,QAASI,GAC7CO,KAAKZ,WACT,CAEAc,UAAAA,GACI,MAAMC,EAAIH,KAAKX,QACf,IAAKc,EAAG,OAAW,KAGnB,GAAIA,EAAEN,MAAO,CACT,IAAIA,EAAQM,EAAEN,MACd,GACIA,EAAMD,OAAS,KACfC,EAAQA,EAAME,YACTF,IAAUM,EAAEN,OACrBG,KAAKX,QAAUW,KAAKC,WAAWD,KAAKX,QAASc,EAAEN,MACnD,CAYA,OAVAG,KAAKI,eAAeD,GAEhBA,IAAMA,EAAEJ,MACRC,KAAKX,QAAU,MAEfW,KAAKX,QAAUc,EAAEJ,MACjBC,KAAKK,eAGTL,KAAKZ,YACEe,EAAEX,KACb,CAEAc,IAAAA,GACI,YAAYlB,SAChB,CAIQiB,WAAAA,GACJ,MAAME,EAAYC,KAAKC,MAAMD,KAAKE,KAAKV,KAAKZ,YAAc,EACpDuB,EAAI,IAAIC,MAAsBL,GAAWM,KAAK,MAE9CC,EAAsB,GA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DI,OAApCA,EAACd,EAAevB,IAAIoC,IAAgBC,EAAIH,UAAYJ,EAASnB,SAChF,GAAIsB,GAA+C,OAArCK,EAAIf,EAAevB,IAAI8B,EAASzG,OAAKiH,EAAIJ,UAAW,CAC9Db,EAAiBvB,IAAIgC,EAASzG,KAAM+G,GACpCb,EAAezB,IAAIgC,EAASzG,KAAM4G,GAClC,MAAME,EAASF,EAAarG,KAAKwD,oBAAoBxD,KAAK4D,OAAOsC,EAASzG,MAAOO,KAAK4D,OAAOwB,IAC7FG,EAAgBjG,OAAOiH,EAAQL,EAASzG,KAC5C,CACJ,CACJ,CAEA,GAAoB,OAAhBsG,EACA,OACJ,KAGA,MAAMY,EAA0B,GAChC,IAAIlH,EAAOsG,EACX,UAAgBa,IAATnH,GACHkH,EAAYE,QAAQ7G,KAAK4D,OAAOnE,IAChCA,EAAO+F,EAAgBpB,IAAI3E,GAI/B,MAAMqH,EAA2B,GAEjC,IADArH,EAAOgG,EAAiBrB,IAAI2B,QACZa,IAATnH,GACHqH,EAAa9F,KAAKhB,KAAK4D,OAAOnE,IAC9BA,EAAOgG,EAAiBrB,IAAI3E,GAKhC,MAAO,CACHsH,KAAM,UACNrC,SAAU,CAAEqC,KAAM,aAAcpC,YAJnB,IAAIgC,KAAgBG,IAKjCE,WAAY,GAEpB"}
1
+ {"version":3,"file":"terra-route.modern.js","sources":["../src/distance/haversine.ts","../src/distance/cheap-ruler.ts","../src/heap/min-heap.ts","../src/terra-route.ts"],"sourcesContent":["import { Position } from \"geojson\";\n\n/** Distance measured in kilometers */\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}\n","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}","import { Heap } from \"./heap\";\n\nexport class MinHeap implements Heap {\n private heap: Array<{ key: number; value: number; index: number }> = [];\n private insertCounter = 0;\n\n insert(key: number, value: number): void {\n const node = { key, value, index: this.insertCounter++ };\n let currentIndex = this.heap.length;\n this.heap.push(node);\n\n while (currentIndex > 0) {\n const parentIndex = (currentIndex - 1) >>> 1;\n const parent = this.heap[parentIndex];\n\n if (\n key > parent.key ||\n (key === parent.key && node.index > parent.index)\n ) {\n break;\n }\n\n this.heap[currentIndex] = parent;\n currentIndex = parentIndex;\n }\n\n this.heap[currentIndex] = node;\n }\n\n extractMin(): number | null {\n const heap = this.heap;\n const length = heap.length;\n\n if (length === 0) {\n return null;\n }\n\n const minNode = heap[0];\n const endNode = heap.pop()!;\n\n if (length > 1) {\n heap[0] = endNode;\n this.bubbleDown(0);\n }\n\n return minNode.value;\n }\n\n size(): number {\n return this.heap.length;\n }\n\n private bubbleDown(index: number): void {\n const heap = this.heap;\n const length = heap.length;\n const node = heap[index];\n const nodeKey = node.key;\n const nodeIndex = node.index;\n\n while (true) {\n const leftChildIndex = (index << 1) + 1;\n if (leftChildIndex >= length) {\n break;\n }\n\n let smallestIndex = leftChildIndex;\n let smallest = heap[leftChildIndex];\n\n const rightChildIndex = leftChildIndex + 1;\n if (rightChildIndex < length) {\n const right = heap[rightChildIndex];\n if (\n right.key < smallest.key ||\n (right.key === smallest.key && right.index < smallest.index)\n ) {\n smallestIndex = rightChildIndex;\n smallest = right;\n }\n }\n\n if (\n smallest.key < nodeKey ||\n (smallest.key === nodeKey && smallest.index < nodeIndex)\n ) {\n heap[index] = smallest;\n index = smallestIndex;\n } else {\n break;\n }\n }\n\n heap[index] = node;\n }\n}\n","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\nimport { MinHeap } from \"./heap/min-heap\";\nimport { HeapConstructor } from \"./heap/heap\";\n\ninterface Router {\n buildRouteGraph(network: FeatureCollection<LineString>): void;\n getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null;\n}\n\nclass TerraRoute implements Router {\n private network: FeatureCollection<LineString> | null = null;\n private distanceMeasurement: (a: Position, b: Position) => number;\n private heapConstructor: HeapConstructor;\n\n // Map from longitude → (map from latitude → index)\n private coordinateIndexMap: Map<number, Map<number, number>> = new Map();\n private coordinates: Position[] = [];\n private adjacencyList: Array<Array<{ node: number; distance: number }>> = [];\n\n constructor(options?: {\n distanceMeasurement?: (a: Position, b: Position) => number;\n heap?: HeapConstructor;\n }) {\n this.distanceMeasurement = options?.distanceMeasurement ?? haversineDistance;\n this.heapConstructor = options?.heap ?? MinHeap;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n\n // Reset everything\n this.coordinateIndexMap = new Map();\n this.coordinates = [];\n this.adjacencyList = [];\n\n // Hoist to locals for speed\n const coordIndexMapLocal = this.coordinateIndexMap;\n const coordsLocal = this.coordinates;\n const adjListLocal = this.adjacencyList;\n const measureDistance = this.distanceMeasurement;\n\n for (const feature of network.features) {\n const lineCoords = feature.geometry.coordinates;\n\n for (let i = 0; i < lineCoords.length - 1; i++) {\n const [lngA, latA] = lineCoords[i];\n const [lngB, latB] = lineCoords[i + 1];\n\n // get or assign index for A \n let latMapA = coordIndexMapLocal.get(lngA);\n if (!latMapA) {\n latMapA = new Map<number, number>();\n coordIndexMapLocal.set(lngA, latMapA);\n }\n let indexA = latMapA.get(latA);\n if (indexA === undefined) {\n indexA = coordsLocal.length;\n coordsLocal.push(lineCoords[i]);\n latMapA.set(latA, indexA);\n adjListLocal[indexA] = [];\n }\n\n // get or assign index for B \n let latMapB = coordIndexMapLocal.get(lngB);\n if (!latMapB) {\n latMapB = new Map<number, number>();\n coordIndexMapLocal.set(lngB, latMapB);\n }\n let indexB = latMapB.get(latB);\n if (indexB === undefined) {\n indexB = coordsLocal.length;\n coordsLocal.push(lineCoords[i + 1]);\n latMapB.set(latB, indexB);\n adjListLocal[indexB] = [];\n }\n\n // record the bidirectional edge \n const segmentDistance = measureDistance(lineCoords[i], lineCoords[i + 1]);\n adjListLocal[indexA].push({ node: indexB, distance: segmentDistance });\n adjListLocal[indexB].push({ node: indexA, distance: segmentDistance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using the A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(\n start: Feature<Point>,\n end: Feature<Point>\n ): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildRouteGraph(network) first.\");\n }\n\n // ensure start/end are in the index maps\n const startIndex = this.getOrCreateIndex(start.geometry.coordinates);\n const endIndex = this.getOrCreateIndex(end.geometry.coordinates);\n\n if (startIndex === endIndex) {\n return null;\n }\n\n const openSet = new this.heapConstructor();\n openSet.insert(0, startIndex);\n\n const nodeCount = this.coordinates.length;\n const gScore = new Array<number>(nodeCount).fill(Infinity);\n const cameFrom = new Array<number>(nodeCount).fill(-1);\n const visited = new Array<boolean>(nodeCount).fill(false);\n\n gScore[startIndex] = 0;\n\n while (openSet.size() > 0) {\n const current = openSet.extractMin()!;\n if (visited[current]) {\n continue;\n }\n if (current === endIndex) {\n break;\n }\n visited[current] = true;\n\n for (const neighbor of this.adjacencyList[current] || []) {\n const tentativeG = gScore[current] + neighbor.distance;\n if (tentativeG < gScore[neighbor.node]) {\n gScore[neighbor.node] = tentativeG;\n cameFrom[neighbor.node] = current;\n const heuristic = this.distanceMeasurement(\n this.coordinates[neighbor.node],\n this.coordinates[endIndex]\n );\n openSet.insert(tentativeG + heuristic, neighbor.node);\n }\n }\n }\n\n if (cameFrom[endIndex] < 0) {\n return null;\n }\n\n // Reconstruct path\n const path: Position[] = [];\n let current = endIndex;\n while (current !== startIndex) {\n path.unshift(this.coordinates[current]);\n current = cameFrom[current];\n }\n path.unshift(this.coordinates[startIndex]);\n\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: path },\n properties: {},\n };\n }\n\n /**\n * Helper to index start/end in getRoute.\n */\n private getOrCreateIndex(coord: Position): number {\n const [lng, lat] = coord;\n let latMap = this.coordinateIndexMap.get(lng);\n if (!latMap) {\n latMap = new Map<number, number>();\n this.coordinateIndexMap.set(lng, latMap);\n }\n let index = latMap.get(lat);\n if (index === undefined) {\n index = this.coordinates.length;\n this.coordinates.push(coord);\n latMap.set(lat, index);\n // ensure adjacencyList covers this new node\n this.adjacencyList[index] = [];\n }\n return index;\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }"],"names":["haversineDistance","pointOne","pointTwo","toRadians","latOrLng","Math","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","a","sin","cos","atan2","sqrt","createCheapRuler","lat","FE","E2","RAD","cosLat","w2","w","m","kx","ky","b","deltaLng","dx","dy","MinHeap","constructor","heap","this","insertCounter","insert","key","value","node","index","currentIndex","length","push","parentIndex","parent","extractMin","minNode","endNode","pop","bubbleDown","size","nodeKey","nodeIndex","leftChildIndex","smallestIndex","smallest","rightChildIndex","right","TerraRoute","options","_options$distanceMeas","_options$heap","network","distanceMeasurement","heapConstructor","coordinateIndexMap","Map","coordinates","adjacencyList","buildRouteGraph","coordIndexMapLocal","coordsLocal","adjListLocal","measureDistance","feature","features","lineCoords","geometry","i","lngA","latA","lngB","latB","latMapA","get","set","indexA","undefined","latMapB","indexB","segmentDistance","distance","getRoute","start","end","Error","startIndex","getOrCreateIndex","endIndex","openSet","nodeCount","gScore","Array","fill","Infinity","cameFrom","visited","current","neighbor","tentativeG","heuristic","path","unshift","type","properties","coord","lng","latMap"],"mappings":"AAGa,MAAAA,EAAoBA,CAACC,EAAoBC,KAClD,MAAMC,EAAaC,GAAsBA,EAAWC,KAAKC,GAAM,IAEzDC,EAASJ,EAAUF,EAAS,IAC5BO,EAAYL,EAAUF,EAAS,IAC/BQ,EAASN,EAAUD,EAAS,IAE5BQ,EAAWD,EAASF,EACpBI,EAFYR,EAAUD,EAAS,IAELM,EAE1BI,EACFP,KAAKQ,IAAIH,EAAW,GAAKL,KAAKQ,IAAIH,EAAW,GAC7CL,KAAKS,IAAIP,GACTF,KAAKS,IAAIL,GACTJ,KAAKQ,IAAIF,EAAc,GACvBN,KAAKQ,IAAIF,EAAc,GAM3B,OALU,EAAIN,KAAKU,MAAMV,KAAKW,KAAKJ,GAAIP,KAAKW,KAAK,EAAIJ,IAEtC,OAGG,KCQhB,SAAUK,EAAiBC,GAC7B,MACMC,EAAK,EAAI,cACTC,EAAKD,GAAM,EAAIA,GACfE,EAAMhB,KAAKC,GAAK,IAEhBgB,EAASjB,KAAKS,IAAII,EAAMG,GACxBE,EAAK,GAAK,EAAIH,GAAM,EAAIE,EAASA,IACjCE,EAAInB,KAAKW,KAAKO,GAEdE,EATK,SASDJ,EACJK,EAAKD,EAAID,EAAIF,EACbK,EAAKF,EAAID,EAAID,GAAM,EAAIH,GAE7B,OAAgB,SAASR,EAAagB,GAClC,IAAIC,EAAWjB,EAAE,GAAKgB,EAAE,GAExB,KAAOC,GAAY,KAAKA,GAAY,IACpC,KAAOA,EAAW,KAAKA,GAAY,IAEnC,MAAMC,EAAKD,EAAWH,EAChBK,GAAMnB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C,EAASjB,SAC9C,GAAIkB,EAAaR,EAAOO,EAAStE,MAAO,CACpC+D,EAAOO,EAAStE,MAAQuE,EACxBJ,EAASG,EAAStE,MAAQqE,EAC1B,MAAMG,EAAY7E,KAAK8B,oBACnB9B,KAAKkC,YAAYyC,EAAStE,MAC1BL,KAAKkC,YAAY+B,IAErBC,EAAQhE,OAAO0E,EAAaC,EAAWF,EAAStE,KACpD,CACJ,CAjBA,CAkBJ,CAEA,GAAImE,EAASP,GAAY,EACrB,OAAO,KAIX,MAAMa,EAAmB,GACzB,IAAIJ,EAAUT,EACd,KAAOS,IAAYX,GACfe,EAAKC,QAAQ/E,KAAKkC,YAAYwC,IAC9BA,EAAUF,EAASE,GAIvB,OAFAI,EAAKC,QAAQ/E,KAAKkC,YAAY6B,IAEvB,CACHiB,KAAM,UACNpC,SAAU,CAAEoC,KAAM,aAAc9C,YAAa4C,GAC7CG,WAAY,GAEpB,CAKQjB,gBAAAA,CAAiBkB,GACrB,MAAOC,EAAKpG,GAAOmG,EACnB,IAAIE,EAASpF,KAAKgC,mBAAmBmB,IAAIgC,GACpCC,IACDA,EAAS,IAAInD,IACbjC,KAAKgC,mBAAmBoB,IAAI+B,EAAKC,IAErC,IAAI9E,EAAQ8E,EAAOjC,IAAIpE,GAQvB,YAPcuE,IAAVhD,IACAA,EAAQN,KAAKkC,YAAY1B,OACzBR,KAAKkC,YAAYzB,KAAKyE,GACtBE,EAAOhC,IAAIrE,EAAKuB,GAEhBN,KAAKmC,cAAc7B,GAAS,IAEzBA,CACX"}
@@ -1,2 +1,2 @@
1
- function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function e(e,n){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,n){if(e){if("string"==typeof e)return t(e,n);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(e,n):void 0}}(e))||n&&e&&"number"==typeof e.length){r&&(e=r);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n=/*#__PURE__*/function(){function t(){this.nodeCount=0,this.minNode=null}var n=t.prototype;return n.insert=function(t,e){var n={key:t,value:e,degree:0,mark:!1,parent:null,child:null,left:null,right:null};n.left=n,n.right=n,this.minNode=this.mergeLists(this.minNode,n),this.nodeCount++},n.extractMin=function(){var t=this.minNode;if(!t)return null;if(t.child){var e=t.child;do{e.parent=null,e=e.right}while(e!==t.child);this.minNode=this.mergeLists(this.minNode,t.child)}return this.removeFromList(t),t===t.right?this.minNode=null:(this.minNode=t.right,this.consolidate()),this.nodeCount--,t.value},n.size=function(){return this.nodeCount},n.consolidate=function(){var t=Math.floor(Math.log2(this.nodeCount))+1,n=new Array(t).fill(null),r=[],i=this.minNode;do{r.push(i),i=i.right}while(i!==this.minNode);for(var o=0,a=r;o<a.length;o++){for(var s=a[o],h=s.degree;n[h];){var d=n[h];if(s.key>d.key){var c=s;s=d,d=c}this.link(d,s),n[h]=null,h++}n[h]=s}this.minNode=null;for(var u,l=e(n);!(u=l()).done;){var f=u.value;f&&(this.minNode=this.mergeLists(this.minNode,f))}},n.link=function(t,e){this.removeFromList(t),t.left=t.right=t,e.child=this.mergeLists(e.child,t),t.parent=e,e.degree++,t.mark=!1},n.mergeLists=function(t,e){if(!t)return e;if(!e)return t;var n=t.right,r=e.right;return t.right=r,r.left=t,e.right=n,n.left=e,t.key<e.key?t:e},n.removeFromList=function(t){t.left.right=t.right,t.right.left=t.left},t}(),r=function(t,e){var n=function(t){return t*Math.PI/180},r=n(t[1]),i=n(t[0]),o=n(e[1]),a=o-r,s=n(e[0])-i,h=Math.sin(a/2)*Math.sin(a/2)+Math.cos(r)*Math.cos(o)*Math.sin(s/2)*Math.sin(s/2);return 2*Math.atan2(Math.sqrt(h),Math.sqrt(1-h))*6371e3/1e3};function i(t){var e=1/298.257223563,n=e*(2-e),r=Math.PI/180,i=Math.cos(t*r),o=1/(1-n*(1-i*i)),a=Math.sqrt(o),s=6378.137*r,h=s*a*i,d=s*a*o*(1-n);return function(t,e){for(var n=t[0]-e[0];n<-180;)n+=360;for(;n>180;)n-=360;var r=n*h,i=(t[1]-e[1])*d;return Math.sqrt(r*r+i*i)}}var o=/*#__PURE__*/function(){function t(t){this.network=void 0,this.distanceMeasurement=void 0,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map,this.distanceMeasurement=t||r}var i=t.prototype;return i.coordinateIndex=function(t){var e=t[0],n=t[1];this.coordMap.has(e)||this.coordMap.set(e,new Map);var r=this.coordMap.get(e);if(r.has(n))return r.get(n);var i=this.coords.length;return this.coords.push(t),r.set(n,i),i},i.buildRouteGraph=function(t){this.network=t,this.adjacencyList=new Map,this.coords=[],this.coordMap=new Map;for(var n,r=e(this.network.features);!(n=r()).done;)for(var i=n.value.geometry.coordinates,o=0;o<i.length-1;o++){var a=this.coordinateIndex(i[o]),s=this.coordinateIndex(i[o+1]),h=this.distanceMeasurement(i[o],i[o+1]);this.adjacencyList.has(a)||this.adjacencyList.set(a,[]),this.adjacencyList.has(s)||this.adjacencyList.set(s,[]),this.adjacencyList.get(a).push({node:s,distance:h}),this.adjacencyList.get(s).push({node:a,distance:h})}},i.getRoute=function(t,r){if(!this.network)throw new Error("Network not built. Please call buildRouteGraph(network) first.");var i=this.coordinateIndex(t.geometry.coordinates),o=this.coordinateIndex(r.geometry.coordinates);if(i===o)return null;var a=new n,s=new n;a.insert(0,i),s.insert(0,o);for(var h=new Map,d=new Map,c=new Map([[i,0]]),u=new Map([[o,0]]),l=new Set,f=new Set,v=null;a.size()>0&&s.size()>0;){var g=a.extractMin();if(l.add(g),f.has(g)){v=g;break}for(var m,y=e(this.adjacencyList.get(g)||[]);!(m=y()).done;){var p,M,w=m.value,L=(null!=(p=c.get(g))?p:Infinity)+w.distance;if(L<(null!=(M=c.get(w.node))?M:Infinity)){h.set(w.node,g),c.set(w.node,L);var k=L+this.distanceMeasurement(this.coords[w.node],this.coords[o]);a.insert(k,w.node)}}var b=s.extractMin();if(f.add(b),l.has(b)){v=b;break}for(var I,N=e(this.adjacencyList.get(b)||[]);!(I=N()).done;){var j,x,S=I.value,A=(null!=(j=u.get(b))?j:Infinity)+S.distance;if(A<(null!=(x=u.get(S.node))?x:Infinity)){d.set(S.node,b),u.set(S.node,A);var C=A+this.distanceMeasurement(this.coords[S.node],this.coords[i]);s.insert(C,S.node)}}}if(null===v)return null;for(var q=[],F=v;void 0!==F;)q.unshift(this.coords[F]),F=h.get(F);var z=[];for(F=d.get(v);void 0!==F;)z.push(this.coords[F]),F=d.get(F);return{type:"Feature",geometry:{type:"LineString",coordinates:[].concat(q,z)},properties:{}}},t}();export{o as TerraRoute,i as createCheapRuler,r as haversineDistance};
1
+ function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r<e;r++)n[r]=t[r];return n}function e(e,r){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,r){if(e){if("string"==typeof e)return t(e,r);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?t(e,r):void 0}}(e))||r&&e&&"number"==typeof e.length){n&&(e=n);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r=function(t,e){var r=function(t){return t*Math.PI/180},n=r(t[1]),i=r(t[0]),a=r(e[1]),o=a-n,s=r(e[0])-i,h=Math.sin(o/2)*Math.sin(o/2)+Math.cos(n)*Math.cos(a)*Math.sin(s/2)*Math.sin(s/2);return 2*Math.atan2(Math.sqrt(h),Math.sqrt(1-h))*6371e3/1e3};function n(t){var e=1/298.257223563,r=e*(2-e),n=Math.PI/180,i=Math.cos(t*n),a=1/(1-r*(1-i*i)),o=Math.sqrt(a),s=6378.137*n,h=s*o*i,u=s*o*a*(1-r);return function(t,e){for(var r=t[0]-e[0];r<-180;)r+=360;for(;r>180;)r-=360;var n=r*h,i=(t[1]-e[1])*u;return Math.sqrt(n*n+i*i)}}var i=/*#__PURE__*/function(){function t(){this.heap=[],this.insertCounter=0}var e=t.prototype;return e.insert=function(t,e){var r={key:t,value:e,index:this.insertCounter++},n=this.heap.length;for(this.heap.push(r);n>0;){var i=n-1>>>1,a=this.heap[i];if(t>a.key||t===a.key&&r.index>a.index)break;this.heap[n]=a,n=i}this.heap[n]=r},e.extractMin=function(){var t=this.heap,e=t.length;if(0===e)return null;var r=t[0],n=t.pop();return e>1&&(t[0]=n,this.bubbleDown(0)),r.value},e.size=function(){return this.heap.length},e.bubbleDown=function(t){for(var e=this.heap,r=e.length,n=e[t],i=n.key,a=n.index;;){var o=1+(t<<1);if(o>=r)break;var s=o,h=e[o],u=o+1;if(u<r){var c=e[u];(c.key<h.key||c.key===h.key&&c.index<h.index)&&(s=u,h=c)}if(!(h.key<i||h.key===i&&h.index<a))break;e[t]=h,t=s}e[t]=n},t}(),a=/*#__PURE__*/function(){function t(t){var e,n;this.network=null,this.distanceMeasurement=void 0,this.heapConstructor=void 0,this.coordinateIndexMap=new Map,this.coordinates=[],this.adjacencyList=[],this.distanceMeasurement=null!=(e=null==t?void 0:t.distanceMeasurement)?e:r,this.heapConstructor=null!=(n=null==t?void 0:t.heap)?n:i}var n=t.prototype;return n.buildRouteGraph=function(t){this.network=t,this.coordinateIndexMap=new Map,this.coordinates=[],this.adjacencyList=[];for(var r,n=this.coordinateIndexMap,i=this.coordinates,a=this.adjacencyList,o=this.distanceMeasurement,s=e(t.features);!(r=s()).done;)for(var h=r.value.geometry.coordinates,u=0;u<h.length-1;u++){var c=h[u],d=c[0],l=c[1],f=h[u+1],v=f[0],p=f[1],y=n.get(d);y||(y=new Map,n.set(d,y));var M=y.get(l);void 0===M&&(M=i.length,i.push(h[u]),y.set(l,M),a[M]=[]);var g=n.get(v);g||(g=new Map,n.set(v,g));var b=g.get(p);void 0===b&&(b=i.length,i.push(h[u+1]),g.set(p,b),a[b]=[]);var m=o(h[u],h[u+1]);a[M].push({node:b,distance:m}),a[b].push({node:M,distance:m})}},n.getRoute=function(t,r){if(!this.network)throw new Error("Network not built. Please call buildRouteGraph(network) first.");var n=this.getOrCreateIndex(t.geometry.coordinates),i=this.getOrCreateIndex(r.geometry.coordinates);if(n===i)return null;var a=new this.heapConstructor;a.insert(0,n);var o=this.coordinates.length,s=new Array(o).fill(Infinity),h=new Array(o).fill(-1),u=new Array(o).fill(!1);for(s[n]=0;a.size()>0;){var c=a.extractMin();if(!u[c]){if(c===i)break;u[c]=!0;for(var d,l=e(this.adjacencyList[c]||[]);!(d=l()).done;){var f=d.value,v=s[c]+f.distance;if(v<s[f.node]){s[f.node]=v,h[f.node]=c;var p=this.distanceMeasurement(this.coordinates[f.node],this.coordinates[i]);a.insert(v+p,f.node)}}}}if(h[i]<0)return null;for(var y=[],M=i;M!==n;)y.unshift(this.coordinates[M]),M=h[M];return y.unshift(this.coordinates[n]),{type:"Feature",geometry:{type:"LineString",coordinates:y},properties:{}}},n.getOrCreateIndex=function(t){var e=t[0],r=t[1],n=this.coordinateIndexMap.get(e);n||(n=new Map,this.coordinateIndexMap.set(e,n));var i=n.get(r);return void 0===i&&(i=this.coordinates.length,this.coordinates.push(t),n.set(r,i),this.adjacencyList[i]=[]),i},t}();export{a as TerraRoute,n as createCheapRuler,r as haversineDistance};
2
2
  //# sourceMappingURL=terra-route.module.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"terra-route.module.js","sources":["../src/fibonacci-heap.ts","../src/distance/haversine.ts","../src/distance/cheap-ruler.ts","../src/terra-route.ts"],"sourcesContent":["type FibNode = {\n key: number;\n value: number;\n degree: number;\n mark: boolean;\n parent: FibNode | null;\n child: FibNode | null;\n left: FibNode;\n right: FibNode;\n};\n\nexport class FibonacciHeap {\n private nodeCount = 0;\n private minNode: FibNode | null = null;\n\n insert(key: number, value: number): void {\n const node: FibNode = {\n key,\n value,\n degree: 0,\n mark: false,\n parent: null,\n child: null,\n left: null as any,\n right: null as any,\n };\n node.left = node;\n node.right = node;\n\n this.minNode = this.mergeLists(this.minNode, node);\n this.nodeCount++;\n }\n\n extractMin(): number | null {\n const z = this.minNode;\n if (!z) return null;\n\n // Add children to root list\n if (z.child) {\n let child = z.child;\n do {\n child.parent = null;\n child = child.right!;\n } while (child !== z.child);\n this.minNode = this.mergeLists(this.minNode, z.child);\n }\n\n this.removeFromList(z);\n\n if (z === z.right) {\n this.minNode = null;\n } else {\n this.minNode = z.right;\n this.consolidate();\n }\n\n this.nodeCount--;\n return z.value;\n }\n\n size(): number {\n return this.nodeCount;\n }\n\n // ========== Internal Methods ==========\n\n private consolidate(): void {\n const maxDegree = Math.floor(Math.log2(this.nodeCount)) + 1;\n const A = new Array<FibNode | null>(maxDegree).fill(null);\n\n const rootList: FibNode[] = [];\n let curr = this.minNode!;\n do {\n rootList.push(curr);\n curr = curr.right!;\n } while (curr !== this.minNode);\n\n for (const w of rootList) {\n let x = w;\n let d = x.degree;\n while (A[d]) {\n let y = A[d]!;\n if (x.key > y.key) {\n const temp = x;\n x = y;\n y = temp;\n }\n this.link(y, x);\n A[d] = null;\n d++;\n }\n A[d] = x;\n }\n\n this.minNode = null;\n for (const node of A) {\n if (node) {\n this.minNode = this.mergeLists(this.minNode, node);\n }\n }\n }\n\n private link(y: FibNode, x: FibNode): void {\n this.removeFromList(y);\n y.left = y.right = y;\n x.child = this.mergeLists(x.child, y);\n y.parent = x;\n x.degree++;\n y.mark = false;\n }\n\n private mergeLists(a: FibNode | null, b: FibNode | null): FibNode {\n if (!a) return b!;\n if (!b) return a;\n\n const aRight = a.right!;\n const bRight = b.right!;\n\n a.right = bRight;\n bRight.left = a;\n b.right = aRight;\n aRight.left = b;\n\n return a.key < b.key ? a : b;\n }\n\n private removeFromList(node: FibNode): void {\n node.left.right = node.right;\n node.right.left = node.left;\n }\n}\n","import { Position } from \"geojson\";\n\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { FibonacciHeap } from \"./fibonacci-heap\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\n\n/**\n * TerraRoute is a routing utility for finding the shortest path\n * between two geographic points over a given GeoJSON LineString network.\n *\n * The class builds an internal graph structure based on the provided network,\n * then applies A* algorithm to compute the shortest route.\n */\nclass TerraRoute {\n private network: FeatureCollection<LineString> | undefined;\n private distanceMeasurement: (positionA: Position, positionB: Position) => number;\n private adjacencyList: Map<number, Array<{ node: number; distance: number }>> = new Map();\n private coords: Position[] = []\n private coordMap: Map<number, Map<number, number>> = new Map();\n\n /**\n * Creates a new instance of TerraRoute.\n * \n * @param distanceMeasurement - Optional custom distance measurement function (defaults to haversine distance).\n */\n constructor(\n distanceMeasurement?: (positionA: Position, positionB: Position) => number\n ) {\n this.distanceMeasurement = distanceMeasurement ? distanceMeasurement : haversineDistance;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n private coordinateIndex(coord: Position): number {\n const [lng, lat] = coord;\n if (!this.coordMap.has(lng)) this.coordMap.set(lng, new Map());\n\n const latMap = this.coordMap.get(lng)!;\n if (latMap.has(lat)) {\n return latMap.get(lat)!;\n }\n\n const index = this.coords.length;\n this.coords.push(coord);\n latMap.set(lat, index);\n\n return index;\n }\n\n /**\n * Builds the internal graph representation (adjacency list) from the input network.\n * Each LineString segment is translated into bidirectional graph edges with associated distances.\n * Assumes that the network is a connected graph of LineStrings with shared coordinates. Calling this \n * method with a new network overwrite any existing network and reset all internal data structures.\n * \n * @param network - A GeoJSON FeatureCollection of LineStrings representing the road network.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n this.adjacencyList = new Map();\n this.coords = [];\n this.coordMap = new Map();\n\n for (const feature of this.network.features) {\n const coords = feature.geometry.coordinates;\n for (let i = 0; i < coords.length - 1; i++) {\n const aIndex = this.coordinateIndex(coords[i]);\n const bIndex = this.coordinateIndex(coords[i + 1]);\n const distance = this.distanceMeasurement(coords[i], coords[i + 1]);\n\n if (!this.adjacencyList.has(aIndex)) this.adjacencyList.set(aIndex, []);\n if (!this.adjacencyList.has(bIndex)) this.adjacencyList.set(bIndex, []);\n\n this.adjacencyList.get(aIndex)!.push({ node: bIndex, distance });\n this.adjacencyList.get(bIndex)!.push({ node: aIndex, distance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using bidirectional A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildRouteGraph(network) first.\");\n }\n\n const startIndex = this.coordinateIndex(start.geometry.coordinates);\n const endIndex = this.coordinateIndex(end.geometry.coordinates);\n\n if (startIndex === endIndex) {\n return null;\n }\n\n const openSetForward = new FibonacciHeap();\n const openSetBackward = new FibonacciHeap();\n openSetForward.insert(0, startIndex);\n openSetBackward.insert(0, endIndex);\n\n const cameFromForward = new Map<number, number>();\n const cameFromBackward = new Map<number, number>();\n const gScoreForward = new Map<number, number>([[startIndex, 0]]);\n const gScoreBackward = new Map<number, number>([[endIndex, 0]]);\n\n const visitedForward = new Set<number>();\n const visitedBackward = new Set<number>();\n\n let meetingNode: number | null = null;\n\n while (openSetForward.size() > 0 && openSetBackward.size() > 0) {\n const currentForward = openSetForward.extractMin()!;\n visitedForward.add(currentForward);\n\n if (visitedBackward.has(currentForward)) {\n meetingNode = currentForward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentForward) || []) {\n const tentativeG = (gScoreForward.get(currentForward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreForward.get(neighbor.node) ?? Infinity)) {\n cameFromForward.set(neighbor.node, currentForward);\n gScoreForward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[endIndex]);\n openSetForward.insert(fScore, neighbor.node);\n }\n }\n\n const currentBackward = openSetBackward.extractMin()!;\n visitedBackward.add(currentBackward);\n\n if (visitedForward.has(currentBackward)) {\n meetingNode = currentBackward;\n break;\n }\n\n for (const neighbor of this.adjacencyList.get(currentBackward) || []) {\n const tentativeG = (gScoreBackward.get(currentBackward) ?? Infinity) + neighbor.distance;\n if (tentativeG < (gScoreBackward.get(neighbor.node) ?? Infinity)) {\n cameFromBackward.set(neighbor.node, currentBackward);\n gScoreBackward.set(neighbor.node, tentativeG);\n const fScore = tentativeG + this.distanceMeasurement(this.coords[neighbor.node], this.coords[startIndex]);\n openSetBackward.insert(fScore, neighbor.node);\n }\n }\n }\n\n if (meetingNode === null) {\n return null;\n }\n\n // Reconstruct forward path\n const pathForward: Position[] = [];\n let node = meetingNode;\n while (node !== undefined) {\n pathForward.unshift(this.coords[node]);\n node = cameFromForward.get(node)!;\n }\n\n // Reconstruct backward path (omit meeting node to avoid duplication)\n const pathBackward: Position[] = [];\n node = cameFromBackward.get(meetingNode)!;\n while (node !== undefined) {\n pathBackward.push(this.coords[node]);\n node = cameFromBackward.get(node)!;\n }\n\n const fullPath = [...pathForward, ...pathBackward];\n\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: fullPath },\n properties: {},\n };\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }"],"names":["FibonacciHeap","this","nodeCount","minNode","_proto","prototype","insert","key","value","node","degree","mark","parent","child","left","right","mergeLists","extractMin","z","removeFromList","consolidate","size","maxDegree","Math","floor","log2","A","Array","fill","rootList","curr","push","_i","_rootList","length","x","d","y","temp","link","_step","_iterator","_createForOfIteratorHelperLoose","done","a","b","aRight","bRight","haversineDistance","pointOne","pointTwo","toRadians","latOrLng","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","sin","cos","atan2","sqrt","createCheapRuler","lat","FE","E2","RAD","cosLat","w2","w","m","kx","ky","deltaLng","dx","dy","TerraRoute","distanceMeasurement","network","adjacencyList","Map","coords","coordMap","coordinateIndex","coord","lng","has","set","latMap","get","index","buildRouteGraph","features","geometry","coordinates","i","aIndex","bIndex","distance","getRoute","start","end","Error","startIndex","endIndex","openSetForward","openSetBackward","cameFromForward","cameFromBackward","gScoreForward","gScoreBackward","visitedForward","Set","visitedBackward","meetingNode","currentForward","add","_iterator2","_step2","_gScoreForward$get","_gScoreForward$get2","neighbor","tentativeG","Infinity","fScore","currentBackward","_step3","_iterator3","_gScoreBackward$get","_gScoreBackward$get2","pathForward","undefined","unshift","pathBackward","type","concat","properties"],"mappings":"oyBAWA,IAAaA,eAAa,WAAA,SAAAA,IAAAC,KACdC,UAAY,EACZC,KAAAA,QAA0B,IAAI,CAAA,IAAAC,EAAAJ,EAAAK,iBAAAD,EAEtCE,OAAA,SAAOC,EAAaC,GAChB,IAAMC,EAAgB,CAClBF,IAAAA,EACAC,MAAAA,EACAE,OAAQ,EACRC,MAAM,EACNC,OAAQ,KACRC,MAAO,KACPC,KAAM,KACNC,MAAO,MAEXN,EAAKK,KAAOL,EACZA,EAAKM,MAAQN,EAEbR,KAAKE,QAAUF,KAAKe,WAAWf,KAAKE,QAASM,GAC7CR,KAAKC,WACT,EAACE,EAEDa,WAAA,WACI,IAAMC,EAAIjB,KAAKE,QACf,IAAKe,EAAG,OAAW,KAGnB,GAAIA,EAAEL,MAAO,CACT,IAAIA,EAAQK,EAAEL,MACd,GACIA,EAAMD,OAAS,KACfC,EAAQA,EAAME,YACTF,IAAUK,EAAEL,OACrBZ,KAAKE,QAAUF,KAAKe,WAAWf,KAAKE,QAASe,EAAEL,MACnD,CAYA,OAVAZ,KAAKkB,eAAeD,GAEhBA,IAAMA,EAAEH,MACRd,KAAKE,QAAU,MAEfF,KAAKE,QAAUe,EAAEH,MACjBd,KAAKmB,eAGTnB,KAAKC,YACEgB,EAAEV,KACb,EAACJ,EAEDiB,KAAA,WACI,OAAOpB,KAAKC,SAChB,EAACE,EAIOgB,YAAA,WACJ,IAAME,EAAYC,KAAKC,MAAMD,KAAKE,KAAKxB,KAAKC,YAAc,EACpDwB,EAAI,IAAIC,MAAsBL,GAAWM,KAAK,MAE9CC,EAAsB,GACxBC,EAAO7B,KAAKE,QAChB,GACI0B,EAASE,KAAKD,GACdA,EAAOA,EAAKf,YACPe,IAAS7B,KAAKE,SAEvB,IAAA,IAAA6B,EAAAC,EAAAA,EAAgBJ,EAAQG,EAAAC,EAAA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AAgB1F,aAGxC,GAFAiG,EAAgBG,IAAIS,GAEhBd,EAAezB,IAAIuC,GAAkB,CACrCX,EAAcW,EACd,KACJ,CAEA,IAAA,IAAoEC,EAApEC,EAAAtF,EAAuBzC,KAAK+E,cAAcU,IAAIoC,IAAoB,MAAEC,EAAAC,KAAArF,MAAE,CAAAsF,IAAAA,EAAAC,EAA3DR,EAAQK,EAAAvH,MACTmH,GAAiDM,OAApCA,EAAClB,EAAerB,IAAIoC,IAAgBG,EAAIL,UAAYF,EAASvB,SAChF,GAAIwB,GAA+CO,OAArCA,EAAInB,EAAerB,IAAIgC,EAASjH,OAAKyH,EAAIN,UAAW,CAC9Df,EAAiBrB,IAAIkC,EAASjH,KAAMqH,GACpCf,EAAevB,IAAIkC,EAASjH,KAAMkH,GAClC,IAAME,EAASF,EAAa1H,KAAK6E,oBAAoB7E,KAAKiF,OAAOwC,EAASjH,MAAOR,KAAKiF,OAAOsB,IAC7FG,EAAgBrG,OAAOuH,EAAQH,EAASjH,KAC5C,CACJ,CACJ,CAEA,GAAoB,OAAhB0G,EACA,OAAO,KAMX,IAFA,IAAMgB,EAA0B,GAC5B1H,EAAO0G,OACKiB,IAAT3H,GACH0H,EAAYE,QAAQpI,KAAKiF,OAAOzE,IAChCA,EAAOmG,EAAgBlB,IAAIjF,GAI/B,IAAM6H,EAA2B,GAEjC,IADA7H,EAAOoG,EAAiBnB,IAAIyB,QACZiB,IAAT3H,GACH6H,EAAavG,KAAK9B,KAAKiF,OAAOzE,IAC9BA,EAAOoG,EAAiBnB,IAAIjF,GAKhC,MAAO,CACH8H,KAAM,UACNzC,SAAU,CAAEyC,KAAM,aAAcxC,YAJtB,GAAAyC,OAAOL,EAAgBG,IAKjCG,WAAY,CAAA,EAEpB,EAAC5D,CAAA,CA5KW"}
1
+ {"version":3,"file":"terra-route.module.js","sources":["../src/distance/haversine.ts","../src/distance/cheap-ruler.ts","../src/heap/min-heap.ts","../src/terra-route.ts"],"sourcesContent":["import { Position } from \"geojson\";\n\n/** Distance measured in kilometers */\nexport const haversineDistance = (pointOne: Position, pointTwo: Position): number => {\n const toRadians = (latOrLng: number) => (latOrLng * Math.PI) / 180;\n\n const phiOne = toRadians(pointOne[1]);\n const lambdaOne = toRadians(pointOne[0]);\n const phiTwo = toRadians(pointTwo[1]);\n const lambdaTwo = toRadians(pointTwo[0]);\n const deltaPhi = phiTwo - phiOne;\n const deltalambda = lambdaTwo - lambdaOne;\n\n const a =\n Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +\n Math.cos(phiOne) *\n Math.cos(phiTwo) *\n Math.sin(deltalambda / 2) *\n Math.sin(deltalambda / 2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n const radius = 6371e3;\n const distance = radius * c;\n\n return distance / 1000;\n}\n","import { Position } from \"geojson\";\n\n// This code is based on Mapbox's cheap-ruler library:\n\n// ISC License\n\n// Copyright (c) 2024, Mapbox\n\n// Permission to use, copy, modify, and/or distribute this software for any purpose\n// with or without fee is hereby granted, provided that the above copyright notice\n// and this permission notice appear in all copies.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n// THIS SOFTWARE.\n\n/**\n * Creates a function for fast geodesic distance approximation using local scaling constants\n * based on a reference latitude. Useful for city-scale distances.\n *\n * @param {number} lat - Reference latitude in degrees\n * @returns {(a: Position, b: Position) => number} - Function that computes distance between two points\n * \n * @example\n * const distance = createCheapRuler(50.5);\n * const d = distance([30.5, 50.5], [30.51, 50.49]);\n * \n */\nexport function createCheapRuler(lat: number): (a: Position, b: Position) => number {\n const RE = 6378.137; // Earth's equatorial radius in kilometers\n const FE = 1 / 298.257223563; // Earth's flattening\n const E2 = FE * (2 - FE);\n const RAD = Math.PI / 180;\n\n const cosLat = Math.cos(lat * RAD);\n const w2 = 1 / (1 - E2 * (1 - cosLat * cosLat));\n const w = Math.sqrt(w2);\n\n const m = RAD * RE;\n const kx = m * w * cosLat; // scale for longitude\n const ky = m * w * w2 * (1 - E2); // scale for latitude\n\n return function distance(a: Position, b: Position): number {\n let deltaLng = a[0] - b[0];\n\n while (deltaLng < -180) deltaLng += 360;\n while (deltaLng > 180) deltaLng -= 360;\n\n const dx = deltaLng * kx;\n const dy = (a[1] - b[1]) * ky;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n}","import { Heap } from \"./heap\";\n\nexport class MinHeap implements Heap {\n private heap: Array<{ key: number; value: number; index: number }> = [];\n private insertCounter = 0;\n\n insert(key: number, value: number): void {\n const node = { key, value, index: this.insertCounter++ };\n let currentIndex = this.heap.length;\n this.heap.push(node);\n\n while (currentIndex > 0) {\n const parentIndex = (currentIndex - 1) >>> 1;\n const parent = this.heap[parentIndex];\n\n if (\n key > parent.key ||\n (key === parent.key && node.index > parent.index)\n ) {\n break;\n }\n\n this.heap[currentIndex] = parent;\n currentIndex = parentIndex;\n }\n\n this.heap[currentIndex] = node;\n }\n\n extractMin(): number | null {\n const heap = this.heap;\n const length = heap.length;\n\n if (length === 0) {\n return null;\n }\n\n const minNode = heap[0];\n const endNode = heap.pop()!;\n\n if (length > 1) {\n heap[0] = endNode;\n this.bubbleDown(0);\n }\n\n return minNode.value;\n }\n\n size(): number {\n return this.heap.length;\n }\n\n private bubbleDown(index: number): void {\n const heap = this.heap;\n const length = heap.length;\n const node = heap[index];\n const nodeKey = node.key;\n const nodeIndex = node.index;\n\n while (true) {\n const leftChildIndex = (index << 1) + 1;\n if (leftChildIndex >= length) {\n break;\n }\n\n let smallestIndex = leftChildIndex;\n let smallest = heap[leftChildIndex];\n\n const rightChildIndex = leftChildIndex + 1;\n if (rightChildIndex < length) {\n const right = heap[rightChildIndex];\n if (\n right.key < smallest.key ||\n (right.key === smallest.key && right.index < smallest.index)\n ) {\n smallestIndex = rightChildIndex;\n smallest = right;\n }\n }\n\n if (\n smallest.key < nodeKey ||\n (smallest.key === nodeKey && smallest.index < nodeIndex)\n ) {\n heap[index] = smallest;\n index = smallestIndex;\n } else {\n break;\n }\n }\n\n heap[index] = node;\n }\n}\n","import { FeatureCollection, LineString, Point, Feature, Position } from \"geojson\";\nimport { haversineDistance } from \"./distance/haversine\";\nimport { createCheapRuler } from \"./distance/cheap-ruler\";\nimport { MinHeap } from \"./heap/min-heap\";\nimport { HeapConstructor } from \"./heap/heap\";\n\ninterface Router {\n buildRouteGraph(network: FeatureCollection<LineString>): void;\n getRoute(start: Feature<Point>, end: Feature<Point>): Feature<LineString> | null;\n}\n\nclass TerraRoute implements Router {\n private network: FeatureCollection<LineString> | null = null;\n private distanceMeasurement: (a: Position, b: Position) => number;\n private heapConstructor: HeapConstructor;\n\n // Map from longitude → (map from latitude → index)\n private coordinateIndexMap: Map<number, Map<number, number>> = new Map();\n private coordinates: Position[] = [];\n private adjacencyList: Array<Array<{ node: number; distance: number }>> = [];\n\n constructor(options?: {\n distanceMeasurement?: (a: Position, b: Position) => number;\n heap?: HeapConstructor;\n }) {\n this.distanceMeasurement = options?.distanceMeasurement ?? haversineDistance;\n this.heapConstructor = options?.heap ?? MinHeap;\n }\n\n /**\n * Converts a coordinate into a unique index. If the coordinate already exists, returns its index.\n * Otherwise, assigns a new index and stores the coordinate.\n * \n * @param coord - A GeoJSON Position array representing [longitude, latitude].\n * @returns A unique numeric index for the coordinate.\n */\n public buildRouteGraph(network: FeatureCollection<LineString>): void {\n this.network = network;\n\n // Reset everything\n this.coordinateIndexMap = new Map();\n this.coordinates = [];\n this.adjacencyList = [];\n\n // Hoist to locals for speed\n const coordIndexMapLocal = this.coordinateIndexMap;\n const coordsLocal = this.coordinates;\n const adjListLocal = this.adjacencyList;\n const measureDistance = this.distanceMeasurement;\n\n for (const feature of network.features) {\n const lineCoords = feature.geometry.coordinates;\n\n for (let i = 0; i < lineCoords.length - 1; i++) {\n const [lngA, latA] = lineCoords[i];\n const [lngB, latB] = lineCoords[i + 1];\n\n // get or assign index for A \n let latMapA = coordIndexMapLocal.get(lngA);\n if (!latMapA) {\n latMapA = new Map<number, number>();\n coordIndexMapLocal.set(lngA, latMapA);\n }\n let indexA = latMapA.get(latA);\n if (indexA === undefined) {\n indexA = coordsLocal.length;\n coordsLocal.push(lineCoords[i]);\n latMapA.set(latA, indexA);\n adjListLocal[indexA] = [];\n }\n\n // get or assign index for B \n let latMapB = coordIndexMapLocal.get(lngB);\n if (!latMapB) {\n latMapB = new Map<number, number>();\n coordIndexMapLocal.set(lngB, latMapB);\n }\n let indexB = latMapB.get(latB);\n if (indexB === undefined) {\n indexB = coordsLocal.length;\n coordsLocal.push(lineCoords[i + 1]);\n latMapB.set(latB, indexB);\n adjListLocal[indexB] = [];\n }\n\n // record the bidirectional edge \n const segmentDistance = measureDistance(lineCoords[i], lineCoords[i + 1]);\n adjListLocal[indexA].push({ node: indexB, distance: segmentDistance });\n adjListLocal[indexB].push({ node: indexA, distance: segmentDistance });\n }\n }\n }\n\n /**\n * Computes the shortest route between two points in the network using the A* algorithm.\n * \n * @param start - A GeoJSON Point Feature representing the start location.\n * @param end - A GeoJSON Point Feature representing the end location.\n * @returns A GeoJSON LineString Feature representing the shortest path, or null if no path is found.\n * \n * @throws Error if the network has not been built yet with buildRouteGraph(network).\n */\n public getRoute(\n start: Feature<Point>,\n end: Feature<Point>\n ): Feature<LineString> | null {\n if (!this.network) {\n throw new Error(\"Network not built. Please call buildRouteGraph(network) first.\");\n }\n\n // ensure start/end are in the index maps\n const startIndex = this.getOrCreateIndex(start.geometry.coordinates);\n const endIndex = this.getOrCreateIndex(end.geometry.coordinates);\n\n if (startIndex === endIndex) {\n return null;\n }\n\n const openSet = new this.heapConstructor();\n openSet.insert(0, startIndex);\n\n const nodeCount = this.coordinates.length;\n const gScore = new Array<number>(nodeCount).fill(Infinity);\n const cameFrom = new Array<number>(nodeCount).fill(-1);\n const visited = new Array<boolean>(nodeCount).fill(false);\n\n gScore[startIndex] = 0;\n\n while (openSet.size() > 0) {\n const current = openSet.extractMin()!;\n if (visited[current]) {\n continue;\n }\n if (current === endIndex) {\n break;\n }\n visited[current] = true;\n\n for (const neighbor of this.adjacencyList[current] || []) {\n const tentativeG = gScore[current] + neighbor.distance;\n if (tentativeG < gScore[neighbor.node]) {\n gScore[neighbor.node] = tentativeG;\n cameFrom[neighbor.node] = current;\n const heuristic = this.distanceMeasurement(\n this.coordinates[neighbor.node],\n this.coordinates[endIndex]\n );\n openSet.insert(tentativeG + heuristic, neighbor.node);\n }\n }\n }\n\n if (cameFrom[endIndex] < 0) {\n return null;\n }\n\n // Reconstruct path\n const path: Position[] = [];\n let current = endIndex;\n while (current !== startIndex) {\n path.unshift(this.coordinates[current]);\n current = cameFrom[current];\n }\n path.unshift(this.coordinates[startIndex]);\n\n return {\n type: \"Feature\",\n geometry: { type: \"LineString\", coordinates: path },\n properties: {},\n };\n }\n\n /**\n * Helper to index start/end in getRoute.\n */\n private getOrCreateIndex(coord: Position): number {\n const [lng, lat] = coord;\n let latMap = this.coordinateIndexMap.get(lng);\n if (!latMap) {\n latMap = new Map<number, number>();\n this.coordinateIndexMap.set(lng, latMap);\n }\n let index = latMap.get(lat);\n if (index === undefined) {\n index = this.coordinates.length;\n this.coordinates.push(coord);\n latMap.set(lat, index);\n // ensure adjacencyList covers this new node\n this.adjacencyList[index] = [];\n }\n return index;\n }\n}\n\nexport { TerraRoute, createCheapRuler, haversineDistance }"],"names":["haversineDistance","pointOne","pointTwo","toRadians","latOrLng","Math","PI","phiOne","lambdaOne","phiTwo","deltaPhi","deltalambda","a","sin","cos","atan2","sqrt","createCheapRuler","lat","FE","E2","RAD","cosLat","w2","w","m","kx","ky","b","deltaLng","dx","dy","MinHeap","heap","this","insertCounter","_proto","prototype","insert","key","value","node","index","currentIndex","length","push","parentIndex","parent","extractMin","minNode","endNode","pop","bubbleDown","size","nodeKey","nodeIndex","leftChildIndex","smallestIndex","smallest","rightChildIndex","right","TerraRoute","options","_options$distanceMeas","_options$heap","network","distanceMeasurement","heapConstructor","coordinateIndexMap","Map","coordinates","adjacencyList","buildRouteGraph","_step","coordIndexMapLocal","coordsLocal","adjListLocal","measureDistance","_iterator","_createForOfIteratorHelperLoose","features","done","lineCoords","geometry","i","_lineCoords$i","lngA","latA","_lineCoords","lngB","latB","latMapA","get","set","indexA","undefined","latMapB","indexB","segmentDistance","distance","getRoute","start","end","Error","startIndex","getOrCreateIndex","endIndex","openSet","nodeCount","gScore","Array","fill","Infinity","cameFrom","visited","current","_iterator2","_step2","neighbor","tentativeG","heuristic","path","unshift","type","properties","coord","lng","latMap"],"mappings":"oyBAGa,IAAAA,EAAoB,SAACC,EAAoBC,GAClD,IAAMC,EAAY,SAACC,GAAgB,OAAMA,EAAWC,KAAKC,GAAM,GAAG,EAE5DC,EAASJ,EAAUF,EAAS,IAC5BO,EAAYL,EAAUF,EAAS,IAC/BQ,EAASN,EAAUD,EAAS,IAE5BQ,EAAWD,EAASF,EACpBI,EAFYR,EAAUD,EAAS,IAELM,EAE1BI,EACFP,KAAKQ,IAAIH,EAAW,GAAKL,KAAKQ,IAAIH,EAAW,GAC7CL,KAAKS,IAAIP,GACTF,KAAKS,IAAIL,GACTJ,KAAKQ,IAAIF,EAAc,GACvBN,KAAKQ,IAAIF,EAAc,GAM3B,OALU,EAAIN,KAAKU,MAAMV,KAAKW,KAAKJ,GAAIP,KAAKW,KAAK,EAAIJ,IAEtC,OAGG,GACtB,ECOM,SAAUK,EAAiBC,GAC7B,IACMC,EAAK,EAAI,cACTC,EAAKD,GAAM,EAAIA,GACfE,EAAMhB,KAAKC,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