Created
May 31, 2024 15:36
-
-
Save sithumonline/f1ff25b0fbeda4a3bee900edd201da16 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const kdbush = require('kdbush'); | |
| const geokdbush = require('geokdbush'); | |
| const haversine = require('haversine-distance'); | |
| // Example train track points as 2D vectors (longitude, latitude) | |
| let track_points = [ | |
| [longitude1, latitude1], | |
| [longitude2, latitude2], | |
| //... | |
| ]; | |
| // Function to convert degrees to radians | |
| function convert_to_radians(points) { | |
| return points.map(([longitude, latitude]) => [ | |
| (longitude * Math.PI) / 180, | |
| (latitude * Math.PI) / 180, | |
| ]); | |
| } | |
| // Convert track points to radians | |
| track_points = convert_to_radians(track_points); | |
| // Build KDTree | |
| let tree = kdbush(track_points); | |
| // Function to find nearest track point for each person | |
| function find_nearest_track_points(person_locations, track_tree) { | |
| person_locations = convert_to_radians(person_locations); // Convert to radians | |
| let nearest_points = []; | |
| let distances = []; | |
| person_locations.forEach((location) => { | |
| const nearest = geokdbush.around(track_tree, location[0], location[1], 1); | |
| nearest_points.push(nearest[0]); | |
| distances.push(haversine(location, nearest[0])); // Convert distance from radians to kilometers | |
| }); | |
| return [nearest_points, distances]; | |
| } | |
| // Example person locations as 2D vectors (longitude, latitude) | |
| let person_locations = [ | |
| [longitude_of_person1, latitude_of_person1], | |
| [longitude_of_person2, latitude_of_person2], | |
| //... | |
| ]; | |
| // Find nearest points and distances | |
| let [nearest_points, distances] = find_nearest_track_points(person_locations, tree); | |
| // Output results | |
| nearest_points.forEach((point, i) => { | |
| console.log(`Person ${i+1} nearest track point is ${point} with distance ${distances[i].toFixed(2)} km.`); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment