3

I've built a React app with a map component which renders a map. I tried to add a marker, but the marker keeps moving when I zoom. What is causing this to happen?

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

const Map = () => {
    const [viewState, setViewState] = useState({
        longitude: 4.895168,
        latitude: 52.370216,
        zoom: 10,
    })
    const [marker] = useState({
        longitude: 4.895168,
        latitude: 52.370216,
    })

    return (
        <div className="map">
            <MapGL
                {...viewState}
                style={{ width: "100%", height: "100%" }}
                mapStyle="mapbox://styles/mapbox/streets-v9"
                onMove={(evt) => setViewState(evt.viewState)}
                mapboxAccessToken="my_token"
            >
                <Marker
                    {...marker}
                />
            </MapGL>
        </div>
    )
}

export default Map;
Tim MG
  • 426
  • 5
  • 17

3 Answers3

9

The problem was this missing line in my index.html:

<link href="https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css" rel="stylesheet">

The documentation tells you nothing about it, had to find it in the source code of this example: https://github.com/visgl/react-map-gl/tree/7.0-release/examples/controls

Tim MG
  • 426
  • 5
  • 17
3

This is not the right solution for me. The solution is very simple

  1. Step 1: Go to your index.js file
  2. Step 2: Then add import 'mapbox-gl/dist/mapbox-gl.css';

And just restart the server. The error will surely be resolved.

0

For me, the solution was different. For some reason, the marker object was rendered so that its top left corner is fixed at the specified location. This is different from the convention that the bottom middle of the marker is fixed at the location. The result is that when you zoom out, all the marker corners seems to change location on the map except for the top left corner. Solved it by adding :

style={{
  width: "50px",
  height: "50px",
  position: "relative",
  top: "-50px",
  left: "-25px",
}}

to my marker JSX to make it's bottom middle fixed instead

ganam
  • 53
  • 2
  • 6