npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

angular-haversine-geolocation

v1.0.2

Published

Angular 20 service for geolocation history management (Haversine)

Readme

npm downloads

angular-haversine-geolocation

An Angular 20 service (Web & Standalone Components) to manage a geolocation history, using the Haversine formula to filter out nearby points and optimize tracking.


angular-haversine-geolocation demo


🚀 Installation

npm install angular-haversine-geolocation

or with yarn:

yarn add angular-haversine-geolocation

✨ Features

  • 📍 Calculate distances in meters using the Haversine formula

  • 🔄 Manage a geolocation history

  • 🎯 Automatically filter out points that are too close to the previous one

  • 💾 Flexible persistence (via localStorage, IndexedDB, APIs, etc.)

  • 🪶 Compatible with Angular 20 (Web & Standalone Components)


🖥️ Live demo :

https://angular-haversine-goelocation-test.netlify.app/


🔧 Example Usage

import { Component, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import {
  GeolocationManagerService,
  TLocation,
  TLocationHistory,
  provideGeolocationManager,
} from 'angular-haversine-geolocation';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <h1>Location History</h1>

    <ul>
      <li *ngFor="let loc of history().locations">
        Latitude: {{ loc.coords.latitude }}, Longitude: {{ loc.coords.longitude }} - Time:
        {{ getFormattedTimestamp(loc.timestamp) }}
      </li>
    </ul>

    <h2>Add a Position Manually</h2>
    <label>
      Latitude:
      <input type="number" [(ngModel)]="latitude" step="0.0001" />
    </label>
    <label>
      Longitude:
      <input type="number" [(ngModel)]="longitude" step="0.0001" />
    </label>
    <button [disabled]="!initialized" (click)="addManualLocation()">Add Position</button>
  `,
  providers: [
    provideGeolocationManager({
      distanceThreshold: 50,
      loadHistory: async () => JSON.parse(localStorage.getItem('geo-history') || 'null'),
      saveHistory: async (h) => localStorage.setItem('geo-history', JSON.stringify(h)),
    }),
  ],
})
export class AppComponent {
  private geo = inject(GeolocationManagerService);

  history = signal<TLocationHistory>({ locations: [] });

  // Inputs for coordinates
  latitude = 48.8566;
  longitude = 2.3522;

  // Flag to know if init() is completed
  initialized = false;

  constructor() {
    this.init();
  }

  private async init() {
    // Initialize the service and retrieve existing history
    await this.geo.init();
    this.geo.history$.subscribe((h) => this.history.set(h));
    this.initialized = true;
  }

  async addManualLocation() {
    // Create a new location with the current timestamp
    const newLocation: TLocation = {
      coords: {
        accuracy: 5,
        altitude: 10,
        altitudeAccuracy: 1,
        heading: 0,
        latitude: this.latitude,
        longitude: this.longitude,
        speed: 0,
      },
      mocked: false,
      timestamp: Date.now(),
    };

    // Add the location via the service with await for persistence
    await this.geo.addLocation(newLocation);
  }

  getFormattedTimestamp(ts: number): string {
    // Convert to local string taking into account the user's timezone
    return new Date(ts).toLocaleString();
  }
}

📖 API

GeolocationManagerService

Methods

  • history$ → Observable

  • historySnapshot → TLocationHistory

  • init(customOptions?: Partial) → Promise

  • addLocation(location: TLocation) → Promise

  • provideGeolocationManager(options: Partial)

  • distanceThreshold?: number → Threshold in meters to consider two positions the same (default: 100)

  • loadHistory: () => Promise<TLocationHistory | null> → Function to load history

  • saveHistory: (history: TLocationHistory) => Promise → Function to save history


🧩 Types

TLocation

export type TLocation = {
  coords: {
    accuracy: number;
    altitude: number;
    altitudeAccuracy: number;
    heading: number;
    latitude: number;
    longitude: number;
    speed: number;
  };
  mocked: boolean;
  timestamp: number;
};

TLocationHistory

export type TLocationHistory = {
  locations: TLocation[];
};

GeolocationOptions

export type GeolocationOptions = {
  distanceThreshold?: number;
  loadHistory: () => Promise<TLocationHistory | null>;
  saveHistory: (history: TLocationHistory) => Promise<void>;
};

📐 Distance Calculation (Haversine)

The distance between two GPS points is calculated using the Haversine formula, which determines the great-circle distance between two points on a sphere using their latitude and longitude.

Haversine formula

This formula is useful for:

Filtering out GPS points that are too close to each other.

Reducing noise in location tracking.

Optimizing storage and performance by avoiding redundant points.

Function signature:

getDistanceInMeters(lat1, lon1, lat2, lon2): number

Example

import { getDistanceInMeters } from 'angular-haversine-geolocation';
const distance = getDistanceInMeters(48.8566, 2.3522, 40.7128, -74.006);
console.log(`Distance: ${distance.toFixed(2)} meters`);

📜 License

MIT