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

@smkdev/geolocation

v1.0.1

Published

Biblioteca Node.js completa para geolocalização com mapas interativos e WebSockets em tempo real

Readme

@smkdev/geolocation 🌍

npm version License: MIT Downloads

Biblioteca Node.js completa para geolocalização com mapas interativos, WebSockets em tempo real e funcionalidades de geocodificação. Perfeita para integração entre apps React Native (Expo) e frontends Next.js.

🚀 Instalação

npm install @smkdev/geolocation

⚡ Início Rápido

Servidor Completo

import { GeoLocationLib } from '@smkdev/geolocation';

const geoLib = new GeoLocationLib({
    port: 3001,
    cors: {
        origin: ["http://localhost:3000", "exp://192.168.1.100:19000"] // Next.js + Expo
    }
});

await geoLib.start();
console.log('🌍 Servidor de geolocalização rodando!');

Usando Apenas os Serviços

import { createServices } from '@smkdev/geolocation';

const services = createServices();

// Calcular distância entre dois pontos
const distance = services.geolocation.calculateDistance(
    { lat: -23.5505, lng: -46.6333 },  // São Paulo
    { lat: -22.9068, lng: -43.1729 }   // Rio de Janeiro
);
console.log(`Distância: ${Math.round(distance/1000)}km`);

// Geocodificação
const locations = await services.geocoding.geocode('São Paulo, Brasil');
console.log('Coordenadas:', locations[0]);

📱 Integração React Native + Next.js

React Native (Cliente)

import { io } from 'socket.io-client';
import * as Location from 'expo-location';

const useRealTimeTracking = (serverUrl) => {
    const [socket, setSocket] = useState(null);

    useEffect(() => {
        const newSocket = io(serverUrl);
        setSocket(newSocket);

        const startTracking = async () => {
            const { status } = await Location.requestForegroundPermissionsAsync();
            if (status === 'granted') {
                await Location.watchPositionAsync({
                    accuracy: Location.Accuracy.High,
                    timeInterval: 5000, // 5 segundos
                    distanceInterval: 10 // 10 metros
                }, (location) => {
                    newSocket.emit('location_update', {
                        userId: 'user123',
                        latitude: location.coords.latitude,
                        longitude: location.coords.longitude,
                        timestamp: Date.now()
                    });
                });
            }
        };

        startTracking();
        return () => newSocket.close();
    }, [serverUrl]);

    return socket;
};

Next.js Frontend (Visualização)

import { useEffect, useState } from 'react';
import { io } from 'socket.io-client';

export default function TrackingPage() {
    const [users, setUsers] = useState(new Map());

    useEffect(() => {
        const socket = io('http://seu-backend.com:3001');

        socket.on('location_update', (data) => {
            setUsers(prev => {
                const updated = new Map(prev);
                updated.set(data.userId, {
                    ...data,
                    lastUpdate: new Date()
                });
                return updated;
            });
        });

        socket.on('user_disconnected', (data) => {
            setUsers(prev => {
                const updated = new Map(prev);
                updated.delete(data.userId);
                return updated;
            });
        });

        return () => socket.close();
    }, []);

    return (
        <div>
            <h1>📍 Rastreamento em Tempo Real</h1>
            {Array.from(users.values()).map(user => (
                <div key={user.userId} style={{ 
                    padding: '10px', 
                    border: '1px solid #ccc', 
                    margin: '5px',
                    borderRadius: '5px'
                }}>
                    <strong>👤 {user.userId}</strong><br/>
                    📍 Lat: {user.latitude.toFixed(6)}<br/>
                    📍 Lng: {user.longitude.toFixed(6)}<br/>
                    🕐 {user.lastUpdate.toLocaleTimeString()}
                </div>
            ))}
        </div>
    );
}

🌐 APIs Disponíveis

WebSocket Events

// Enviar (cliente → servidor)
socket.emit('location_update', locationData);
socket.emit('location_share', { userId, latitude, longitude, message });
socket.emit('join_room', { userId, roomId });

// Receber (servidor → cliente)
socket.on('location_update', handleLocationUpdate);
socket.on('user_connected', handleUserConnected);
socket.on('geofence_alert', handleGeofenceAlert);

REST Endpoints

// Geocodificação
GET /api/geocoding/forward?q=São Paulo, Brasil
GET /api/geocoding/reverse?lat=-23.5505&lng=-46.6333

// Cálculos de distância
POST /api/geolocation/distance
{
    "from": {"lat": -23.5505, "lng": -46.6333},
    "to": {"lat": -23.5506, "lng": -46.6334}
}

🎯 Funcionalidades

  • WebSocket em tempo real com Socket.IO
  • Mapas interativos com Leaflet.js
  • Geocodificação com rate limiting inteligente
  • Cálculos geográficos (distância, bearing, geofencing)
  • Interface web pronta para demonstrações
  • Segurança e monitoramento integrados
  • Compatível com React Native, Next.js, Vue, Angular
  • Pronto para produção com logs e métricas

🔧 Configuração Avançada

import { GeoLocationLib } from '@smkdev/geolocation';

const geoLib = new GeoLocationLib({
    port: 3001,
    cors: {
        origin: process.env.ALLOWED_ORIGINS?.split(',') || ["*"]
    },
    security: {
        rateLimit: {
            windowMs: 15 * 60 * 1000, // 15 minutos
            max: 100 // máximo 100 requests por IP
        }
    },
    geocoding: {
        providers: ['openstreetmap', 'nominatim'],
        cacheTimeout: 60 * 60 * 1000, // 1 hora
        maxRequestsPerMinute: 60
    }
});

📖 Documentação Completa

Para documentação completa, exemplos avançados e guias de implementação, visite:

📄 Licença

MIT © smkdev


🌍 Construa aplicações de geolocalização em tempo real de forma simples e rápida!