0

I'm trying to use Google Maps Api in my app, everything is fine until I want to display a Marker at the first render of the map. The Marker is not showing up, but if I add one more Marker after the render is done, the Marker will appear.

So the problem is that I want to render the map with a Marker already there, I don't want to wait for some location to be selected.

I want to receive lat and lng from props, but for now I've made an hard coded const (center).

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

export default function GoogleMaps({ lat, lng }) {
  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
  });

  const center = useMemo(() => ({ lat: 42.4332, lng: 20.4343 }), []);

  if (!isLoaded) {
    return <h2>Calculating Locations..</h2>;
  }

  return (
    isLoaded && (
      <GoogleMap
        center={center}
        zoom={17}
        mapContainerStyle={{ width: "450px", height: "400px" }}
        options={{ disableDefaultUI: true, mapId: "deleted for this snippet" }}
      >
        <Marker position={center} />
      </GoogleMap>
    )
  );
}

2 Answers 2

0

Have you tried importing and using MarkerF instead of Marker?

See: https://github.com/JustFly1984/react-google-maps-api/issues/3048#issuecomment-1166410403

"MarkerF is functional component vs class based Marker component, which does not work with react Strict and/or react@17+"

Also, there are similar issues discussed here: Markers not rendering using @react-google-maps/api and here: Map Marker don't show up (Marker rendered before Map)- ReactJS with @react-google-maps/api

Sign up to request clarification or add additional context in comments.

Comments

0

For everyone struggling with this, it was the damn react Strict

When I changed my code from this

import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const rootElement = document.getElementById("root");
if (rootElement) {
  const root = createRoot(rootElement);
  root.render(
    <React.StrictMode>
      <App />
   </React.StrictMode>
  );
} else {
  console.error("Root element not found");
}

to this

import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const rootElement = document.getElementById("root");
if (rootElement) {
  const root = createRoot(rootElement);
  root.render(<App />);
} else {
  console.error("Root element not found");
}

Everything worked like a charm. I would have never checked if it wasn't for DavidCastefa, thanks mate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.