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

use-geo-location

v1.0.1

Published

Custom react hook for getting user's location

Downloads

670

Readme

minotaurrr

Custom react hook for getting user's geo location. Google Maps Geocoding API can also be used by providing a valid API key to the hook. Supports TypeScript by default.

Installation

$ yarn add use-geo-location

OR

$ npm i use-geo-location

Basic Usage

Refer to this link for Google Maps response.

import React from 'react';
import { useGeoLocation } from 'use-geo-location';

const TestComponent = () => {
  const apiKey = 'YOUR_GOOGLE_MAPS_API_KEY';
  const { latitude, longitude, loading, error, timestamp, googleMapsResults } = useGeoLocation({ apiKey }); // apiKey is optional

  return (
    <>
      {loading ? (
        <span>Loading...</span>
      ) : (
        <div>
          <span>latitude: {latitude}</span>
          <br />
          <span>longitude: {longitude}</span>
        </div>
      )}
    </>
  );
};

Function description

useGeoLocation()

The following can be provided as options:

| Param | Optional | Type | | :----- | :------- | :---------------------------------------------------------------------- | | apiKey | Yes | string | | watch | Yes | boolean | | config | Yes | { enableHighAccuracy: boolean; timeout: number; maximumAge: number; } |

// e.g.
const config = {
  enableHighAccuracy: false, // default value is false
  timeout: 10000, // default value is 10000
  maximumAge: 0, // default value is 0
}
const apiKey = 'YOUR_GOOGLE_MAPS_API_KEY'
useGeoLocation({ watch: true, config, apiKey }) // watch is set to `false` by default

Options

  • Setting enableHighAccuracy: true may result in slower response and increased power consumption.

  • timeout is the length of time allowed in milliseconds until it gets the user's coords back

  • maximumAge is the length of time in milleseconds until it retries to get user's location. Setting this value to 0 means it will immediately attempt to acquire user's location.

useGeoLocation() will return the following:

| Value | Type | Description | | :---------------- | :------------------------------- | :--------------------------------------------------------- | | latitude | number \| undefined | user's latitude | | longitude | number \| undefined | user's longitude | | loading | boolean | loading status | | error | Error | any error caught from fetching location | | timestamp | number \| undefined | unix timestamp of whem user location was last fetched | | googleMapsResults | GoogleMapsResults \| undefined | google maps api response for user's latitude and longitude |

GoogleMapsResults

| Value | Type | | :-------- | :------- | | plus_code | any | | status | string | | results | any[] |

Please refer to this link for details on what Google Maps API returns.

Watch parameter

If watch is set to true (set to true by default), it'll continuously continuously attempt to get user's position, this is useful when user is using a mobile device. If it's set to true, it will fetch user's position on render and cache it. The cached value will be used until it reaches its maximumAge, set in options.

Error handling

There are two main types of error useGeoLocation() can return.

GeolocationPositonError

Please see https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError for details.

When geo location is not available on user's device, it will return the following error.

{
  code: -1,
  message: 'Geolocation not available',
  PERMISSION_DENIED: 1,
  POSITION_UNAVAILABLE: 2,
  TIMEOUT: 3,
}

Google Maps API Error

Refer to this link for details on Google Maps API errors. Here's a short summary of status message.

| Status | Description | | :----------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | OK | indicates that no errors occurred; the address was successfully parsed and at least one geocode was returned. | | ZERO_RESULTS | indicates that the geocode was successful but returned no results. This may occur if the geocoder was passed a non-existent address. | | OVER_DAILY_LIMIT | indicates any of the following:The API key is missing or invalid.Billing has not been enabled on your account.A self-imposed usage cap has been exceeded.The provided method of payment is no longer valid (for example, a credit card has expired). | | OVER_QUERY_LIMIT | indicates that you are over your quota. | | REQUEST_DENIED | indicates that your request was denied. | | INVALID_REQUEST | generally indicates that the query (address, components or latlng) is missing. | | UNKNOWN_ERROR | indicates that the request could not be processed due to a server error. The request may succeed if you try again. |

Testing

$ yarn test

OR

$ npm test