Search code examples
reactjsgeolocationmapbox

MapboxGL display user location, bad acuracy


I'm working on an (PWA) app where the user is meant to navigate through the map and collect rewards by visiting a store's coordinates on the map. I'm currently using a React wrapper for Mapbox which has been great so far but the user location's accuracy has not been great so I was wondering if someone has found a workaround for displaying the user's exact location in the map.

This is how I'm displaying the user's location.

    <div className="flex flex-auto h-screen overflow-hidden">
      <ReactMapGL
        {...viewport}
        height="100%"
        width="100%"
        onViewportChange={(nextViewport: any) => setViewport(nextViewport)}
        mapboxApiAccessToken="foo"
        onResize={clearPopupInformation}
        onWheel={clearPopupInformation}
        onClick={clearPopupInformation}
      >
        <GeolocateControl
          style={geolocateControlStyle}
          positionOptions={{ enableHighAccuracy: true }}
          trackUserLocation={true}
          auto
          showUserLocation={true}
        />
        {
            // ...other stuff
        }
      </ReactMapGL>
    </div>

I've found the following:


Solution

  • Apparently this issue only occurs on web browsers where your location in calculated using your IP address, when using a mobile device the built-in GPS is used to calculate your exact location.

    You will need HTTPs to ask mobile users for their location, there are many ways to use HTTPs in react but I combined these two:

    Useful guide here: https://github.com/FiloSottile/mkcert