Files
nodeMap/utils/geometryUtils.js

37 lines
1.4 KiB
JavaScript

// utils/geometryUtils.js
/**
* Parses a point string in the format "POINT (longitude latitude)" and returns an object with latitude and longitude as numbers.
* @param {string} position - The position string in the format "POINT (longitude latitude)".
* @returns {{latitude: number, longitude: number}} An object containing the latitude and longitude as numbers.
*/
export const parsePoint = (position) => {
const [longitude, latitude] = position.slice(6, -1).split(" ");
return { latitude: parseFloat(latitude), longitude: parseFloat(longitude) };
};
/**
* Finds the closest points on a polyline to a new point.
* @param {Array} coordinates - The coordinates of the polyline.
* @param {Object} newPoint - The new point (with latitude and longitude).
* @param {Object} map - The map object.
* @returns {Array} The closest pair of points on the polyline.
*/
export const findClosestPoints = (coordinates, newPoint, map) => {
if (!map) {
console.error("Map is not defined. Cannot find closest points.");
return [];
}
let minDist = Infinity;
let closestPair = [];
for (let i = 1; i < coordinates.length; i++) {
const dist = L.LineUtil.pointToSegmentDistance(map.latLngToLayerPoint(newPoint), map.latLngToLayerPoint(coordinates[i - 1]), map.latLngToLayerPoint(coordinates[i]));
if (dist < minDist) {
minDist = dist;
closestPair = [coordinates[i - 1], coordinates[i], i];
}
}
return closestPair;
};