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

react-gmaps-utils

v0.1.8

Published

a React library that provides components and hooks for integrating Google Maps functionality into your React applications.

Downloads

41

Readme

react-gmaps-utils

npm package npm downloads npm bundle size

react-gmaps-utils is a React library that provides components and hooks for integrating Google Maps functionality into your React applications.

Installation

You can install react-gmaps-utils using npm:

npm install react-gmaps-utils
npm install --save-dev @types/google.maps

Usage

GoogleMapsProvider

The GoogleMapsProvider component is used to load the Google Maps script and provide a context for other components to access the Google Maps API.

import { GoogleMapsProvider } from 'react-gmaps-utils'

function App() {
  return (
    <GoogleMapsProvider apiKey='YOUR_API_KEY'>
      {/* Your application components */}
    </GoogleMapsProvider>
  )
}

Map

The Map component renders a Google Map and provides various options for customization.

import { Map } from 'react-gmaps-utils'

function MyMap() {
  return (
    <Map
      options={{
        center: { lat: 37.7749, lng: -122.4194 },
        zoom: 10
      }}
    >
      {/* Optional child components */}
    </Map>
  )
}

Marker

The Marker component adds a marker to the map at a specified position.

import { Map } from 'react-gmaps-utils'

function MyMapWithMarker() {
  return (
    <Map
      options={{
        center: { lat: 37.7749, lng: -122.4194 },
        zoom: 10
      }}
    >
      <Map.Marker position={{ lat: 37.7749, lng: -122.4194 }} />
    </Map>
  )
}

Autocomplete

The Autocomplete component provides an input field with autocomplete functionality for places.

import { Places, Autocomplete } from 'react-gmaps-utils'
import { useMemo, useRef, useState } from 'react'

function MyAutocomplete() {
  const [query, setQuery] = useState('')
  const autocompleteRef = useRef<{close: () => void}>(null)
  const placesService = useRef<google.maps.places.PlacesService | null>(null)
  const [placeId, setPlaceId] = useState<string | null>(null);
  return (
    <Places
      onLoaded={(places) => {
        placesService.current = places
      }}
    >
      <Autocomplete
        as={CustomInput}
        ref={autocompleteRef}
        value={query}
        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
          setQuery(e.target.value)
        }
        options={{ types: ['(cities)'] }}
        className='input'
        renderResult={(predictions) => {
          return (
            <div className='dropdown'>
              {predictions.map((prediction) => (
                <div
                  className='dropdown-item'
                  key={prediction.place_id}
                  onClick={() => {
                    setPlaceId(prediction.place_id)
                    autocompleteRef.current?.close()
                  }}
                >
                  <span>{prediction.description}</span>
                </div>
              ))}
            </div>
          )
        }}
      />
      <Places.FindPlaceByPlaceId placeId={placeId} onPlaceReceived={(place) => {console.log(place?.geometry?.location?.toJSON())}} />
    </Places>
  )
}

The component also has shouldFetch which is a boolean that you can pass to prevent the autocomplete from fetching suggestions. example usecase could be if you want to make the fetch occurs only if there was a user interaction.

ReverseGeocodeByLocation

The ReverseGeocodeByLocation component performs reverse geocoding based on a specified location.

import { ReverseGeocodeByLocation } from 'react-gmaps-utils'

function MyReverseGeocoder() {
  return (
    <ReverseGeocodeByLocation
      position={{ lat: 37.7749, lng: -122.4194 }}
      onAddressReceived={(result) => console.log(result)}
    />
  )
}

MapEvent

The MapEvent component listens for events on the map and executes a callback function when the event is triggered.

import { MapEvent } from 'react-gmaps-utils'

function MyMapEvent() {
  const handleMapClick = (map, event) => {
    console.log('Map clicked at:', event.latLng.lat(), event.latLng.lng())
  }

  return (
    <Map
      options={{
        center: { lat: 37.7749, lng: -122.4194 },
        zoom: 10
      }}
    >
      <Map.Event event='click' callback={handleMapClick} />
    </Map>
  )
}

Custom Hooks

useCurrentPosition

The useCurrentPosition hook retrieves the current position of the user.

import { useCurrentPosition } from 'react-gmaps-utils'

function MyComponent() {
  const { position, loading, error, getCurrentPosition, getIPBasedPosition } = useCurrentPosition({
    onInit: {
      getPosition: true,
      ipBased: true,
    }
  })

  if (loading) return <div>Loading...</div>
  if (error) return <div>Error: {error}</div>

  return (
    <div>
      Latitude: {position?.lat}
      <br />
      Longitude: {position?.lng}
      <br />
      <button onClick={getCurrentPosition}>Get Exact Location</button>
    </div>
  )
}

Note

This library requires an API key from Google Maps. Make sure to replace "YOUR_API_KEY" with your actual API key in the GoogleMapsProvider component.

License

MIT © abdelrahman146