Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i access current location from web-page in react native webview

I have an app which developed in react-js. I want to integrate this app into react-native-webview. everything I right but I have two problems.
1-how can I access current location of the user in react-native-webview.
2-how can I debug my react-js(webpage) app inside react-native-webview.

for first problem
if I run webpage in a mobile browser and click on that event I'm getting current location of the user and at the same time when my react-native app getting started, I'm invoking permission for current location so in react-native-debugger i'm getting current location of user.i followed the similar example but this is related to react-native.
exact problem is how can I access the current location of webview in react-native-webview

for second problem
when I'm clicking on the event to fetch current location it is not showing the current location so ** I want to see what is error/response of that event**. because it is in webview I can access react-native logs in react-native-debugger but cannot see the web view logs in the debugger.I followed this one also but I don't know where to put that android config code.

my react-native code

import React, {Component} from 'react';
import {PermissionsAndroid} from 'react-native';
import { WebView } from "react-native-webview";

export default class App extends Component {

constructor(props){
    super(props);

    // To see all the requests in the chrome Dev tools in the network tab.
    XMLHttpRequest = GLOBAL.originalXMLHttpRequest ?
    GLOBAL.originalXMLHttpRequest :
    GLOBAL.XMLHttpRequest;

    // fetch logger
    global._fetch = fetch;
    global.fetch = function (uri, options, ...args) {
    return global._fetch(uri, options, ...args).then((response) => {
    console.log('Fetch', { request: { uri, options, ...args }, response });
    return response;
});
};
}
async requestLocationPermission() {
    try {
    const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
        'title': 'Location Access Permission',
        'message': 'Stanplus would like to use your location ' +
                    'so you we track you.'
        }
    )
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("You can use the location");
        if (typeof window !== 'undefined' && typeof window.navigator !== 'undefined' && navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            (position) => {
            console.log(position.coords.latitude,'success');
            },
            (error) => {
            console.log(error,'fail')
            },
            { enableHighAccuracy: false, timeout: 5000, maximumAge: 10000 }
        );
        }


    } else {
        console.log("Location permission denied")
    }
    } catch (err) {
    console.warn(err)
    }


}

componentDidMount() {
        this.requestLocationPermission();
    }

render() {
    return (
    <WebView 
        source={{uri: 'https://3fa4f958.ngrok.io/steptwo'}}
        style={{marginTop: 20}}
        onMessage={(event)=> console.log(event.nativeEvent.data)}
        scalesPageToFit={true}
    javaScriptEnabled = {true}
    />
    );
}
}

my React.js code which accesses current location

if (navigator.geolocation) {
        alert('event clicked');//in react-native app its showing the alert
        navigator.geolocation.getCurrentPosition(
        //but inside here react-native can't execute because of location permission issue
        position => {   
                let latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                let geocoder = new window.google.maps.Geocoder();
                //do other stuff----------
            }
        )
}

** I want to fetch current location when user click on webpage event inside react-native app and how to debug webview code**

please help stuck since 2 days ):

like image 779
zulqarnain Avatar asked Jan 29 '19 14:01

zulqarnain


People also ask

How do I get current location in React Native?

Geolocation is enabled by default when you create a project with react-native init . In order to enable geolocation in the background, you need to include the 'NSLocationAlwaysUsageDescription' key in Info. plist and add location as a background mode in the 'Capabilities' tab in Xcode.

How do I get data from React Native in Webview?

Create a function called webviewRef and attach it to the WebView component. Next, create a function called sendDataToWebView and add the code below to it. Inside the “script” tag, use window. addEventListener to listen to the event from the React Native app.

How do you get accurate location in react?

Access Geolocation You can access a user's geolocation using the JavaScript API navigator. geolocation , which allows you to ask for location permission. If the user gives permission, location properties can be accessed.


1 Answers

A few steps are needed to get it working on Android.

Add this line to your AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

And then in your app you'll need to request location once before the webview can request it. Do it like so in your view:

import { PermissionsAndroid } from 'react-native';

...

PermissionsAndroid.request(
  PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
  {
    title: 'Location Access Permission',
    message: 'We would like to use your location',
    buttonPositive: 'Okay'
  }
);

And then also on your webview add the property:

geolocationEnabled={true}
like image 147
Benjamin Kaiser Avatar answered Oct 19 '22 19:10

Benjamin Kaiser