How to Set up Mapbox Maps with React Native

Are you fed up with react-native-maps? Or want a change from Google Maps? In this tutorial, I explain how to use Mapbox Maps in your React Native project.

Update: This tutorial is outdated and a new blog post on Mapbox integration is here – How to integrate Mapbox in React Native.

First of all signup an account here and obtain Mapbox token. Install React Native Mapbox with the following command:

npm install @mapbox/react-native-mapbox-gl --save

If you’re using yarn, use the one given below:

yarn add @mapbox/react-native-mapbox-gl

Now make some native changes to your project as the installation guide given in the following links:

Android

iOS

That’s all need for Mapbox react native setup. Now use the code given below to show a map and a specific annotation in it.

import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import Mapbox from '@mapbox/react-native-mapbox-gl';

Mapbox.setAccessToken(
	'UseYourMapboxTokenHere'
);
export default class MyComponent extends Component {
	renderAnnotations() {
		return (
			<Mapbox.PointAnnotation
				key="pointAnnotation"
				id="pointAnnotation"
				coordinate={[11.254, 43.772]}>
				<View style={styles.annotationContainer}>
					<View style={styles.annotationFill} />
				</View>
				<Mapbox.Callout title="An annotation here!" />
			</Mapbox.PointAnnotation>
		);
	}

	render() {
		return (
			<View style={styles.container}>
				<Mapbox.MapView
					styleURL={Mapbox.StyleURL.Street}
					zoomLevel={15}
					centerCoordinate={[11.256, 43.77]}
					style={styles.container}>
					{this.renderAnnotations()}
				</Mapbox.MapView>
			</View>
		);
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1
	},
	map: {
		height: 400,
		marginTop: 80
	},
	annotationContainer: {
		width: 30,
		height: 30,
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: 'white',
		borderRadius: 15
	},
	annotationFill: {
		width: 30,
		height: 30,
		borderRadius: 15,
		backgroundColor: 'blue',
		transform: [{ scale: 0.6 }]
	}
});

Replace ‘UseYourMapboxTokenHere’ in the code with your Mapbox token which you obtained.

If you want to dig more then refer the official Mapbox documentation and tutorials.

Similar Posts

One Comment

Leave a Reply