How to get Geolocation of React Native WebView

In this React Native source code example, the source code below illustrate how to get Geolocation of React Native WebView.

You can copy and adopt this source code example to your React Native project without reinventing the wheel.

import React, {Component} from 'react';
import {PermissionsAndroid, Alert} from 'react-native';
import { WebView } from "react-native-webview";
//for this to work, location must be switched on, on the device
//you also have to add   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
//to your AndroidManifest.xml

export default class App extends Component {
async requestLocationPermission() {
    try {
    const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
        'title': 'Location Access Permission',
        'message': 'We would like to use your location ' +
                    'so you we track you.'
        }
    )
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("You can use the location");
        await navigator.geolocation.getCurrentPosition(
          (position) => {
            Alert.alert('latitiude:  ',position.coords.latitude.toFixed(2));
          },
          (error) => console.log(error),
          {enableHighAccuracy: false, timeout: 50000}
      );
    }
  else {
        console.log("Location permission denied")
    }
    } catch (err) {
    console.warn(err)
    }
}

componentDidMount() {
        this.requestLocationPermission();
    }

render() {
    return (
    <WebView
        source={{uri: 'https://google.com'}}
        style={{marginTop: 20}}
        geolocationEnabled={true}
        onMessage={(event)=> console.log(event.nativeEvent.data)}
        scalesPageToFit={true}
        javaScriptEnabled = {true}
    />
    );
}
}

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment