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 🙏

© 2024 – Pkg Stats / Ryan Hefner

nodejs-geolocation

v2.3.0

Published

NodeJS library that simplifies geolocation and related calculations.

Downloads

7,021

Readme

nodejs-geolocation is a Node.js library that bundles all the most important geolocation tools and services, simplifying geolocation tasks and calculations.

npm version install size GitHub GitHub last commit

Supported Providers

nodejs-geolocation supports the following IP geolocation providers:

nodejs-geolocation supports the following geocoding providers:

Installation

You can install this library with npm:

npm install nodejs-geolocation

Loading and configuration

nodejs-geolocation supports both CommonJS and ES Modules.

ES Modules / TypeScript (recommended)

import NodeGeolocation from 'nodejs-geolocation';

const geo = new NodeGeolocation('<ApplicationName>');

CommonJS

const NodeGeolocation = require('nodejs-geolocation').default;

const geo = new NodeGeolocation('<ApplicationName>');

Usage

Get geolocation data from IP address

nodejs-geolocation supports IPInfo and IP2Location as geolocation providers. The examples are written in TypeScript, but the same methods are available in JavaScript.

IPInfo Get your API key

import NodeGeolocation from 'nodejs-geolocation';

const geo = new NodeGeolocation('MyApp');

// Set ipGeolocationOptions
geo.ipGeolocationOptions = {
    service: 'ipinfo',
    key: 'mySecretApiKeyFromIPInfo'
};

// Get geolocation data from IP address
geo.getLocation('111.6.105.201')
    .then((data) => {
        console.log(data);
    })
    .catch((err) => {
        console.log(err);
    });

IP2Location Get your API key

import NodeGeolocation from 'nodejs-geolocation';

const geo = new NodeGeolocation('MyApp');

// Set ipGeolocationOptions
geo.ipGeolocationOptions = {
    service: 'ip2location',
    key: 'mySecretApiKeyFromIP2Location'
};

// Get geolocation data from IP address
geo.getLocation('111.6.105.201')
    .then((data) => {
        console.log(data);
    })
    .catch((err) => {
        console.log(err);
    });

Result data

The result data is automatically formatted in a standard format, regardless of the provider used.

{
    ip: string;
    city: string;
    region: string;
    countryCode: string;
    timezone: string;
    position: {
        lat: number;
        lon: number;
    }
    org: string;
    asn: string;
    postal: string;
    raw: any; // Raw data from provider for advanced usage
}

Get geocoding data from address

nodejs-geolocation supports OpenStreetMap Nominatim API and Here Location API as geocoding provider.

OpenStreetMap Nominatim API

import NodeGeolocation from 'nodejs-geolocation';

const geo = new NodeGeolocation('MyApp');

// Set geocodingOptions
geo.geocodingOptions = {
    service: 'Nominatim',
    key: '' // Not required
};

// Get geocoding data from address
geo.getGeocoding('Rome, Italy')
    .then((data) => {
        console.log(data);
    })
    .catch((err) => {
        console.log(err);
    });

Here Location API Get your API key

import NodeGeolocation from 'nodejs-geolocation';

const geo = new NodeGeolocation('MyApp');

// Set geocodingOptions
geo.geocodingOptions = {
    service: 'Here',
    key: 'mySecretApiKeyFromHere'
};

// Get geocoding data from address
geo.getGeocoding('Rome, Italy')
    .then((data) => {
        console.log(data);
    })
    .catch((err) => {
        console.log(err);
    });

Result data

The result data is automatically formatted in a standard format, regardless of the provider used.

{
    id: string;
    position: {
        lat: number;
        lon: number;
    }
    address: {
        city: string;
        county: string;
        state: string;
        country: string;
        countryCode: string;
    }
    displayName: string;
    boundingBox: {
        north: number;
        south: number;
        east: number;
        west: number;
    }
    raw: any; // Raw data from provider for advanced usage
}

Get reverse geocoding data from coordinates

nodejs-geolocation supports OpenStreetMap Nominatim API and Here Location API as reverse geocoding provider.

OpenStreetMap Nominatim API

import NodeGeolocation from 'nodejs-geolocation';

const geo = new NodeGeolocation('MyApp');

// Set geocodingOptions
geo.geocodingOptions = {
    service: 'Nominatim',
    key: '' // Not required
};

const position = { lat: 41.8933203, lon: 12.4829321 };

// Get reverse geocoding data from coordinates
geo.getReverseGeocoding(position)
    .then((data) => {
        console.log(data);
    })
    .catch((err) => {
        console.log(err);
    });

Here Location API Get your API key

import NodeGeolocation from 'nodejs-geolocation';

const geo = new NodeGeolocation('MyApp');

// Set geocodingOptions
geo.geocodingOptions = {
    service: 'Here',
    key: 'mySecretApiKeyFromHere'
};

const position = { lat: 41.8933203, lon: 12.4829321 };

// Get reverse geocoding data from coordinates
geo.getReverseGeocoding(position)
    .then((data) => {
        console.log(data);
    })
    .catch((err) => {
        console.log(err);
    });

Result data

The result data of reverse geocoding is not formatted by nodejs-geolocation for more accuracy and flexibility. The result data is the raw data from the provider used.

Geofencing

nodejs-geolocation has a built-in geofencing system that allows you to check if a point is inside a polygon.

import { Geofencing } from 'nodejs-geolocation';

const geofencing = new Geofencing();

// Add a geofence
// addGeofence(id: string, position: Position, radius: number, metadataObject?: any)
geofencing.addGeofence('home', { lat: 40.7128, lon: -74.006 }, 1000, { description: 'Home sweet home' });

// Check if a point is inside a geofence
// isInsideGeofence(id: string, position: Position)
const isInside = geofencing.isInsideGeofence('home', { lat: 40.7128, lon: -74.006 });

console.log(isInside); // true

// Get all geofences
const geofences = geofencing.getGeofences();

// Remove a geofence
// removeGeofence(id: string)
geofencing.removeGeofence('home');

// Remove all geofences
geofencing.clearGeofences();

You can even use the geofencing system with events. With the updateLocation() method, you can update the position of an object and if that enters or leaves a geofence, an event will be triggered.

import { Geofencing } from 'nodejs-geolcation';

const geofencing = new Geofencing();

// Add a geofence
geofencing.addGeofence('home', { lat: 40.7128, lon: -74.006 }, 1000, { description: 'Home sweet home' });

// Add the event listeners
geofencing.on('enter', (geofence) => {
    console.log(`Entered geofence ${geofence.id}`);
});

geofencing.on('exit', (geofence) => {
    console.log(`Exited geofence ${geofence.id}`);
});

// Update location method
// updateLocation(position: Position)
geofencing.updateLocation({ latitude: 40.712, longitude: -74.0065 }); // trigger 'enter' event for geofence 'home'

Get distance between two points

nodejs-geolocation uses the Haversine formula to calculate the distance between two points on earth, based on their coordinates.

import NodeGeolocation from 'nodejs-geolocation';

const geo = new NodeGeolocation('MyApp');

/**
 * Accepted position formats:
 * { lat: number, lon: number }
 * { latitude: number, longitude: number }
 * { x: number, y: number }
 */

// Rome, Italy
const pos1 = { lat: 41.902782, lon: 12.496366 };
// Tokyo, Japan
const pos2 = { latitude: 35.685013, longitude: 139.7514 };

const distance = geo.calculateDistance(pos1, pos2);
console.log(distance); // 9857

/**
 * Options object
 * unit?: 'km' | 'yd' | 'mi' | 'm' | 'ft'
 * format?: boolean
 * exact?: boolean
 */
// Result:

console.log(geo.calculateDistance(pos1, pos2, { unit: 'mi' })); // 6125

console.log(geo.calculateDistance(pos1, pos2, { format: true })); // "9857 kilometers"

console.log(geo.calculateDistance(pos1, pos2, { unit: 'mi', exact: true })); // 6124.860370167203

Timezone converter

Converting timezones is usually tough, but nodejs-geolocation makes it easy with an integrated timezone converter.

import NodeGeolocation from 'nodejs-geolocation';

const geo = new NodeGeolocation('MyApp');

const from = 'PST';
const to = 'UTC+3';
const datePST = new Date('2022-01-01T00:00:00Z');

const dateUTC3 = geo.timeZoneConvert(date, from, to);

console.log(dateUTC3.toISOString()); // "2022-01-01T11:00:00.000Z"

Timezone type (Supported formats)

type Timezone =
  | 'GMT'
  | 'UTC'
  | `UTC${'+' | '-'}${number}`
  | `UTC${'+' | '-'}${number}:${number}`
  | 'EST'
  | 'CST'
  | 'PST'
  | 'ChinaST'
  | 'IST'
  | 'EET'
  | 'CET'
  | 'AEST`;

Unit conversion

nodejs-geolocation comes with a built-in unit conversion method.

import NodeGeolocation from 'nodejs-geolocation';

const geo = new NodeGeolocation('MyApp');

/**
 * Accepted unit formats:
 * km | yd | mi | m | ft
 */

// Convert 1500 meters to kilometers
const km = geo.convertUnit(1500, 'm', 'km');
console.log(km); // 1.5

Typescript interfaces (TS only)

You can import the interfaces from the package to use them in your project.

// Import interfaces (example)
import { Position, Unit, DistanceCalculationOptions } from 'nodejs-geolocation';

const pos: Position = { lat: 41.8933203, lon: 12.4829321 };

const myUnit: Unit = 'yd';

const options: DistanceCalculationOptions = {
    unit: myUnit,
    format: true,
    exact: true
};

License

MIT