1

Anyone can help? My map is being rendered and working perfectly but my marker is not working I have been fighting with this for 4 hours.

    import React from "react";
    import { GoogleMap, Marker } from "@react-google-maps/api";

    function Map({ lati, longi }) {
      const position = {
        // lat: lati,
        // lng: longi,
        lat: 33.7295198,
        lng: 73.0371536,
      };

      const onLoad = (marker) => {
        console.log("marker: ", marker);
      };

      return (
        <>
          <GoogleMap
            zoom={18}
            center={{ lat: lati, lng: longi }}
            mapContainerClassName="map-container"
          >
            <Marker onLoad={onLoad} position={position} />
          </GoogleMap>
        </>
      );
    }

    export default Map;
yohanes
  • 2,365
  • 1
  • 15
  • 24

2 Answers2

1

Try

import { GoogleMap, MarkerF } from "@react-google-maps/api";


<MarkerF />
Ahmet Emre Kilinc
  • 5,489
  • 12
  • 30
  • 42
kacper3671
  • 136
  • 1
  • 3
  • 11
0

IMO, it might be because the strict mode renders the app twice, so the marker that we created at the first render is not re-created at the next render.

So, just disable the strict mode by removing the React.StrictMode from your root.render by changing this:

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

into this:

root.render(<App />);

Then you can render the maps in your app by making sure the google.maps object has been loaded before rendering the map:

App.js

import { useEffect } from "react";
import { useJsApiLoader } from "@react-google-maps/api";
import Map from "./Map";

function App() {
  const { isLoaded } = useJsApiLoader({
    id: "google-map-script",
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
  });

  useEffect(() => {
    console.log(isLoaded);
  }, [isLoaded]);

  return <div>{isLoaded && <Map lati={-6.2297465} longi={106.829518} />}</div>;
}

export default App;

Map.js

import React from "react";
import { GoogleMap, Marker } from "@react-google-maps/api";

function Map({ lati, longi }) {
  const position = {
    lat: -6.175878,
    lng: 106.827196,
  };

  const onLoad = (marker) => {
    console.log("marker: ", marker);
  };

  return (
    <>
      <GoogleMap
        zoom={12}
        center={{ lat: lati, lng: longi }}
        mapContainerStyle={{ width: "100%", height: "100vh" }}
      >
        <Marker onLoad={onLoad} position={position} />
      </GoogleMap>
    </>
  );
}

export default Map;
yohanes
  • 2,365
  • 1
  • 15
  • 24