Added the first constant

const GettingStartedGoogleMap = withGoogleMap(props => (
  <GoogleMap
    ref={props.onMapLoad}
    zoom={13}
    center={{ lat: 21.178574, lng: 72.814149 }}
    onClick={props.onMapClick}
  >
    {props.markers.map(marker => (
      <Marker
        {...marker}
        onRightClick={() => props.onMarkerRightClick(marker)}
      />
    ))}
  </GoogleMap>

Changed the containerElement size and mapElement size to pixels instead of percentage

  containerElement={
    <div style={{ height: `150px` }} />
  }
  mapElement={
    <div style={{ height: `150px` }} />
  }

And just adding marker to the function which was called

markers={this.state.markers}
Answer from Dhaval Jardosh on Stack Overflow
๐ŸŒ
React Map GL
visgl.github.io โ€บ component
<Marker> Component | React Google Maps
import React, {FunctionComponent} from 'react'; import {APIProvider, Map, Marker} from '@vis.gl/react-google-maps'; const App: FunctionComponent<Record<string, unknown>> = () => ( <APIProvider apiKey={'Your API key here'}> <Map zoom={12} center={{lat: 53.54992, lng: 10.00678}}> <Marker position={{lat: 53.54992, lng: 10.00678}} /> </Map> </APIProvider> ); export default App;
๐ŸŒ
npm
npmjs.com โ€บ package โ€บ google-maps-react-markers
google-maps-react-markers - npm
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.
      ยป npm install google-maps-react-markers
    
Published ย  Feb 09, 2025
Version ย  2.0.15
Author ย  Giorgia Bosello
๐ŸŒ
Medium
medium.com โ€บ @masonlynass โ€บ using-react-google-maps-advancedmarkers-and-implementing-google-maps-javascript-api-features-7a9ffc2655c4
Using React-Google-Maps, AdvancedMarkers, and implementing Google Maps JavaScript API features in the Better Bathroom Bureau website | by Mason Lynass | Medium
July 1, 2024 - One big reason I loved using the new vis.gl/react-google-maps package is that there are plenty of examples in their documentation! Whether you want to specify custom marker clustering, implement autocomplete or add directions, display synchronized maps, or just set up a basic example map, there are visual examples with code provided on their website.
๐ŸŒ
GitHub
github.com โ€บ google-map-react โ€บ google-map-react
GitHub - google-map-react/google-map-react: Google map library for react that allows rendering components as markers :tada: ยท GitHub
Google map library for react that allows rendering components as markers :tada: - google-map-react/google-map-react
Starred by 6.5K users
Forked by 856 users
Languages ย  JavaScript 97.7% | HTML 1.8% | CSS 0.5%
๐ŸŒ
Tabnine
tabnine.com โ€บ home page โ€บ code โ€บ javascript โ€บ marker
react-google-maps.Marker JavaScript and Node.js code examples | Tabnine
withScriptjs(withGoogleMap(() => <GoogleMap defaultZoom={12} defaultCenter={{ lat: parseFloat(-37.813179), lng: parseFloat(144.950259) }} > <Marker position={{ lat: -37.813179, lng: 144.950259 }} /> </GoogleMap>, )) ... createMarkers() { if(this.state.render === false){ this.createMarkers(); } return this.state.locations.map( (item ,index) => { return <Marker position={{lat: item.lat, lng: item.lng}} key={index} /> }) }
๐ŸŒ
GitHub
github.com โ€บ giorgiabosello โ€บ google-maps-react-markers
GitHub - giorgiabosello/google-maps-react-markers: Google Maps library that accepts markers as react components and works with React 18+. ยท GitHub
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!
Starred by 152 users
Forked by 20 users
Languages ย  TypeScript 92.3% | JavaScript 6.6% | Shell 1.1%
Find elsewhere
๐ŸŒ
React Map GL
visgl.github.io โ€บ react-google-maps โ€บ examples โ€บ advanced-marker-interaction
Advanced Marker interaction - React Google Maps
Markers scale on hover and change their color when they are selected by clicking on them. The default z-index is sorted by latitude.
Top answer
1 of 4
36

Edit:
Since this answer was posted the docs (and likely, the API) of the GoogleMapReact element was changed to support children. Any child with lat and lng would be rendered at the corresponding location on the map, as also indicated by @Jobsamuel's answer.

The onGoogleApiLoaded callback should not be used for this purpose, as it is inferior to the declarative style and would not be re-run if changes are made to the map.


Original answer (outdated):

This may not be entirely clear from the description in the Readme, but the maps argument is, in fact, the maps API object (and map is, of course, the current Google Map instance). Therefore, you should pass both to your method:

onGoogleApiLoaded={({map, maps}) => this.renderMarkers(map, maps)}

and use them:

renderMarkers(map, maps) {
  let marker = new maps.Marker({
    position: myLatLng,
    map,
    title: 'Hello World!'
  });
}
2 of 4
20

Adding a marker on your map isn't as easy as we would like to, mostly because the confusing docs but here you have a super easy example:

const Map = props => {
  return (
    <GoogleMapReact
     bootstrapURLKeys={{ props.key }}
     defaultCenter={{lat: props.lat, lng: props.lng}}
     defaultZoom={props.zoom}>

       {/* This is the missing part in docs:
         *
         * Basically, you only need to add a Child Component that
         * takes 'lat' and 'lng' Props. And that Component should
         * returns a text, image, super-awesome-pin (aka, your marker).
         *
         */}
       <Marker lat={props.lat} lng={props.lng}} />
    </GoogleMapReact>
  )
}

const Marker = props => {
  return <div className="SuperAwesomePin"></div>
}
๐ŸŒ
DEV Community
dev.to โ€บ aneeqakhan โ€บ how-to-add-markers-to-google-maps-in-reactjs-1jnk
How to Add Markers to Google Maps in React.js - DEV Community
April 22, 2024 - {showDialog && ( // displays a dialog to add clicked location <InfoWindow position={dialogLocation}> <button className="app-button" onClick={onAddLocation}> Add this location </button> </InfoWindow> )} <Marker position={markerLocation} /> ... ... Here on the "Add this location" button, I passed the "onAddLocation" function to it. For this, we need a new state to store all the clicked locations. // store list of all locations selected const [listOfLocations, setListOfLocations] = useState([]); // add location to show in a list const onAddLocation = () => { // Create a Google Maps Geocoder insta
๐ŸŒ
Medium
medium.com โ€บ @cristhiangrojas โ€บ react-google-maps-markers-typescript-6f8d1d1d44d3
React + Google Maps + Markers + Typescript | by Cristhiangrojas | Medium
December 26, 2023 - @googlemaps/react-wrapper: google package to show map on screen ยท @googlemaps/markerclusterer: google package to add markers to our map
๐ŸŒ
React Map GL
visgl.github.io โ€บ component
<AdvancedMarker> Component | React Google Maps
A component to add an AdvancedMarkerElement to a map. By default, an AdvancedMarker will appear as a balloon-shaped, red maps-pin at the specified position on the map, but the appearance of the markers can be fully customized.
๐ŸŒ
GitHub
github.com โ€บ fullstackreact โ€บ google-maps-react
GitHub - fullstackreact/google-maps-react: Companion code to the "How to Write a Google Maps React Component" Tutorial ยท GitHub
The <Map /> api includes subcomponents ... the three props (as children): ... To place a marker on the Map, include it as a child of the <Map /> component....
Starred by 1.6K users
Forked by 807 users
Languages ย  JavaScript
Top answer
1 of 3
1

As you can tell, you can pass DOM nodes into advanced markers like you have here:

        const markerComponent = document.createElement("div");
        markerComponent.innerHTML = `
  <img src="${busTopViewImage}" />
  <h5 style="background-color: ${markerData.marker.backgroundColor}; color: white; border-radius: 10px; padding: 8px;">
        ${markerData.marker.text}
  </h5>
`;
        const m = new AdvancedMarkerElement({
          map,
          position: markerData.coordinates,
          content: markerComponent,
        });

The only thing you're missing is to generate the HTML via React.

    // Setup a React root on a virtual DOM node
    const markerComponent = document.createElement("div");
    // Initialize root at new DOM node
    const root = ReactDOM.createRoot(el);
    // Output HTML into it
    root.render(<Marker ... />);

     // Use it
    const m = new AdvancedMarkerElement({
          map,
          position: markerData.coordinates,
          content: markerComponent,
        });

If you need to share state with the rest of the tree, you can combine this with Portals.

2 of 3
1

You can check this youtube video here: https://www.youtube.com/watch?v=8kxYqoY2WwE

Github source code: https://github.com/leighhalliday/google-maps-threejs/blob/main/pages/markers.js

import { Wrapper } from "@googlemaps/react-wrapper";
import { useRef, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";

export default function App() {
  return (
    <Wrapper
      apiKey={process.env.NEXT_PUBLIC_MAP_API_KEY}
      version="beta"
      libraries={["marker"]}
    >
      <MyMap />
    </Wrapper>
  );
}

const mapOptions = {
  mapId: process.env.NEXT_PUBLIC_MAP_ID,
  center: { lat: 43.66293, lng: -79.39314 },
  zoom: 10,
  disableDefaultUI: true,
};

function MyMap() {
  const [map, setMap] = useState();
  const ref = useRef();

  useEffect(() => {
    setMap(new window.google.maps.Map(ref.current, mapOptions));
  }, []);

  return (
    <>
      <div ref={ref} id="map" />
      {map && <Weather map={map} />}
    </>
  );
}

const weatherData = {
  A: {
    name: "Toronto",
    position: { lat: 43.66293, lng: -79.39314 },
    climate: "Raining",
    temp: 20,
    fiveDay: [15, 18, 12, 22, 20],
  },
  B: {
    name: "Guelph",
    position: { lat: 43.544811, lng: -80.248108 },
    climate: "Cloudy",
    temp: 20,
    fiveDay: [15, 18, 12, 22, 20],
  },
  C: {
    name: "Orangeville",
    position: { lat: 43.919239, lng: -80.097412 },
    climate: "Sunny",
    temp: 20,
    fiveDay: [15, 18, 12, 22, 20],
  },
};

function Weather({ map }) {
  const [data, setData] = useState(weatherData);
  const [highlight, setHighlight] = useState();
  const [editing, setEditing] = useState();

  return (
    <>
      {editing && (
        <Editing
          weather={data[editing]}
          update={(newWeather) => {
            setData((existing) => {
              return { ...existing, [editing]: { ...newWeather } };
            });
          }}
          close={() => setEditing(null)}
        />
      )}
      {Object.entries(data).map(([key, weather]) => (
        <Marker
          key={key}
          map={map}
          position={weather.position}
          onClick={() => setEditing(key)}
        >
          <div
            className={`marker ${weather.climate.toLowerCase()} ${
              highlight === key || editing === key ? "highlight" : ""
            }`}
            onMouseEnter={() => setHighlight(key)}
            onMouseLeave={() => setHighlight(null)}
          >
            <h2>{weather.climate}</h2>
            <div>{weather.temp}c</div>
            {highlight === key || editing === key ? (
              <div className="five-day">
                <p>Next 5</p>
                <p>{weather.fiveDay.join(", ")}</p>
              </div>
            ) : null}
          </div>
        </Marker>
      ))}
    </>
  );
}

function Editing({ weather, update, close }) {
  return (
    <div className="editing">
      <h2>Editing {weather.name}</h2>

      <label htmlFor="climate">Climate</label>
      <select
        id="climate"
        value={weather.climate}
        onChange={(e) => update({ ...weather, climate: e.target.value })}
      >
        {["Sunny", "Cloudy", "Raining"].map((val) => (
          <option key={val} value={val}>
            {val}
          </option>
        ))}
      </select>

      <label htmlFor="temp">Temperature</label>
      <input
        id="temp"
        type="number"
        value={weather.temp}
        onChange={(e) => update({ ...weather, temp: e.target.value })}
      />

      <button type="button" onClick={() => close()}>
        Close
      </button>
    </div>
  );
}

function Marker({ map, position, children, onClick }) {
  const rootRef = useRef();
  const markerRef = useRef();

  useEffect(() => {
    if (!rootRef.current) {
      const container = document.createElement("div");
      rootRef.current = createRoot(container);

      markerRef.current = new google.maps.marker.AdvancedMarkerView({
        position,
        content: container,
      });
    }

    return () => (markerRef.current.map = null);
  }, []);

  useEffect(() => {
    rootRef.current.render(children);
    markerRef.current.position = position;
    markerRef.current.map = map;
    const listener = markerRef.current.addListener("click", onClick);
    return () => listener.remove();
  }, [map, position, children, onClick]);
}
๐ŸŒ
GitHub
github.com โ€บ cedricdelpoux โ€บ react-google-map
GitHub - cedricdelpoux/react-google-map: React component to render a map with markers from Google Maps API ยท GitHub
coordinates={[ { title: "Toulouse", position: { lat: 43.604363, lng: 1.443363, }, onLoaded: (googleMaps, map, marker) => { // Set Marker animation marker.setAnimation(googleMaps.Animation.BOUNCE) // Define Marker InfoWindow const infoWindow = new googleMaps.InfoWindow({ content: ` <div> <h3>Toulouse<h3> <div> Toulouse is the capital city of the southwestern French department of Haute-Garonne, as well as of the Occitanie region.
Starred by 25 users
Forked by 19 users
Languages ย  JavaScript
๐ŸŒ
Form.io
mindbowser.com โ€บ home โ€บ blogs โ€บ react google map with a custom pin marker
Tailored Marker Pins for React Google Map
January 15, 2024 - This article guides you through the process of setting up and implementing Google Maps in ReactJS. Additionally, you'll discover how to customize the marker pin.
๐ŸŒ
DEV Community
dev.to โ€บ jameseaster โ€บ react-google-maps-api-thoughts-pt-2-nnj
@react-google-maps/api thoughts (pt.2) - DEV Community
May 11, 2020 - These buttons will eventually allow us to add markers to our map and remove markers from our map. If we are going to add buttons we will have to wrap our current component in a . Then underneath the , but inside of the , we'll add some buttons. <div> <GoogleMap {/* a bunch of stuff we added from the last blog */} </GoogleMap> <button type="button" style={{backgroundColor: drawMarker ?