landxml/lib/util.js

73 lines
1.9 KiB
JavaScript

import randomColor from 'randomcolor';
import { polygon } from '@turf/helpers';
export function getProp(obj, ...props) {
if (props.length === 0) throw new Error("You must at least provide one property.");
const prop = props.shift();
const exists = obj.hasOwnProperty(prop);
if (props.length === 0) {
return exists ? obj[prop] : undefined;
}
if (obj[prop] === undefined) {
return undefined;
}
return getProp(obj[prop], ...props);
}
export function parseSequence(str) {
return str.replace(/\r?\n?\t?/g, '').split(' ');
}
const colors = {};
export function getColor(key, opts) {
if (key in colors) {
return colors[key];
}
const color = randomColor(opts);
colors[key] = color;
return color;
}
export function toRadians(angleInDegrees) {
return angleInDegrees * Math.PI / 180;
}
export function toDegrees(angleInRadians) {
return angleInRadians * 180 / Math.PI;
}
export function circleToPolygon(center, radius, numberOfSegments, properties) {
const n = numberOfSegments ? numberOfSegments : 32;
const flatCoordinates = [];
const coordinates = [];
for (var i = 0; i < n; ++i) {
flatCoordinates.push(...offset(center, radius, 2 * Math.PI * i / n));
}
flatCoordinates.push(flatCoordinates[0], flatCoordinates[1]);
for (let i = 0, j = 0; j < flatCoordinates.length; j += 2) {
coordinates[i++] = flatCoordinates.slice(j, j + 2);
}
return polygon([coordinates.reverse()], properties);
};
export function offset(c1, distance, bearing) {
const lat1 = toRadians(c1[1]);
const lon1 = toRadians(c1[0]);
const dByR = distance / 6378137; // distance divided by 6378137 (radius of the earth) wgs84
const lat = Math.asin(
Math.sin(lat1) * Math.cos(dByR) +
Math.cos(lat1) * Math.sin(dByR) * Math.cos(bearing));
const lon = lon1 + Math.atan2(
Math.sin(bearing) * Math.sin(dByR) * Math.cos(lat1),
Math.cos(dByR) - Math.sin(lat1) * Math.sin(lat));
return [toDegrees(lon), toDegrees(lat)];
}