GithubHelp home page GithubHelp logo

vgavara / haversine-ts Goto Github PK

View Code? Open in Web Editor NEW
0.0 1.0 0.0 440 KB

Typescript library for calculations on a sphere surface with both decimal degrees (DD) or degrees minutes seconds (DMS) coordinates.

License: MIT License

Shell 0.26% JavaScript 0.21% TypeScript 99.53%
decimal-degrees degrees-minutes-seconds haversine bearing-calculations distance-calculation point-calculation sphere-surface typescript

haversine-ts's Introduction

haversine-ts

GitHub release (latest SemVer) License:

About

Typescript library for distance calculation on a sphere surface with both decimal degrees (DD) or degrees minutes seconds (DMS) coordinates.

Main package features:

  • Allows calculating distances between to points in metres, kilometres or miles.
  • Allows using decimal degree (DD) or degrees minutes seconds (DMS) coordinates.
  • Allows calculating start and end bearings of a path between two points.
  • Allows calculating the end point of a path given its start point, start bearing and distance.

At a glance

Calculate the distance, in kilometres, between two decimal degrees coordinates

import { DDPoint, Haversine } from "haversine-ts";

// New York decimal degrees (DD) coordinates are:
// latitude 40.730610 N,
// longitude 73.935242 W
const newYork = new DDPoint(40.73061, -73.935242);

// Madrid decimal degrees (DD) coordinates are:
// latitude 40.416775 N,
// longitude 3.703790 W
const madrid = new DDPoint(40.416775, -3.70379);

const haversine = new Haversine();
const distance = haversine.getDistance(newYork, madrid);

console.log(`The distance from New York to Madrid is ${distance} kilometres.`);

Calculate the distance, in miles, between two degrees minutes seconds (DMS) coordinates

import {
  DMSCoordinate,
  DMSPoint,
  Haversine,
  UnitOfDistance
} from "haversine-ts";

// New York DMS coordinates are
// latitude 40° 43' 50.1960'' N,
// longitude 73° 56' 6.8712'' W
const newYork = new DMSPoint(
  new DMSCoordinate(40, 43, 50.196),
  new DMSCoordinate(-73, 56, 6.8712)
);

// Madrid DMS coordinates are
// latitude 40° 25' 0.3900'' N,
// longitude 3° 42' 13.6440'' W
const madrid = new DMSPoint(
  new DMSCoordinate(40, 25, 0.39),
  new DMSCoordinate(-3, 42, 13.644)
);

const haversine = new Haversine(UnitOfDistance.Mile);
const distance = haversine.getDistance(newYork.toDDPoint(), madrid.toDDPoint());

console.log(`The distance from New York to Madrid is ${distance} miles.`);

Calculate the bearing between two points

import { DDPoint, Haversine } from "haversine-ts";

const newYork = new DDPoint(40.73061, -73.935242);
const madrid = new DDPoint(40.416775, -3.70379);

const haversine = new Haversine();
const bearing = haversine.getBearing(newYork, madrid);

console.log(
  `The start bearing of the path from New York to Madrid is ${bearing.start} degrees, and the end bearing is ${bearing.end} degrees.`
);

Calculate the endpoint of a path

import { DDPoint, Haversine } from "haversine-ts";

const newYork = new DDPoint(40.73061, -73.935242);
const bearing = 65.71472;
const distance = 5762;

const haversine = new Haversine();
const madrid = haversine.getPoint(newYork, bearing, distance);

console.log(
  `Madrid is the endpoint of the path starting in New York with a bearing of ${bearing} degrees at a distance of ${distance} kilometers`
);

Installation

To install the package using nmp simply run this command in the root folder of your node project:

npm install haversine-ts

Usage

Overview

The Haversine class supports the implementation of the sphere path resolvers (distance and bearing between two points, end point given start point, bearing and distance).

It uses as input decimal degrees (DD) coordinates defined as DDPoint class object instances, that can be converted into degrees minutes seconds (DMS) coordinates as instances of the DMSPoint class. Each DMSPoint object instance is composed by two DMSCoordinate class object instances.

The SphereBearing class represents a tuple with the start and end bearings of a sphere path (orthodrome) between two points.

DDPoint class

Sphere point defined by a latitude and a longitude in decimal degrees (DD)

new DDPoint(latitude, longitude)

Creates a sphere point object instance.

import { DDPoint } from "haversine-ts";

const newYork = new DDPoint(40.73061, -73.935242);

console.log(
  `The coordinates of New York, in decimal notation, are latitude ${newYork.latitude}, longitude ${newYork.longitude}`
);

ddPoint.latitude ⇒ number

Returns the point latitude set in the object instance constructor.

ddPoint.longitude ⇒ number

Returns the point longitude set in the object instance constructor.

ddPoint.toDMSPoint() ⇒ DMSPoint

Gets the equivalent point in degrees minutes seconds (DMS) notation.

import { DDPoint } from "haversine-ts";

const newYork = new DDPoint(40.73061, -73.935242);
const newYorkDMS = newYork.toDMSPoint();

console.log(
  `The coordinates of New York, in DMS notation, are ${newYorkDMS.degrees} degrees, ${newYorkDMS.minutes} minutes, ${newYorkDMS.seconds} seconds`
);
  • Returns:
    • DMSPoint - Equivalent sphere point defined in degrees minutes seconds (DMS) notation

DMSCoordinate

Latitude/Longitude coordinate defined in degrees minutes seconds (DMS).

new DMSCoordinate(degrees, minutes, seconds)

Initializes a DMSCoordinate object instance.

import { DMSCoordinate } from "haversine-ts";

const newYorkLatitude = new DMSCoordinate(40, 43, 50.196);

console.log(
  `The New York latitude, in DMS notation, is ${newYorkLatitude.degrees} degrees, ${newYorkLatitude.minutes} minutes, ${newYorkLatitude.seconds} seconds,`
);
  • Parameters
    • degrees (number): Coordinate degrees, from -180 to 180.
    • minutes (number): Coordinate minutes, from 0 to <60.
    • seconds (number): Coordinate seconds, from 0 to <60.
  • Throws:
    • Error if degrees, minutes or seconds are out of range.

dmsCoordinate.degrees ⇒ number

Returns the coordinate degrees set in the constructor.

dmsCoordinate.minutes ⇒ number

Returns the coordinate minutes set in the constructor.

dmsCoordinate.seconds ⇒ number

Returns the coordinate seconds set in the constructor.

DMSPoint class

Sphere point defined by a latitude and a longitude in degrees minutes seconds (DMS).

new DMSPoint(latitude, longitude)

Creates a sphere point object instance in DMS notation.

import { DMSPoint } from "haversine-ts";

const newYork = new DMSPoint(
  new DMSCoordinate(40, 43, 50.196),
  new DMSCoordinate(-73, 56, 6.8712)
);

const newYorkLatitude = newYork.latitude;
const newYorkLongitude = newYork.longitude;

console.log(
  `The New York coordinates, in DMS notation, are latitude ${newYorkLatitude.degrees} degrees ${newYorkLatitude.minutes} minutes, ${newYorkLatitude.seconds} seconds, longitude ${newYorkLongitude.degrees} degrees ${newYorkLongitude.minutes} minutes, ${newYorkLongitude.seconds} seconds`
);
  • Parameters
    • latitude (DMSCoordinate): Latitude coordinate in degrees minutes seconds.
    • longitude (DMSCoordinate): Longitude coordinate in degrees minutes seconds.
  • Throws:
    • Error if latitude degrees are out of range (-90 to 90).

dmsPoint.latitude ⇒ DMSCoordinate

Returns the point latitude set in the constructor.

dmsPoint.longitude ⇒ DMSCoordinate

Returns the point longitude set in the constructor.

dmsPoint.toDDPoint() ⇒ DDPoint

Gets the equivalent point in decimal degrees notation.

import { DMSPoint } from "haversine-ts";

const newYork = new DMSPoint(
  new DMSCoordinate(40, 43, 50.196),
  new DMSCoordinate(-73, 56, 6.8712)
);
const newYorkDD = newYork.toDDPoint();

console.log(
  `The coordinates of New York, in DD notation, are latitude ${newYorkDD.latitude}, longitude ${newYorkDD.longitude}`
);
  • Returns:
    • DDPoint - Equivalent sphere point defined in decimal degrees (DD) notation.

Haversine class

Haversine formula resolver.

new Haversine([uod], [sphereRadius])

Initializes the Haversine resolver.

import { Haversine, UnitOfDistance } from "haversine-ts";

const haversine = new Haversine(UnitOfDistance.Mile);
  • Parameters:
    • uod (UnitOfDistance, optional): Unit of distance (default: UnitOfDistance.Kilometre)
    • sphereRadius (number, optional): Custom sphere radius in uod units (default: equatorial Earth radius).

haversine.getBearing(startPoint, endPoint) ⇒ SphereBearing

Calculates the sphere bearing, or start and end bearings, of the path between two points in a sphere.

import { DDPoint, Haversine } from "haversine-ts";

const newYork = new DDPoint(40.73061, -73.935242);
const madrid = new DDPoint(40.416775, -3.70379);

const haversine = new Haversine();
const bearing = haversine.getBearing(newYork, madrid);

console.log(
  `The start bearing of the path from New York to Madrid is ${bearing.start} degrees, and the end bearing is ${bearing.end} degrees.`
);
  • Parameters:
    • startPoint (DDPoint): Start point, in decimal degrees coordinates.
    • endPoint (DDPoint): End point, in decimal degrees coordinates.
  • Returns:
    • SphereBearing - Bearings of the path from startPoint to endPoint, in degrees (0 to 360, clockwise from North).

haversine.getDistance(pointA, pointB) ⇒ number

Calculates the distance between to sphere points defined as decimal degrees (DD) coordinates.

import { DDPoint, Haversine } from "haversine-ts";

const newYork = new DDPoint(40.73061, -73.935242);
const madrid = new DDPoint(40.416775, -3.70379);

const haversine = new Haversine();

const distance = haversine.getDistance(newYork, madrid);

console.log(`The distance from New York to Madrid is ${distance} kilometres.`);
  • Parameters:
    • pointA (DDPoint): Point A, in decimal degrees coordinates.
    • pointB (DDPoint): Point B, in decimal degrees coordinates.
  • Returns:
    • number - Distance between the points, in the unit of distance set in the class constructor.

haversine.getPoint(startPoint, bearing, distance) ⇒ DDPoint

Calculates the coordinates of the end point of a path given its start point, start bearing and distance.

import { DDPoint, Haversine } from "haversine-ts";

const newYork = new DDPoint(40.73061, -73.935242);
const bearing = 65.71472;
const distance = 5762;

const haversine = new Haversine();
const madrid = haversine.getPoint(newYork, bearing, distance);

console.log(
  `Madrid is the endpoint of the path starting in New York with a bearing of ${bearing} degrees at a distance of ${distance} kilometers`
);
  • Parameters:
    • startPoint (DDPoint): Start point, in decimal degrees coordinates.
    • bearing (number): Bearing to the end point, in degrees (0 to 360, clockwise from North).
    • distance (number): Distance from the start point to the targetted point, using as unit of measure that set in the class constructor (metres, kilometres or miles).
  • Returns:.
    • DDPoint - End point, in decimal degrees coordinates.

SphereBearing

Sphere bearing as a tuple of start and end bearings of a sphere path (orthodrome) between two points.

new SphereBearing(start, end)

Initializes a sphere bearing object instance.

import { SphereBearing } from "haversine-ts";

const bearing = new SphereBearing(60.5, 181);

console.log(
  `The start bearing of the path from A to B is ${bearing.start} degrees, and the end bearing is ${bearing.end} degrees.`
);
  • Parameters
    • start (number): Start bearing, from 0 to <360 clockwise from North.
    • end (number): End bearing, from 0 to <360 clockwise from North.
  • Throws:
    • Error if start or end bearings are out of range.

sphereBearing.start ⇒ number

Start bearing set in the constructor.

sphereBearing.end ⇒ number

End bearing set in the constructor.

UnitOfDistance enum

Enum Value Description
Metre 0 Distance in metres
Kilometre 1 Distance in kilometres
Mile 2 Distance in miles

Support

In order to notify some problem or suggest an improvement or new feature, submit an issue in the GitHub repository issues section.

License

This package is licensed under the MIT terms of use.

Contact

You can contact the package creator via email, GitHub or LinkedIn.

haversine-ts's People

Contributors

renovate[bot] avatar vgavara avatar

Watchers

 avatar

haversine-ts's Issues

Improve the README.md documentation structure

Perform these operations in README.md:

  • Add npm, release and license badges
  • Move the current heading information to a subsection called "About"
  • Keep the current "At a glance" section but convert it into subseciton
  • Create a subsection called "Installation"
  • Create a subsection called "Usage" describing in detail each class
  • Create a subsection called "Support" with a link to the repository issues
  • Create a subsection called "License" including a link to the MIT
  • Create a subsection called "Contact" with the repo owner email and a link to GitHub and LinkedIn.

Support searching points in a given radio

Add Haversine class a method (getInRange?) to find those points that are in a given distance range from a reference point:

havesine.getInRange(referencePoint: DDPoint, points: DDPoint[], distance: number) => DDPoint[]

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • Update dependency eslint to v8.57.0
  • Update dependency prettier to v3.2.5
  • Update dependency prettier-plugin-jsdoc to v1.3.0
  • Update dependency @typescript-eslint/eslint-plugin to v7
  • Update dependency chai to v5
  • Update dependency eslint to v9
  • Update dependency husky to v9
  • Update dependency sinon to v18
  • 🔐 Create all rate-limited PRs at once 🔐

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/pull-request.yml
  • actions/checkout v4
  • actions/setup-node v3
.github/workflows/release.yml
  • actions/checkout v4
  • actions/setup-node v3
npm
package.json
  • @types/chai ^4.3.4
  • @types/mocha ^10.0.0
  • @types/sinon ^10.0.13
  • @typescript-eslint/eslint-plugin ^6.0.0
  • chai ^4.3.7
  • eslint ^8.28.0
  • eslint-config-prettier ^8.5.0
  • eslint-plugin-prettier ^5.0.0
  • husky ^8.0.2
  • lint-staged ^13.0.4
  • mocha ^10.1.0
  • prettier ^3.0.0
  • prettier-plugin-jsdoc ^1.0.0
  • sinon ^16.0.0
  • ts-node ^10.9.1
  • tsconfig-paths ^4.1.0
  • typescript ^4.9.3

  • Check this box to trigger a request for Renovate to run again on this repository

Add support to GitHub PR workflow

Create a GitHub workflow to be run when a PR to master/stable branches was created.
The workflow must build the project and run the tests

Support finding the nearest/farthest point to a reference one

Add Haversine class a method to find the nearest/farthest point of a list of points to a given reference point:

havesine.getNearest(referencePoint: DDPoint, points: DDPoint[]) => DDPoint
havesine.getFarthest(referencePoint: DDPoint, points: DDPoint[]) => DDPoint

Create haversine class with basic features

Create a Haversine static class supporting the calculation of the distance between two points.
Also create the Point class addressed to hold a sphere point latitude and longitude.

Give support to NPM integration

Add required files, actions and secrets to allow an automatic deployment to NPM once a pull request was merged on branch stable and tagged.

Create repository base

Create the file set needed for developing a typescript library able to be uploaded to NPM as package. The library must contain:

  • Support to linter and prettier, including jsdoc-prettier, on commiting
  • Support to unit tests

Support calculation of a destination point given a source point, bearing and distance

Add Haversine class a new method for calculating the coordinates of a destination point given a source point, a bearing and a distance.

Add suitable unit tests and update the documentation accordingly.

Sample:

  /**
   * Calculates the coordinates of a point given an start point, a distance and
   * a bearing
   *
   * @param {DDPoint} startPoint - Start point, in decimal degrees coordinates.
   * @param {number} distance - Distance from the start point to the targetted
   *   point, using as unit of measure that set in the class constructor
   *   (metres, kilometres or miles).
   * @param {number} bearing Bearing to the targetted point, in degrees (0 to
   *   360, clockwise from North).
   */
  getPoint(startPoint: DDPoint, distance: number, bearing: number): DDPoint {
    if (distance < 0)
      throw new Error("Distance out of range: Must be equal of higher than 0");
    if (bearing < 0 || bearing >= 360)
      throw new Error("Bearing out of range: Must be between 0 and < 360");

    const startLatitude = toRadians(startPoint.latitude);
    const startLongitude = toRadians(startPoint.longitude);
    const angularDistance = distance / this.sphereRadius;

    const targetLatitude = Math.asin(
      Math.sin(startLatitude) * Math.cos(angularDistance) +
        Math.cos(startLatitude) * Math.sin(angularDistance) * Math.cos(bearing)
    );
    const targetLongitude =
      startLongitude +
      Math.atan2(
        Math.sin(bearing) * Math.sin(angularDistance) * Math.cos(startLatitude),
        Math.cos(angularDistance) -
          Math.sin(startLatitude) * Math.sin(targetLatitude)
      );

    return new DDPoint(targetLatitude, targetLongitude);
  }

Fix coordinates range check

Coordinates range check must be fixed to validate that latitude ranges from -90 to 90 instead of -180 to 180.

This fix must be performed in both DD and DMS point classes

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.