Search code examples
react-nativemapboxmapbox-gl

React Native Mapbox GL give UserLocation custom position


react-native-mapbox-gl provides a UserLocation component to display the location of the user via builtin Geolocation tracking: https://github.com/react-native-mapbox-gl/maps/blob/master/docs/UserLocation.md

However I would like to leverage all the animation, rendering and bearing aspects, etc. of this component BUT with my own position data (at least longitude, latitude and heading/bearing).

I do not see this currently as possible or mentioned in the documentation of their repo. Is it possible?

It seems to be possible in the underlying Android documentation: https://docs.mapbox.com/android/maps/api/9.6.1/index.html / LocationComponent:

...You can also push location updates to the component without any internal engine management.
To achieve that, use activateLocationComponent(Context, Style, boolean) with false.
No engine is going to be initialized and you can push location updates with forceLocationUpdate(Location).
...

Solution

  • So it seems there is no props or API for this in the docs so I am doing what should be safe to do: extend the UserLocation component:

    export default class CustomUserLocation extends UserLocation {
      static defaultProps = {
        ...UserLocation.defaultProps,
        <your custom props here>
      }
    
      async componentDidUpdate (prevProps) {
        await UserLocation.prototype.componentDidUpdate.call(this, prevProps)
        ...<checks for your custom props here>
      }
    
      // !! this is the key method to override
      _onLocationUpdate (location) {
        ...
        this.setState({
          coordinates: <set your custom coordinates array here>,
          heading: <set your custom heading here>
        })
        ...
      }
    }