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

gmaps-script-loader

v0.1.3

Published

A simple react hook for loading a google maps API script on browser

Downloads

17

Readme

React Google Maps Script Loader

Build codecov npm MIT license

Description

A simple react hook for loading google maps API script on browser. The loadScript method let you easily change the language and region on the fly.

Install

Available via npm as the package gmaps-script-loader and can be installed by using npm

npm i gmaps-script-loader

or using yarn:

yarn add gmaps-script-loader

TypeScript

TypeScript users need to install the following types package.

npm i -D @types/google.maps

API Reference

useScriptLoader is a react-hook that accepts UseScriptLoader property and returns a ScriptLoader object:

const useScriptLoader = (props: UseScriptLoader): ScriptLoader
type Libraries = Array<
  'drawing' | 'geometry' | 'localContext' | 'places' | 'visualization'
>;

interface UseScriptLoader {
  apiKey: string;
  libraries: Libraries;
  initMap: () => Promise<void>;
}

interface ScriptLoader {
  loadScript: (language: string, region: string) => void;
}

Usage

The useScriptLoader hook can be used as follow:

const { loadScript } = useScriptLoader({
  apiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY as string,
  libraries: ['places'],
  initMap,
});

Example

This is an example of how to combine useScriptLoader with a language selector:

// App.tsx

import { useEffect, useRef, useState } from 'react';
import { useScriptLoader } from 'gmaps-script-loader';
import Language from './Language';
import './styles.css';

export default function App() {
  const mapElementRef = useRef<HTMLDivElement>(null);
  const mapRef = useRef<google.maps.Map | null>(null);

  const initMap = useCallback(async () => {
    const { Map } = google.maps;
    const currentCenter = mapRef.current?.getCenter();

    mapRef.current = new Map(mapElementRef.current as HTMLElement, {
      center: {
        lat: currentCenter?.lat() ?? -34.397,
        lng: currentCenter?.lng() ?? 150.644,
      },
      zoom: mapRef.current?.getZoom() ?? 8,
    });
  }, []);

  const [language, setLanguage] = useState<string>('bahasa');

  const mapLoader = useScriptLoader({
    apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    libraries: ['places'],
    initMap,
  });

  useEffect(() => {
    mapLoader.loadScript('id', 'ID');
  }, [mapLoader]);

  return (
    <>
      <Language
        loader={mapLoader}
        language={language}
        setLanguage={setLanguage}
      />
      <div ref={mapElementRef} style={{ width: '100vw', height: '100vh' }} />
    </>
  );
}

and the language selector component that implementing loadScript method:

// Language.tsx

import { Dispatch, SetStateAction, useEffect } from 'react';

type Lang = { language: string; region: string };

interface Languages {
  [key: string]: Lang;
}

const languages: Languages = {
  bahasa: {
    language: 'id',
    region: 'ID',
  },
  english: {
    language: 'en',
    region: 'GB',
  },
  chinese: {
    language: 'zh',
    region: 'CN',
  },
};

const options = ['bahasa', 'english', 'chinese'];

export default function Language({
  loader,
  language,
  setLanguage,
}: {
  loader: ScriptLoader;
  language: string;
  setLanguage: Dispatch<SetStateAction<string>>;
}) {
  useEffect(() => {
    if (language) {
      const selected = languages[language];
      loader.loadScript(selected.language, selected.region);
    }
  }, [loader, language]);

  return (
    <div style={{ position: 'absolute', right: 70, top: 10, zIndex: 50 }}>
      <select value={language} onChange={e => setLanguage(e.target.value)}>
        {options.map(opt => (
          <option value={opt} key={opt}>
            {opt.charAt(0).toUpperCase() + opt.slice(1)}
          </option>
        ))}
      </select>
    </div>
  );
}

Contribute

We are welcome to any contribution, which has a clear goal and description. You can contribute by creating a feature/fix branch on your own fork and making pull requests towards develop branch of the original repo.