Using maps in react native is easy because we can use react-native-maps, but we also need to know how to make configurations.
As a first yarn add react-native-maps
Link module with react-native link react-native-maps android/app/src/main/AndroidManifest.xml
<application>
<!-- You will only need to add this meta-data tag, but make sure it's a child of application -->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="Your Google maps API Key Here"/>
</application>
Now let’s talk about
The best approach would be to create a generic component for our maps, let’s start our Maps component by defining what we need:
const screen = Dimensions.get('window');
const ASPECT_RATIO = screen.width / screen.height;
const LATITUDE_DELTA = 0.010;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
const LATITUDE = 0;
const LONGITUDE = 0;
As you can see in the above code we calculate LONGITUDE_DELTA with the aspect ratio of the screen. For LATITUDE_DELTA you can add what size you want to have for your map, referring to the zoom of the map.
import React, { Component } from 'react';
import { Dimensions } from 'react-native';
import MapView, { PROVIDER_GOOGLE } from 'react-native-maps';
const screen = Dimensions.get('window');
const ASPECT_RATIO = screen.width / screen.height;
const LATITUDE_DELTA = 0.010;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
const LATITUDE = 0;
const LONGITUDE = 0;
class Maps extends React.Component {
state = {
latitude: LATITUDE,
longitude: LONGITUDE,
}
componentDidMount() {
// first time ,get current location
}
getMapRegion = () => {
return {
latitude: latitude,
longitude: longitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: longitudeDelta
}
}
render() {
return(
<View>
<MapView
style={styles.map}
provider={PROVIDER_GOOGLE}
showsMyLocationButton
mapType="standard"
showsUserLocation
loadingEnabled
region={this.getMapRegion()}
/>
</View>
)
}
}
export default Maps;
MapView
is the component for rendering our map and as we can see, attribute has initial values from the state. Another case on our code is to get our current location in instead of hard-coding our location.
Don’t forget to set the permissions for Android:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.CAMERA"/>
If you enjoyed this article stay in touch with me on twitter (@StefanCraciun5) and facebook (fb.me/stefaniqblog) .