This article aims to give knowledge about how to implement Google Maps into your react native applications with basic concepts like Rendering a Map with an initial region, Changing map type ,Placing a marker ,Get user’s current Location ,Move to specific position with animation etc.
Get GITHUB code from HERE.
Note: In the above video on pressing LOCATE ME button shows your current location.
- Start a new React Native project. If you don’t know how then read my this tutorial.
- After creating project Open Command Prompt in your system .
- Now using command prompt locate your project’s root folder .
Adding React Native Map to Android
- Now install react-native-maps inside your project :
npm install react-native-maps –save
Configure Project for Android devices
- In your android/app/build.gradle add:
dependencies {
...
implementation(project(':react-native-maps')){
exclude group: 'com.google.android.gms', module: 'play-services-base'
exclude group: 'com.google.android.gms', module: 'play-services-maps'
}
implementation 'com.google.android.gms:play-services-base:10.0.1'
implementation 'com.google.android.gms:play-services-maps:10.0.1'
}
- In your android/settings.gradle add:
include ':react-native-maps'
project(':react-native-maps').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-maps/lib/android')
- Specify your Google Maps API Key:
Add your API key to your manifest file(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>
- Add import com.airbnb.android.react.maps.MapsPackage; and new MapsPackage() in your MainApplication.java :
import com.airbnb.android.react.maps.MapsPackage;
...
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new MapsPackage()
);
}
MapView
This MapView component is built so that features on the map (such as Markers, Polygons, etc.) are specified as children of the MapView itself.
;
OR
var MapView = ;
Rendering a Map with an initial region
In the below code :
latitude , longitude : refers to a specific position or point.
latitudeDelta , longitudeDelta : refers to the area around the specific position.
initialRegion : sets the map region on initialization. Cannot accommodate updates.
region : able to take location updates from your application and re-render map accordingly.
state = {
focusedLocation: {
latitude: 37.7900352,
longitude: -122.4013726,
latitudeDelta: 0.0122,
longitudeDelta:
Dimensions.get("window").width /
Dimensions.get("window").height *
0.0122
}
}
render() {
return (
<View style={styles.container}>
<MapView
initialRegion={this.state.focusedLocation}
style={styles.map}
>
</MapView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
map: {
width: "100%",
height: "100%"
}
});
Run your project and congratulations if you see a map displaying on your device.
Changing Map Type
You can move to any kind of map by defining mapType prop as :
– standard: standard road map (default)
– none: no map
– satellite: satellite view
– hybrid: satellite view with roads and points of interest overlayed
– terrain: (Android only) topographic view
– mutedStandard: more subtle, makes markers/lines pop more (iOS 11.0+ only)
Placing a Marker
You can place a marker on the map by using following code:
<MapView.Marker coordinate={ {latitude: 37.7900352,longitude: -122.4013726} }
title = "title"
description = "description"
pinColor = "blue"
image = {require("./assets/custum_icon.png")} />
coordinate : The coordinate for the marker.
title : The title of the marker. This is only used if the component has no children that are a <Callout />, in which case the default callout behavior will be used, which will show both the title and the description, if provided.
description : The description of the marker. This is only used if the component has no children that are a <Callout />, in which case the default callout behavior will be used, which will show both the title and the description, if provided.
pinColor : If no custom marker view or custom image is provided, the platform default pin will be used, which can be customized by this color. Ignored if a custom marker is being used.
image : A custom image to be used as the marker’s icon. Only local image resources are allowed to be used.
Get User’s current Location
The navigator geolocation property(navigator.geolocation) returns a Geolocation object that can be used to locate the user’s position.
The getCurrentPosition() method is used to return the user’s position.
state = {
focusedLocation: {
latitude: 37.7900352,
longitude: -122.4013726,
latitudeDelta: 0.0122,
longitudeDelta:
Dimensions.get("window").width /
Dimensions.get("window").height *
0.0122
}
}
navigator.geolocation.getCurrentPosition(pos => {
this.setState(prevState => {
return {
focusedLocation: {
...prevState.focusedLocation,
latitude: pos.coords.latitude,
longitude: pos.coords.longitude }
};
});
},
err => {
console.log(err);
alert("Fetching the Position failed");
})
Move to specific Position With Animation
onPress : Callback that is called when user taps on the map. It returns an object (with property coordinate and position )and we can access event data by using nativeEvent object.
animateToRegion : this method is used when we want to animate at specific position with animation.We pass region and duration as two arguments.
state = {
focusedLocation: {
latitude: 37.7900352,
longitude: -122.4013726,
latitudeDelta: 0.0122,
longitudeDelta:
Dimensions.get("window").width /
Dimensions.get("window").height *
0.0122
}
}
<MapView
initialRegion={this.state.focusedLocation}
region={!this.state.locationChosen ? this.state.focusedLocation : null}
style={styles.map}
onPress={this.pickLocationHandler}
ref={ref => this.map = ref}
>
pickLocationHandler = event => {
const coords = event.nativeEvent.coordinate;
this.map.animateToRegion({
...this.state.focusedLocation,
latitude: coords.latitude,
longitude: coords.longitude
});
this.setState(prevState => {
return {
focusedLocation: {
...prevState.focusedLocation,
latitude: coords.latitude,
longitude: coords.longitude
}
};
});
};
Complete Code:
import React, { Component } from "react";
import {
View,
Image,
Button,
StyleSheet,
Text,
Dimensions
} from "react-native";
import MapView from "react-native-maps";
export default class App extends Component {
state = {
focusedLocation: {
latitude: 37.7900352,
longitude: -122.4013726,
latitudeDelta: 0.0122,
longitudeDelta:
Dimensions.get("window").width /
Dimensions.get("window").height *
0.0122
},
locationChosen: false
}
pickLocationHandler = event => {
const coords = event.nativeEvent.coordinate;
this.map.animateToRegion({
...this.state.focusedLocation,
latitude: coords.latitude,
longitude: coords.longitude
});
this.setState(prevState => {
return {
focusedLocation: {
...prevState.focusedLocation,
latitude: coords.latitude,
longitude: coords.longitude
},
locationChosen: true
};
});
};
getLocationHandler = () => {
navigator.geolocation.getCurrentPosition(pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the Position failed, please pick one manually!");
})
}
render() {
let marker = null;
if (this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
}
return (
<View style={styles.container}>
<MapView
initialRegion={this.state.focusedLocation}
region={!this.state.locationChosen ? this.state.focusedLocation : null}
style={styles.map}
onPress={this.pickLocationHandler}
ref={ref => this.map = ref}
>
{marker}
</MapView>
<View style={styles.button}>
<Button title="Locate Me" onPress={this.getLocationHandler} />
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
width: "100%",
alignItems: "center"
},
map: {
width: "100%",
height: 600
},
button: {
margin: 8
}
});