TypeError: null is not an object (evaluating 'this.state.initialPosition') - React Native

时间:2021-03-05 02:15:22

标签: react-native geolocation xdebug

我正在做一个使用 Geolocation 获取当前位置的 RN 项目,但我不知道这有什么问题。

这是我的代码:

   import React, { Component } from 'react';
   // Import required component
   import { SafeAreaView, StyleSheet, Text, Alert, TouchableOpacity, Image, View } from 'react-native';
   
   import { request, PERMISSIONS } from 'react-native-permissions';
   
   // Import vector icons
   import Icon from 'react-native-vector-icons/FontAwesome';
   import MapView, { PROVIDER_GOOGLE, Platform, Marker, Callout, Circle } from 'react-native-maps';
   import coordinate from '../../api/binLocationData';
   import Geolocation from '@react-native-community/geolocation';
   
   export class Home extends Component {
     componentDidMount() {
       this.requestLocationPermission();
     }
   
     requestLocationPermission = async () => {
       if (Platform.OS === 'IOS') {
         var response = await request(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE);
         console.log('IOS: ' + response);
         if (response === 'granted') {
           this.locateCurrentPosition();
         }
       } else {
         var response = await request(PERMISSIONS.ANDROID.LOCATION_WHEN_IN_USE);
         console.log('Android: ' + response);
         if (response === 'granted') {
           this.locateCurrentPosition();
         }
       }
     };
   
     locateCurrentPosition = () => {
       Geolocation.getCurrentPosition(
         (position) => {
           console.log(JSON.stringify(position));
   
           let initialPosition = {
             latitude: position.coords.latitude,
             longitude: position.coords.longitude,
             latitudeDelta: 0.05,
             longitudeDelta: 0.05,
           };
           this.setState({ initialPosition });
         },
         (error) => Alert.alert(error.message),
         { enableHighAccuracy: true, timeout: 1000, maximumAge: 1000 },
       );
     };
     render() {
       return (
         <SafeAreaView style={{ flex: 1 }}>
           <View style={{ flex: 1 }}>
             <MapView
               provider={PROVIDER_GOOGLE}
               ref={(map) => (this._map = map)}
               showsUserLocation={true}
               style={styles.maps}
               initialRegion={this.state.initialPosition}
               // initialRegion={{
               //   latitude: 16.0599,
               //   longitude: 108.2438,
               //   latitudeDelta: 0.05,
               //   longitudeDelta: 0.05,
               // }}
             >
               <Circle
                 radius={1000}
                 center={{ latitude: 16.0599, longitude: 108.2438 }}
                 fillColor={'rgba(51,150,152,0.3)'}
               />
               <Marker coordinate={{ latitude: 16.0599, longitude: 108.2438 }}>
                 <Callout>
                   <Text>Bin 1</Text>
                 </Callout>
                 {/* <Image source={require('./src/assets/icons/bin.png')} /> */}
               </Marker>
               {coordinate.map((marker) => (
                 <Marker
                   key={marker.id}
                   coordinate={{ latitude: marker.latitude, longitude: marker.longitude }}
                   title={marker.name}
                 />
               ))}
             </MapView>
           </View>
         </SafeAreaView>
       );
     }
   }
   const styles = StyleSheet.create({
     maps: {
       ...StyleSheet.absoluteFillObject,
     },
   });
   
   export default Home;

和调试显示:

<块引用>

TypeError: null is not an object (evaluating 'this.state.initialPosition')

我该如何解决?

1 个答案:

答案 0 :(得分:1)

您忘记初始化状态。您应该将其添加到您的类组件中:

constructor(props) {
        this.state = {
          latitude: 0,
          longitude: 0,
          latitudeDelta: 0,
          longitudeDelta: 0,
        };
      }

这应该有效:

import React, { Component } from "react";
// Import required component
import {
  SafeAreaView,
  StyleSheet,
  Text,
  Alert,
  TouchableOpacity,
  Image,
  View,
} from "react-native";

import { request, PERMISSIONS } from "react-native-permissions";

// Import vector icons
import Icon from "react-native-vector-icons/FontAwesome";
import MapView, {
  PROVIDER_GOOGLE,
  Platform,
  Marker,
  Callout,
  Circle,
} from "react-native-maps";
import coordinate from "../../api/binLocationData";
import Geolocation from "@react-native-community/geolocation";

export class Home extends Component {
  constructor(props) {
    this.state = {
      latitude: 0,
      longitude: 0,
      latitudeDelta: 0,
      longitudeDelta: 0,
    };
  }

  componentDidMount() {
    this.requestLocationPermission();
  }

  requestLocationPermission = async () => {
    if (Platform.OS === "IOS") {
      var response = await request(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE);
      console.log("IOS: " + response);
      if (response === "granted") {
        this.locateCurrentPosition();
      }
    } else {
      var response = await request(PERMISSIONS.ANDROID.LOCATION_WHEN_IN_USE);
      console.log("Android: " + response);
      if (response === "granted") {
        this.locateCurrentPosition();
      }
    }
  };

  locateCurrentPosition = () => {
    Geolocation.getCurrentPosition(
      (position) => {
        console.log(JSON.stringify(position));

        let initialPosition = {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          latitudeDelta: 0.05,
          longitudeDelta: 0.05,
        };
        this.setState({
           latitude: initialPosition.latitude,
           longitude: initialPosition.longitude,
           latitudeDelta: initialPosition.latitudeDelta,
           longitudeDelta: initialPosition.longitudeDelta,
         });
      },
      (error) => Alert.alert(error.message),
      { enableHighAccuracy: true, timeout: 1000, maximumAge: 1000 }
    );
  };
  render() {
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={{ flex: 1 }}>
          <MapView
            provider={PROVIDER_GOOGLE}
            ref={(map) => (this._map = map)}
            showsUserLocation={true}
            style={styles.maps}
            initialRegion={this.state.initialPosition}
            // initialRegion={{
            //   latitude: 16.0599,
            //   longitude: 108.2438,
            //   latitudeDelta: 0.05,
            //   longitudeDelta: 0.05,
            // }}
          >
            <Circle
              radius={1000}
              center={{ latitude: 16.0599, longitude: 108.2438 }}
              fillColor={"rgba(51,150,152,0.3)"}
            />
            <Marker coordinate={{ latitude: 16.0599, longitude: 108.2438 }}>
              <Callout>
                <Text>Bin 1</Text>
              </Callout>
              {/* <Image source={require('./src/assets/icons/bin.png')} /> */}
            </Marker>
            {coordinate.map((marker) => (
              <Marker
                key={marker.id}
                coordinate={{
                  latitude: marker.latitude,
                  longitude: marker.longitude,
                }}
                title={marker.name}
              />
            ))}
          </MapView>
        </View>
      </SafeAreaView>
    );
  }
}
const styles = StyleSheet.create({
  maps: {
    ...StyleSheet.absoluteFillObject,
  },
});

export default Home;