react-map-gl Marker is moving when zooming the map
Asked Answered
A

4

5

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;
Alejandraalejandrina answered 6/2, 2022 at 15:17 Comment(0)
A
12

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

Alejandraalejandrina answered 6/2, 2022 at 18:22 Comment(1)
i get cors error using thisStreptothricin
R
8

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.

Ratiocination answered 1/4, 2023 at 13:57 Comment(0)
B
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

Bedplate answered 19/3, 2023 at 10:20 Comment(0)
D
0

My solution was to set an offset on the marker to [0, 0].

<Marker
  longitude={longitude}
  latitude={latitude}
  anchor="bottom"
  offset={[0, 0]}
></Marker>

I have no idea why this works. A bug perhaps? Why wouldn't the default be to not move the marker on a zoom.

Derwent answered 8/3 at 10:40 Comment(1)
Adding anchor="bottom" was enough for me, thanks. docs.mapbox.com/mapbox-gl-js/api/markers/#markerLexicologist

© 2022 - 2024 — McMap. All rights reserved.