Геолокация - React Native - PullRequest
       4

Геолокация - React Native

0 голосов
/ 04 апреля 2020

Я следовал следующему руководству, чтобы узнать местоположение пользователя для моего собственного собственного реактивного приложения: https://reactnativemaster.com/react-native-geolocation-example/
Однако, кроме Hello на моем iphone, ничего не отображается.

Я думаю, что проблема в том, что геокод является нулем, но я не знаю, как это исправить.

Любые советы будут полезны:)

При необходимости см. Мой код ниже:

import React, { Component } from "react";
import {
  StyleSheet,
  Text,
  View,
} from "react-native";
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';



class App extends Component {
  state= {
    location:null,
    geocode:null,
    errorMessage:""
  }

  getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);


    if (status !== 'granted') {
      this.setState({
        errorMessage: 'Permission to access location was denied',
      });
    }

    let location = await Location.getCurrentPositionAsync({accuracy:Location.Accuracy.Highest});
    const { latitude , longitude } = location.coords
    this.getGeocodeAsync({latitude, longitude})
    this.setState({ location: {latitude, longitude}});

  };

  getGeocodeAsync= async (location) => {
    let geocode = await Location.reverseGeocodeAsync(location)
    this.setState({ geocode})
  }

  render(){
    const {location,geocode, errorMessage } = this.state
    return (
        <View style={styles.overlay}>
          <Text>Hello</Text>
          <Text style={styles.heading1}>{geocode  ? `${geocode[0].city}, ${geocode[0].isoCountryCode}` :""}</Text>
          <Text style={styles.heading2}>{geocode ? geocode[0].street :""}</Text>
          <Text style={styles.heading3}>{location ? `${location.latitude}, ${location.longitude}` :""}</Text>
          <Text style={styles.heading2}>{errorMessage}</Text>

        </View>
    );
  }
}

export default App;

1 Ответ

0 голосов
/ 04 апреля 2020
import React, { Component } from "react";
import {
  StyleSheet,
  Text,
  View,
} from "react-native";
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';



class App extends Component {
  state= {
    location:null,
    geocode:null,
    errorMessage:""
  }

  // You have to call this.getLocationAsync()

  componentDidMount(){
    // this is needed for geocode
    Location.setApiKey("Your-API-KEY-Here")
    this.getLocationAsync();
  }

  getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);


    if (status !== 'granted') {
      this.setState({
        errorMessage: 'Permission to access location was denied',
      });
    }

    let location = await Location.getCurrentPositionAsync({accuracy:Location.Accuracy.Highest});
    const { latitude , longitude } = location.coords
    this.setState({ location: {latitude, longitude}});
    this.getGeocodeAsync({latitude, longitude}).catch(err => {this.setState({errorMessage: err})})

  };

  getGeocodeAsync= async (location) => {
    let geocode = await Location.reverseGeocodeAsync(location)
    this.setState({geocode: geocode})

    // check console for geocode response
    console.log(geocode)
  }

  render(){
    const {location,geocode, errorMessage } = this.state
    return (
        <View style={styles.overlay}>
          <Text>Hello</Text>
          <Text style={styles.heading1}>{geocode  ? `${geocode[0].city}, ${geocode[0].region}` :""}</Text>
          <Text style={styles.heading2}>{geocode ? geocode[0].country :""}</Text>
          <Text style={styles.heading3}>{location ? `${location.latitude}, ${location.longitude}` :""}</Text>
          <Text style={styles.heading2}>{errorMessage}</Text>

        </View>
    );
  }
}

// Create styles for your headings here

const styles = StyleSheet.create({
  heading1:{
    fontSize: 24
  },
  heading2:{
    fontSize: 18
  },
  heading3:{
    fontSize: 12
  }
})

export default App;

Вам необходимо использовать свой ключ API Google для службы геокодирования, чтобы он не возвращал значение NULL, и если вы запустите его без него, вам нужно установитьState для отображения сообщения об ошибке для геокода.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...