Git Product home page Git Product logo

jmarceli / react-hook-google-maps Goto Github PK

View Code? Open in Web Editor NEW
23.0 2.0 3.0 1.08 MB

React useGoogleMaps hook for easy integration with Google Maps API https://www.npmjs.com/package/react-hook-google-maps

Home Page: https://www.npmjs.com/package/react-hook-google-maps

License: MIT License

HTML 4.06% CSS 8.19% TypeScript 79.33% JavaScript 8.42%
google maps react hooks react-usegooglemaps-hook react-use

react-hook-google-maps's Introduction

react-hook-google-maps

React useGoogleMaps hook

license version dependencies status CI build code coverage

Easiest way to use Google Maps in your React application.

For Google API documentation please check https://developers.google.com/maps/documentation/javascript/reference

Install

npm install --save react-hook-google-maps

Usage examples

Check example dir in this repo for most up to date examples.

Simple

import * as React from "react";

import { useGoogleMaps } from "react-hook-google-maps";

const App = () => {
  const { ref, map, google } = useGoogleMaps(
    // Use your own API key, you can get one from Google (https://console.cloud.google.com/google/maps-apis/overview)
    "AIzaSyC4Z5Qz97EWcoCczNn2IcYvaYG0L9pe6Rk",
    // NOTE: You should always set initial 'center' and 'zoom' values
    // even if you plan to change them later
    {
      center: { lat: 0, lng: 0 },
      zoom: 3,
    },
  );
  console.log(map); // instance of created Map object (https://developers.google.com/maps/documentation/javascript/reference/map)
  console.log(google); // google API object (easily get google.maps.LatLng or google.maps.Marker or any other Google Maps class)
  return <div ref={ref} style={{ width: 400, height: 300 }} />;
};

export default App;

Check live example on CodeSandbox:

Edit priceless-shaw-o6e7x

Map with marker

import React from "react";
import { useGoogleMaps } from "react-hook-google-maps";

// based on https://developers.google.com/maps/documentation/javascript/adding-a-google-map
const uluru = { lat: -25.344, lng: 131.036 };

export const MapWithMarker = React.memo(function Map() {
  const { ref, map, google } = useGoogleMaps(
    "AIzaSyC4Z5Qz97EWcoCczNn2IcYvaYG0L9pe6Rk",
    {
      zoom: 4,
      center: uluru,
    },
  );
  console.log("render MapWithMarkers");

  if (map) {
    // execute when map object is ready
    new google.maps.Marker({ position: uluru, map });
  }

  return (
    <div>
      <span>
        Example from{" "}
        <a href="https://developers.google.com/maps/documentation/javascript/adding-a-google-map">
          https://developers.google.com/maps/documentation/javascript/adding-a-google-map
        </a>
      </span>
      <div ref={ref} style={{ width: 400, height: 300 }} />
    </div>
  );
});

Check live example on CodeSandbox:

Edit funny-wood-twb4t

Map with external controls

import React, { useState, useEffect } from "react";
import { useGoogleMaps } from "react-hook-google-maps";

export const Map = React.memo(function Map() {
  const [value, setValue] = useState(0);
  const { ref, map, google } = useGoogleMaps(
    "AIzaSyC4Z5Qz97EWcoCczNn2IcYvaYG0L9pe6Rk",
    {
      center: { lat: 0, lng: 0 },
      zoom: 3,
    },
  );
  console.log("render Map");

  useEffect(() => {
    if (!map) {
      return;
    }
    setValue(map.getZoom());

    const listener = map.addListener("zoom_changed", () => {
      setValue(map.getZoom());
    });
    return () => google.maps.event.removeListener(listener);
  }, [map, google]);

  const handleZoomUpdate = (zoomChange = 1) => {
    const nextZoom = value + zoomChange;
    if (nextZoom < 0) {
      return;
    }
    map.setZoom(nextZoom);
  };

  return (
    <div>
      <span>External zoom controls example</span>
      <div ref={ref} style={{ width: 400, height: 300 }} />
      <button onClick={() => handleZoomUpdate(1)}>Zoom In</button>
      <button onClick={() => handleZoomUpdate(-1)} disabled={value < 1}>
        Zoom Out
      </button>
      <div>{value}</div>
    </div>
  );
});

Check live example on CodeSandbox:

Edit funny-wood-twb4t

License

MIT

Author

Jan Grzegorowski

react-hook-google-maps's People

Contributors

jmarceli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-hook-google-maps's Issues

Can i add clickable event?

I want to get to the location by click on the map. Like "set on the map" where i can get the lat and lng from map

Support related google libraries?

I think it could be nice if this hook also allowed to initialize related libraries like the Drawing Library, and returned a DrawingManager object. Same goes for PlacesService etc...

Any interest in supporting this type of feature? I am happy to have a go at a PR, I am already using similar functionality elsewhere.

Invalid hook call

Tried manually setting react@^16.12.0 and react-dom@^16.12.0 but it doesn't appear that version mismatches are the issue.

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (react.development.js?3558:1465)
    at useState (react.development.js?3558:1496)
    at useGoogleMapsApi (index.es.js?8df1:5)
    at useGoogleMaps (index.es.js?8df1:39)
    at Search (index.tsx?2d4b:37)
    at renderWithHooks (react-dom.development.js?61bb:14803)
    at mountIndeterminateComponent (react-dom.development.js?61bb:17482)
    at beginWork (react-dom.development.js?61bb:18596)
    at HTMLUnknownElement.callCallback (react-dom.development.js?61bb:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js?61bb:237)
    at invokeGuardedCallback (react-dom.development.js?61bb:292)
    at beginWork$1 (react-dom.development.js?61bb:23203)
    at performUnitOfWork (react-dom.development.js?61bb:22154)
    at workLoopSync (react-dom.development.js?61bb:22130)
    at performSyncWorkOnRoot (react-dom.development.js?61bb:21756)
    at eval (react-dom.development.js?61bb:11089)
    at unstable_runWithPriority (scheduler.development.js?3069:653)
    at runWithPriority$1 (react-dom.development.js?61bb:11039)
    at flushSyncCallbackQueueImpl (react-dom.development.js?61bb:11084)
    at flushSyncCallbackQueue (react-dom.development.js?61bb:11072)
    at flushSync (react-dom.development.js?61bb:21932)
    at Object.scheduleRefresh (react-dom.development.js?61bb:11626)
    at eval (react-refresh-runtime.development.js?1816:304)
    at Set.forEach (<anonymous>)
    at Object.performReactRefresh (react-refresh-runtime.development.js?1816:293)
    at eval (helpers.js?e64a:124)

How can I add a Marker on map?

Thank you for your work on this library.

I didn't figure out how can I add a marker point to the map. Can you give me a hint ... pls?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.