Ameen Izhac
Ameen Izhac

Reputation: 125

I cant get mapbox to work in my Next.js app

I have tried using the react-map-gl library but that didn't work. I have done what is shown here in the docs: https://docs.mapbox.com/mapbox-gl-js/guides/ but it doesn't work for me. Here is my code:

import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";

mapboxgl.accessToken =
  "here i put my api key";

const map = new mapboxgl.Map({
  container: "map",
  style: "mapbox://styles/mapbox/streets-v12",
  center: [-74.5, 40],
  zoom: 9,
});

export default function Home() {
  return <div id="map" />;
}

and when I run it I get this error:

TypeError: Cannot read properties of undefined (reading 'mark')

complaining about this line:

const map = new mapboxgl.Map({...

I have tried to modify the webpack to handle loading worker files which I don't think should be neccessary anyway but that didn't work either.

If you have any idea, help would be much appreciated :)

Upvotes: 1

Views: 3975

Answers (2)

Ameen Izhac
Ameen Izhac

Reputation: 125

My code before the map was working:

import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";

mapboxgl.accessToken =
  "ACCESS_TOKEN";

const map = new mapboxgl.Map({
  container: "map",
  style: "mapbox://styles/mapbox/streets-v12",
  center: [-74.5, 40],
  zoom: 9,
});

export default function Home() {
  return <div id="map" />;
}

My code after the map worked:

import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";
import { useEffect, useRef } from "react";
import styles from "../styles/index.module.scss";

export default function Home() {
  const mapContainer = useRef<any>(null);
  const map = useRef<mapboxgl.Map | any>(null);

  useEffect(() => {
    mapboxgl.accessToken =
      "ACCESS_TOKEN";

    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: "mapbox://styles/mapbox/streets-v12",
      center: [-1.46389, 53.296543],
      zoom: 13,
    });
  }, []);

  return (
    <div id="map">
      <div className={styles.style1} ref={mapContainer} />
    </div>
  );
}

Upvotes: 0

Nuno Costa
Nuno Costa

Reputation: 83

Follow this link to implement mapbox in your Next.js project: https://docs.mapbox.com/help/tutorials/use-mapbox-gl-js-with-react/

Consider using userRef instead of declaring a constant variable. Also move the "dist/xxx.css" import to pages/index or pages/app

Upvotes: 0

Related Questions