0
import { useState, useRef, useEffect, useCallback } from "react";
import Map, { GeolocateControl, Marker } from "react-map-gl";
import "mapbox-gl/dist/mapbox-gl.css";

const App = () => {
  const map = useRef(null);
  const [markers, setMarkers] = useState([]);
  const [viewport, setViewport] = useState({
    latitude: 13.084547176887455,
    longitude: 79.95072330224205,
    width: "100vw",
    height: "100vh",
    zoom: 13,
  });
  const geolocateControlRef = useCallback((ref) => {
    console.log(ref);
    if (ref) {
      ref.trigger();
    }
  }, []);

  return (
    <div className="h-screen">
      <Map
        ref={map}
        className="h-full"
        initialViewState={viewport}
        mapStyle="mapbox://styles/mapbox/streets-v11"
        mapboxAccessToken="pk.eyJ1IjoibmF2ZWVuZzI0MDIiLCJhIjoiY2w1dTlya29xMDl4cjNrdGZ1OWszNTY3aiJ9.ijW4t9ROw0Pa-Uyhgv2s6Q"
        onClick={(e) => setMarkers([...markers, e.lngLat])}
      >
        {map.current && (
          <GeolocateControl ref={geolocateControlRef}></GeolocateControl>
        )}
        {markers.map((marker, i) => (
          <Marker key={i} latitude={marker.lat} longitude={marker.lng}></Marker>
        ))}
      </Map>
    </div>
  );
};

export default App;

I'm trying to show the user location on the map and from the docs I came to know about the GeolocateControl tag but it fails

This comes straight off the documentation but it yells!!! Chrome DevTools Error Log

The map is showing fine and it is at the initial position Image showing the map

naveeng2402
  • 67
  • 1
  • 5

2 Answers2

0

As a (somewhat ugly) workaround I edited the geolocateControlRef to look like this.

const geolocateControlRef = useCallback((ref) => {
  if (ref) {
    (async () => {
      while (!map.current) await ((() => new Promise((resolve) => setTimeout(resolve, 200)))())
      ref.trigger();
    })()
  }
}, []);

Basically this checks every 100ms if map ref is truthy (=loaded). And if it is, try triggering geolocateControl.

I'm still getting the same error message for some reason, but at least the functionality is fine.

Napuu
  • 834
  • 8
  • 10
0

You can use onLoad method in yours Map component. By setting boolean to true in the created useState, you can solve this problem.