skip to Main Content

I am using react-map-gl for a project. The map itself renders but i can’t use useMap(). It always logs { current: undefined }. Has anyone a solution?

My layout.tsx contains:

import { MapProvider } from "react-map-gl";
....
<div className="flex h-screen">
  <MapProvider>
    <div>
      {children}
    </div>

    <InternalMap />
  </MapProvider>
</div>

);

InternalMap.tsx looks like:

  import MapGL, { ScaleControl } from "react-map-gl";

  <MapGL
      ....
   >
    ....some more stuff 

The children page looks like:

import { useMap } from "react-map-gl";

const { default: map } = useMap();
console.log(map, useMap())

2

Answers


  1. Chosen as BEST ANSWER

    I messed up some imports in my monorepo and tried to imported react-map-gl from a wrong place with a version missmatch


  2. you have to use An API access token is required to use Mapbox GL.

    import React, { Component } from "react";
    import ReactDOM from "react-dom";
    import ReactMapboxGl, { GeoJSONLayer } from "react-mapbox-gl";
    import * as turf from "@turf/turf";
    import geojsonStyles from "./geojsonStyles";
    import "@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css";
    
    import "./styles.css";
    
    const Map = ReactMapboxGl({
      accessToken:"enter your access token"
    });
    
    class App extends Component {
      onDrawCreate = ({ features }) => {
        console.log(features);
      };
    
      onDrawUpdate = ({ features }) => {
        console.log({ features });
      };
    
      render() {
        const centerPoint = [-73.975547, 40.691785];
    
        var radius = 0.1;
    
        var options = {
          steps: 50,
          units: "miles",
          properties: {
            text: "test"
          }
        };
    
        const firstCircle = turf.circle(centerPoint, radius, options);
    
        const secondCircle = turf.circle(centerPoint, radius * 2, options);
    
        const thirdCircle = turf.circle(centerPoint, radius * 4, options);
    
        return (
          <div className="App">
            <Map
              style="mapbox://styles/mapbox/streets-v9" // eslint-disable-line
              containerStyle={{
                height: "100vh",
                width: "100vw"
              }}
              zoom={[14]}
              center={[-73.975547, 40.691785]}
            >
              <GeoJSONLayer {...geojsonStyles} data={firstCircle} />
              <GeoJSONLayer {...geojsonStyles} data={secondCircle} />
              <GeoJSONLayer {...geojsonStyles} data={thirdCircle} />
            </Map>
          </div>
        );
      }
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    
    

    CodeSandbox URL: https://codesandbox.io/p/sandbox/react-mapbox-gl-turf-mueyi?file=%2Fsrc%2Findex.js%3A1%2C1-65%2C1

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search