Newby Coder header banner

React Native Google Maps

react-native-maps package provides MapView component which can be used to integrate Google Maps in an Android/iOS application

To use Google Maps, an API key is required which can be created with a Google developer account

A MapView component can be used to/with

Usage

Import

Import MapView and PROVIDER_GOOGLE from react-native-maps module

import MapView, { PROVIDER_GOOGLE } from 'react-native-maps';

Render MapView

Render MapView inside render() method

Assign PROVIDER_GOOGLE provider prop, which is for Google maps

ref prop is to assign a callback which gets called after the component is available in the DOM tree to be referenced

The callback function is passed a reference to the DOM node of the component

initialRegion is a bounded region to be initially shown by the map based on latitude +- latitudeDelta and longitude likewise

    <MapView
          provider={PROVIDER_GOOGLE}
          ref={ref => {
            this.map = ref;
          }}
          style={styles.map}
          initialRegion={{
            latitude: 37.78825,
            longitude: -122.4324,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }}
    />

Creating new React Native App

Check React Native Installation for installation related info

Use react-native init command to create a new React Native project (here named NcGoogleMapsApp)

react-native init NcGoogleMapsApp

This creates a directory named NcGoogleMapsApp and initializes it as a react native application directory

This can be skipped in case an existing react native project is being integrated into

Dependency

To use MapView, add react-native-maps package to project

Go to project directory and run following yarn command to install the dependency

yarn add react-native-maps

Or using npm

npm install react-native-maps --save

Add API Key

A API key can be generated from a project under a Google developer account

Create a project in Google Cloud console or select existing project

Go to Google cloud console and log in with a Google account

If not created already, go to https://console.cloud.google.com/projectcreate to create a project

Projects should appear in the top left corner drop-down, including Firebase projects

google-cloud-select-project

Select project from the dropdown

Enable Google maps API

Goto https://console.cloud.google.com/google/maps-apis

Alternatively, search for Maps SDK for Android

Click on the Enable button

google-cloud-enable-google-maps-api

Generate Api key

Go to https://console.cloud.google.com/apis/credentials

Navigate to Create Credentials and click on API key

google-cloud-create-credentials-api-key

Copy Api key to be added to manifest

google-cloud-copy-api-key-for-maps

Add API key to AndroidManifest.xml

Add Api key as meta-data inside application tag as highlighted

Here NcGoogleMapsApp is React native project name

NcGoogleMapsApp/android/app/src/main/AndroidManifest.xml
    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <meta-data android:name="com.google.android.geo.API_KEY"
             android:value="AIzaSyBg-g9QZMHSmmnPOC-lTC4QnCjClgfTGaI"/>
      <uses-library android:name="org.apache.http.legacy" android:required="false"/>

App Code

App.js
import React from 'react';
import { StyleSheet, View, TouchableOpacity, Text, Alert } from 'react-native';
import MapView, { PROVIDER_GOOGLE } from 'react-native-maps';


class App extends React.Component {
  async getCamera() {
    const camera = await this.map.getCamera();
    Alert.alert('Current camera', JSON.stringify(camera), [{ text: 'OK' }], {
      cancelable: true,
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <MapView
          provider={PROVIDER_GOOGLE}
          ref={ref => {
            this.map = ref;
          }}
          style={styles.map}
          initialRegion={{
            latitude: 37.78825,
            longitude: -122.4324,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }}
        />
        <View style={styles.buttonContainer}>
          <TouchableOpacity
            onPress={() => this.getCamera()}
            style={[styles.bubble, styles.button]}
          >
            <Text>Get current camera</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  map: {
    ...StyleSheet.absoluteFillObject,
  },
  bubble: {
    backgroundColor: 'rgba(255,255,255,0.7)',
    paddingHorizontal: 18,
    paddingVertical: 12,
    borderRadius: 20,
  },
  button: {
    marginTop: 12,
    paddingHorizontal: 12,
    alignItems: 'center',
    marginHorizontal: 10,
  },
  buttonContainer: {
    flexDirection: 'column',
    marginVertical: 20,
    backgroundColor: 'transparent',
  },
});

export default App;

Run instructions

Running in Android

cd into project directory (here NcGoogleMapsApp)

cd NcGoogleMapsApp

Run metro server to serve js

react-native start

Go to project directory in another terminal tab

Enter following run command for Android:

react-native run-android
cl-react-native-android-google-map-as1cl-react-native-android-google-map-as2