Adding permission to use location in React Expo


I had a working React Native Expo App that shows a map and my realtime location together with custom markers and some other info, great. Now I have to add the request permission code to use "my location".

I’m having trouble adding it to my code because I think it’s overlapping with the existing components.
I found similar questions and examples using the useState and useEffect -sorry I know- and tried to apply them with no success.

import React, { Component, useState, useEffect } from 'react';
import { View, Text, StyleSheet, Platform } from 'react-native';
import { Constants, MapView } from 'expo';
import geolib from "geolib";

const ACTIVE_PIN = require('./map_pin.png');
const INACTIVE_PIN = require('./map_pin_active.png');

export default class App extends Component {
  constructor (props) {
    super(props);
    this.state = {
      lat: this.props.latitude!=null? this.props.latitude: -34.908014,
      lng: this.props.longitude!=null ? this.props.longitude: -56.151055,
      latDelta: 0.0015*5,
      lngDelta: 0.00121*5,
      speed: null,
      heading: null,
      distance: null,
      error: null
    };
  }

  componentDidMount () {
    this.watchId = navigator.geolocation.watchPosition(
      (position) => {
        const { latitude, longitude, speed, heading } = position.coords;


    var centers = [
    /*Rambla CV*/  {id: 'C01', latitude: -34.910490, longitude: -56.201567}];



var myPos = {latitude: latitude, longitude: longitude};


        this.setState({
          latitude: latitude,
          longitude: longitude,
          speed: speed,
          heading: heading,
          lat: position.coords.latitude,
          lng: position.coords.longitude,
          latitudeDelta: 0.015*5,
          longitudeDelta: 0.0121*5,
          error: null
        });
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 5000, maximumAge: 0, distanceFilter: 10 }
    ); //timeout estaba en 20000



  }

  onRegionChange(region) {    //entro de suerte aca
    this.setState({ region });
  }

  componentWillUnmount () {
    navigator.geolocation.clearWatch(this.watchId);
  }



state = {
    isSelected: false
  }

  renderPins = () => {
    const { isSelected } = this.state;

    const venues = [
{id: 'C01', title: 'Rambla y Ciudadela', coordinates: [-34.910490, -56.201567]}];




    return venues.map(venue => (
      <MapView.Marker
        key={venue.id}
        identifier={venue.id}
        title={venue.id}
        description={venue.title}
        coordinate={{
          latitude: venue.coordinates[0],
          longitude: venue.coordinates[1]
        }}
        image={isSelected ? INACTIVE_PIN : ACTIVE_PIN}
        ref={`callout-${venue.id}`}
        zIndex={isSelected ? 999 : 0}
      >

      </MapView.Marker>
    ));
  }



  render () {
    return (
        <View style={styles.container}>
        <MapView
          style={{flex: 1}}
          mapType={'standard'}
          showsPointsOfInterest={false}
          showsUserLocation={true}
          loadingEnabled={true}
          provider={Platform.OS === 'ios' ? null : 'google'}
        region={{
       latitude: this.state.lat,
       longitude: this.state.lng,
       latitudeDelta: this.state.latDelta,
       longitudeDelta: this.state.lngDelta,
     }}
       //region={this.state.region}
      // onRegionChange={region => this.onRegionChange(region)}
        >
          { this.renderPins() }
        </MapView>
        <View style={{ flexGrow: 0.3, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude:: {this.state.latitude}</Text>
        <Text>Longitude:: {this.state.longitude}</Text>
        <Text>Speed:: {Math.round(this.state.speed * 3.6)} km/h </Text>
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
      </View>
      </View>
    );
  }
}

  const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
   textShadow: {
      textShadowColor: 'red',
      textShadowOffset: { width: 2, height: 2 },
      textShadowRadius : 5
   }
});

Source: React – Stack Overflow

August 28, 2021
Category : News
Tags: expo | jsx | permissions | react native | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.