Skip to main content

Overview

The Point class represents a geographic coordinate on Earth using latitude and longitude. It provides distance calculation between two points using the Haversine formula.

Constructor

new Point(latitude, longitude)

Parameters

latitude
number
required
The latitude coordinate in decimal degrees (-90 to 90)
longitude
number
required
The longitude coordinate in decimal degrees (-180 to 180)

Example

const point1 = new Point(40.7128, -74.0060); // New York City
const point2 = new Point(34.0522, -118.2437); // Los Angeles

Methods

distance()

Calculates the great-circle distance between two points using the Haversine formula.
point.distance(otherPoint)

Parameters

otherPoint
Point
required
Another Point instance to calculate the distance to

Returns

distance
number
The distance between the two points in kilometers

Implementation

The distance calculation uses the Haversine formula, which determines the great-circle distance between two points on a sphere given their longitudes and latitudes.
distance(point){
    const R = 6371; // Radius of the earth in km
    const dLat = (point.latitude-this.latitude) * (Math.PI/180)  // deg2rad below
    const dLon = (point.longitude-this.longitude) * (Math.PI/180) 
    const a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(this.latitude * (Math.PI/180)) * Math.cos( point.latitude * (Math.PI/180)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ; 
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    const d = R * c; // Distance in km
    return d;
}
The Earth’s radius is approximated as 6371 km in this implementation. This provides sufficient accuracy for most terrestrial applications.

Example

const start = new Point(40.7128, -74.0060);
const destination = new Point(40.7580, -73.9855);

const distanceInKm = start.distance(destination);
console.log(`Distance: ${distanceInKm.toFixed(2)} km`);
// Output: Distance: 5.48 km

Constants

Earth Radius

The Haversine formula uses the Earth’s mean radius:
const R = 6371; // Radius of the earth in km
This constant represents the average radius of Earth in kilometers and is used to convert the angular distance (in radians) to linear distance (in kilometers).

Use Cases

The Point class is used throughout the route-finding algorithm for:
  • Representing start and destination coordinates
  • Calculating walking distances to nearby bus stops
  • Determining if a stop is within walking range (maxWalkKm)
  • Measuring the remaining distance to the destination
The Haversine formula provides good accuracy for distances up to a few hundred kilometers. For longer distances or higher precision requirements, more sophisticated geodesic formulas like Vincenty’s formula may be preferred.

Build docs developers (and LLMs) love