Create a React Native map using Mapbox
Published: 2023-08-16 22:10:21

by [Popoola Temitope](https://blog.openreplay.com/authors/popoola-temitope)

<blockquote><em>In today's digital world, maps have become essential to mobile applications. Whether it's for navigation, locating nearby places, or providing location-based services, integrating maps into your app can greatly enhance the user experience. [React Native](https://reactnative.dev), a popular framework for building cross-platform mobile apps, provides a seamless way to create interactive maps using various mapping platforms. This article will show you how to create a React Native application map using the Mapbox library to enhance your app.</em></blockquote>



[Mapbox](https://www.mapbox.com/) is a popular mapping platform offering developers powerful tools and services. With its comprehensive set of APIs and SDKs, Mapbox allows developers to create stunning and feature-rich maps in their React Native applications. From displaying a map view to integrating user location and adding custom markers, Mapbox provides all the tools to create an immersive and engaging map experience.

In this article, we will explore the steps required to set up Mapbox in your project, display a map view, obtain the user's location, and add custom markers to enhance the functionality of the map.

## Prerequisites
Before we get started, make sure you have the following prerequisites:
- [Node.js](https://nodejs.org/en) and [npm](https://www.npmjs.com/) are installed on your computer.
- [Expo CLI](https://docs.expo.dev/more/expo-cli/).
- A [Mapbox account](https://account.mapbox.com/). You can sign up for a free account at [mapbox.com](https://account.mapbox.com/).
- An [EAS (Expo Application Services)](https://expo.dev/eas) account is required.
- If you're developing on `iOS`, you'll need an Apple Developer Account, which requires an annual fee of approximately `$100`.
- Additionally, if you are developing for Android, you will need an `Android simulator` or a physical Android phone.


## Setting Up the App
To create a new React app using `Expo CLI`, open your terminal, navigate to the directory where you want to install the project and run the following command:
```bash
npx create-expo-app mapbox_app
cd mapbox_app
```
## Installing and setting up Mapbox
To install the [Mapbox package](https://github.com/rnmapbox/maps) in the project folder, run the command below:
```bash
npm i @rnmapbox/maps
```
For [@rnmapbox/maps](https://github.com/rnmapbox/maps) to work on the IOS platform, we must add the following configurations to `ios/Podfile`.
```
pre_install do |installer|
   $RNMapboxMaps.pre_install(installer)
   ... other pre install hooks
   end
post_install do |installer|
   $RNMapboxMaps.post_install(installer)
   ... other post install hooks
   end
```
Now, let's install the Mapbox dependency for iOS. In the `ios` folder of your project, run the following command in your terminal:
```bash
pod install
```
Next, log in to your Mapbox dashboard page to generate a Mapbox API token. From the dashboard, click on `Create a Token`.

![-](https://blog.openreplay.com/images/create-a-react-native-map-using-mapbox/images/image1.png)

On the `Create an Access Token` page, enter the app name, check the `DOWNLOAD:READ` option  and then click on the `Create Token` button as shown in the image below:

![-](https://blog.openreplay.com/images/create-a-react-native-map-using-mapbox/images/image2.png)

Next, you will be redirected back to the dashboard page, where you can access the API public token and secret token, as shown below:

![-](https://blog.openreplay.com/images/create-a-react-native-map-using-mapbox/images/image3.png)


## Displaying a Map View
To display a map view in our React Native app, we must first import the Mapbox package into our code. Open the app.js and add the following code.
```javascript
import React from "react";
import { StyleSheet, View } from "react-native";
import Mapbox from "@rnmapbox/maps";
// . .  .
```
Next, we must set the Mapbox access token and create a variable called `defaultStyle`. The `defaultStyle` variable contains details on how the map will load and be customized, such as the source, minimum and maximum zoom levels, map background color, and map type.
```javascript
// . . .
// Mapbox.setWellKnownTileServer("Mapbox");
Mapbox.setAccessToken("Your Access  Token here");
const defaultStyle = {
 version: 8,
 name: "Land",
 sources: {
   map: {
     type: "raster",
     tiles: ["https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"],
     tileSize: 256,
     minzoom: 1,
     maxzoom: 19,
   },
 },
 layers: [
   {
     id: "background",
     type: "background",
     paint: {
       "background-color": "#f2efea",
     },
   },
   {
     id: "map",
     type: "raster",
     source: "map",
     paint: {
       "raster-fade-duration": 100,
     },
   },
 ],
};
// . . .
```
In the code above, update the access token with your access token from the Mapbox dashboard.
Now, we will use the Mapbox MapView component to display the map in our application by passing the `defaultStyle` variable to the `styleJSON` attribute using the code below.
```javascript
// . . .
const App = () => {
 return (
   <View style={styles.page}>
     <View style={styles.container}>
       <Mapbox.MapView
         style={styles.map}
         styleJSON={JSON.stringify(defaultStyle)}
       />
     </View>
   </View>
 );
};
export default App;
const styles = StyleSheet.create({
 page: {
   flex: 1,
   justifyContent: "center",
   alignItems: "center",
 },
 container: {
   height: 700,
   width: 390,
 },
 map: {
   flex: 1,
 },
});
```

<div style="background-color:#efefef; border-radius:8px; padding:10px; display:block;">
<hr/>
<h3><em>Session Replay for Developers</em></h3> 
<p><em>Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data.</em></p>
<img alt="OpenReplay" style="margin-top:5px; margin-bottom:5px;" width="768" height="400" src="https://raw.githubusercontent.com/openreplay/openreplay/main/static/openreplay-git-hero.svg" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<p><em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em><p>
<hr/>
</div>


## Building the application using EAS 
[EAS](https://expo.dev/eas) (Expo Application Services) is a suite of tools and services provided by Expo, a popular platform for building and deploying React Native applications. `EAS` offers a range of features and services to streamline Expo projects' development, testing, and deployment process.
We cannot test the application using Expo because Mapbox does not support Expo. To test the map application, we need to build the application using EAS.
To install EAS in the project directory, run the following commands on your terminal.
```javascript
npm install -g eas-cli
npx expo install expo-dev-client expo-location
```
To configure the build application, create an eas.json file in the project's root folder and add the following Android and iOS configurations.
```json
{
 "build": {
   "development-simulator": {
     "developmentClient": true,
     "distribution": "internal",
     "android": {
       "simulator": true
     },
     "ios": {
       "simulator": true
     }
   }
 }
}
```
Next, run the code below to build the application on your preferred platform.
``` bash
eas build --profile development-simulator --platform android
# OR
eas build --profile development-simulator --platform ios
```
The build command above may take some time to complete. Wait until the process finishes.

![-](https://blog.openreplay.com/images/create-a-react-native-map-using-mapbox/images/image4.png)

After completing the build, use the build link to download and install the application on your device.
We have to start the Expo project with the development server command. Run the command below on your terminal.
```bash
npx expo start --dev-client
```
Now open the installed application, and it should display the map as shown in the image below.

![-](https://blog.openreplay.com/images/create-a-react-native-map-using-mapbox/images/image5.png)



## Getting a user’s location
One of the common features of a map application is to get the user's location using their coordinate and display them on the map view. [expo-location](https://docs.expo.dev/versions/latest/sdk/location/) is a package for detecting a user's location. 
Install the [expo-location](https://docs.expo.dev/versions/latest/sdk/location/) package using the command below.
```bash
npx expo install expo-location
```
To get the user's coordinate location, open `app.js` and replace the code with the following.
```javascript
import React, { useState, useEffect } from "react";
import { Platform, Text, View, StyleSheet } from "react-native";
import Mapbox from "@rnmapbox/maps";
import * as Location from "expo-location";
Mapbox.setWellKnownTileServer("Mapbox");
Mapbox.setAccessToken(
 "Access Token Here"
);
export default function App() {
 const [location, setLocation] = useState(null);
 useEffect(() => {
   (async () => {
     let { status } = await Location.requestForegroundPermissionsAsync();
     if (status !== "granted") {
       setErrorMsg("Permission to access location was denied");
       return;
     }
     let location = await Location.getCurrentPositionAsync({});
     setLocation(location);
   })();
 }, []);
// . . .
```
In the code above, we first prompt the users to enable the application to access their location details using `Location.requestForegroundPermissionsAsync()`. 
Once the location permission is granted, we use `Location.getLastKnownPositionAsync()` to retrieve the user's coordinates and store them in the location variable.
## Adding a Marker to the user’s location
Adding a custom marker to the user's location is useful for highlighting their position on the map. Mapbox provides APIs to add markers to the map using Mapbox's `PointAnnotation` component.
To indicate the user's location using a map marker, add the following code to the `app.js` file.
```javascript
return (
 <Mapbox.MapView style={{ flex: 1 }}>
   {location && (
     <Mapbox.PointAnnotation
       id="userLocation"
       coordinate={[location.coords.longitude, location.coords.latitude]}
     >
       <Mapbox.Callout title="You are here!" />
     </Mapbox.PointAnnotation>
   )}
 </Mapbox.MapView>
)};
```
Now, reload the application, and you will be prompted to grant the application access to your location. Once permission is granted, you will see location markers on the map view indicating your current location, as shown in the image below.

![-](https://blog.openreplay.com/images/create-a-react-native-map-using-mapbox/images/image6.png)


## Conclusion
In this article, we explored creating a React Native map using Mapbox. We covered the installation and setup process, displaying a map view on both iOS and Android platforms, displaying a user's location, and adding a marker to the user's location.

With these steps, you can enhance your React Native apps by integrating powerful mapping capabilities using Mapbox. Experiment with different features and APIs provided by Mapbox to create engaging and interactive map-based applications.