New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

google-maps-react-markers

Package Overview
Dependencies
Maintainers
0
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

google-maps-react-markers

Google Maps library that accepts markers as react components, works with React 18+ and it is fully typed.

  • 2.0.15
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

Google Maps React Markers

NPM NPM total downloads Maintained GitHub license: MIT GitHub stars GitHub open issues PRs welcome

Google Maps library that accepts markers as react components and works with React 18+.

It supports a small set of the props of Google Map React. Clustering also is possible. The library implements Google Maps Custom Overlays official library.

If you like this library, please consider supporting me ❤️

Buy me a Coffee PayPal

💬 Discussion

Released TypeScript version of the library!

Feedbacks are welcome in this discussion.

🚀 Demo

See it in action here (API KEY not provided).

Demo source code is available here.

🛠 Install

pnpm add google-maps-react-markers

or

yarn add google-maps-react-markers

or

npm install --save google-maps-react-markers

💻 Usage

import GoogleMap from 'google-maps-react-markers'

const App = () => {
  const mapRef = useRef(null)
  const [mapReady, setMapReady] = useState(false)

  /**
   * @description This function is called when the map is ready
   * @param {Object} map - reference to the map instance
   * @param {Object} maps - reference to the maps library
   */
  const onGoogleApiLoaded = ({ map, maps }) => {
    mapRef.current = map
    setMapReady(true)
  }

  const onMarkerClick = (e, { markerId, lat, lng }) => {
    console.log('This is ->', markerId)

    // inside the map instance you can call any google maps method
    mapRef.current.setCenter({ lat, lng })
    // ref. https://developers.google.com/maps/documentation/javascript/reference?hl=it
  }

  return (
    <>
      {mapReady && <div>Map is ready. See for logs in developer console.</div>}
      <GoogleMap
        apiKey=""
        defaultCenter={{ lat: 45.4046987, lng: 12.2472504 }}
        defaultZoom={5}
        options={mapOptions}
        mapMinHeight="100vh"
        onGoogleApiLoaded={onGoogleApiLoaded}
        onChange={(map) => console.log('Map moved', map)}
      >
        {coordinates.map(({ lat, lng, name }, index) => (
          <Marker
            key={index}
            lat={lat}
            lng={lng}
            markerId={name}
            onClick={onMarkerClick} // you need to manage this prop on your Marker component!
            // draggable={true}
            // onDragStart={(e, { latLng }) => {}}
            // onDrag={(e, { latLng }) => {}}
            // onDragEnd={(e, { latLng }) => {}}
          />
        ))}
      </GoogleMap>
    </>
  )
}

export default App

🧐 Props

GoogleMap component

PropTypeRequiredDefaultDescription
apiKeystringyes''API Key to load Google Maps
defaultCenterobjectyes{ lat: 0, lng: 0 }Default center of the map
defaultZoomnumberyes1-20Default zoom of the map
librariesarrayno['places', 'geometry']Libraries to load
optionsobjectno{}Options for the map
onGoogleApiLoadedfunctionno() => {}Callback when the map is loaded
onChangefunctionno() => {}Callback when the map has changed
eventsarrayno[]Array of objects name/handler of DOM events to pass down to the div overlay. Example: events: [{ name: 'onClick', handler: () => {} }]
childrennodenonullMarkers of the map
loadScriptExternallyboolnofalseWhether to load the Google Maps script externally.
If true, the status prop is required and it will be used to control the loading of the script
statusstringnoidleThe forced status of the Google Maps script. Depends on loadScriptExternally.
It can be one of idle, loading, ready, error
loadingContentnodeno'Google Maps is loading'Content to show while the map is loading
idleContentnodeno'Google Maps is on idle'Content to show when the map is idle
errorContentnodeno'Google Maps is on error'Content to show when the map has an error
mapMinHeightstringno'unset'Min height of the map
containerPropsobjectno{}Props for the div container of the map
scriptCallbackfunctionno() => {}window global callback passed to the Google Script
externalApiParamsobjectnoundefinedOptional params to pass to the Google API script. Eg. {region: 'IT', language: 'it'}

Markers

PropTypeRequiredDefaultDescription
latnumberyesundefinedLatitude of the marker
lngnumberyesundefinedLongitude of the marker
draggableboolnofalseIf true, the marker can be dragged
onDragStartfuncno() => {}This event is fired when the user starts dragging the marker
onDragfuncno() => {}This event is repeatedly fired while the user drags the marker
onDragEndfuncno() => {}This event is fired when the user stops dragging the marker
zIndexnumberno0The z-index of the marker. To bring the marker to the front, e.g. when it is active, set a higher value.

📍 Clustering

For clustering, follow this guide using useSupercluster Hook, but use bounds in this way:

const [mapBounds, setMapBounds] = useState({
  bounds: [0, 0, 0, 0],
  zoom: 0,
})
const onMapChange = ({ bounds, zoom }) => {
  const ne = bounds.getNorthEast()
  const sw = bounds.getSouthWest()
  /**
   * useSupercluster accepts bounds in the form of [westLng, southLat, eastLng, northLat]
   * const { clusters, supercluster } = useSupercluster({
   *	points: points,
   *	bounds: mapBounds.bounds,
   *	zoom: mapBounds.zoom,
   * })
   */
  setMapBounds({ ...mapBounds, bounds: [sw.lng(), sw.lat(), ne.lng(), ne.lat()], zoom })
}

👥 Contributing

To run the project locally, clone the repo and run:

# in the root directory
yarn --frozen-install
yarn dev
# in another tab (with NextJS and SSR)
cd docs
yarn install
yarn dev

Do your changes to src/ or docs/src directory, commits all files in the root directory (yarn.lock and ones in dist too) and open a PR.

💻 Built with

🗒 License

MIT © giorgiabosello

🙏 Support

Buy me a Coffee PayPal


Developed with ❤️ in Italy 🇮🇹

Keywords

FAQs

Package last updated on 09 Feb 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc