How to integrate OpenStreetMap into a react-native project?

Using Mapbox GL

⚠️ WARNING: the instructions below for Mapbox appear to no longer be free if you use SDK/library versions after 2.0.0, released around Dec 2020. See this SO answer for more details: https://gis.stackexchange.com/a/188241/55948

Old answer (pre-December 2020 – see above):

Another option is to use Mapbox GL, which is free as long as you don’t use anything in the Mapbox platform. Unlike other options, this won’t require an API key ([source 1] [source 2]).

There’s often confusion about Mapbox, since the platform (global styles, tilesets, datasets, Mapbox Studio, etc) is paid, but Mapbox GL is a library which you may use to display content that is either self-hosted or hosted by the Mapbox platform.

Below is an snippet of an example using Stamen Watercolor tiles (which are also OSM-based):

render() {
  const rasterSourceProps = {
    id: 'stamenWatercolorSource',
    tileUrlTemplates: [
      'https://stamen-tiles.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.jpg',
    ],
    tileSize: 256,
  };

  return (
    <MapboxGL.MapView style={sheet.matchParent}>
      <MapboxGL.Camera
        zoomLevel={16}
      />

      <MapboxGL.RasterSource {...rasterSourceProps}>
        <MapboxGL.RasterLayer
          id="stamenWatercolorLayer"
          sourceID="stamenWatercolorSource"
          style={{rasterOpacity: this.state.opacity}}
        />
      </MapboxGL.RasterSource>
    </MapboxGL.MapView>
  );
}

Other options

As mentioned earlier, one other option for React Native (both Android and iOS) is react-native-maps.

It’s at best unclear, though, if you must use a Google API key to use this lib if you don’t display a Google map: Google says “To use the Maps SDK for Android you must have an API key”, but react-native-maps appears to use a drop-in Maps SDK replacement called AirMapView, which supports other providers and claims you’d need to setup the native Maps SDK on Android only “to support native Google Maps”. To be on the safe side, most people end up setting up a billing account with Google to generate an API key (even if you don’t plan to ever count a single map view), something which Mapbox doesn’t require.

Leave a Comment