React Native “更新由以下人员管理的视图的属性”region“时出错:AIRMap空经度'

mefy6pfw  于 2023-10-22  发布在  React
关注(0)|答案(5)|浏览(160)

我想做一个Map,用户可以选择他的当前位置,以及可以选择从他的当前位置以外的位置.但我得到这个错误.“更新由管理的视图的属性”region“时出错:AIRMap空经度”......这里我附上我的Map类代码太...请帮助我

import React from 'react';

    import PropTypes from 'prop-types';

    import { View, StyleSheet, Animated, Platform, UIManager, TouchableOpacity, Text, ViewPropTypes } from 'react-native';

    import MaterialIcons from 'react-native-vector-icons/MaterialIcons';

    import Entypo from 'react-native-vector-icons/Entypo';

    import axios from 'axios';

    import Events from 'react-native-simple-events';

    import MapView from 'react-native-maps';

    import AutoCompleteInput from './AutoCompleteInput'

    const PLACE_DETAIL_URL = 'https://maps.googleapis.com/maps/api/place/details/json';
    const DEFAULT_DELTA = { latitudeDelta: 0.015, longitudeDelta: 0.0121 };

    export default class Map extends React.Component {

     static propTypes = {
        apiKey:"AIzaSyCqDF-mH8qkUQ4z0qB1exxxxxxI0FYRACs",

        initialLocation: PropTypes.shape({
          latitude: PropTypes.number,
          longitude: PropTypes.number,
        }).isRequired,
        markerColor: PropTypes.string,

        actionButtonStyle: ViewPropTypes.style,
        actionTextStyle: Text.propTypes.style,
        actionText: PropTypes.string,
        onLocationSelect: PropTypes.func,
        debounceDuration: PropTypes.number,

        components: PropTypes.arrayOf(PropTypes.string),
      };

      static defaultProps = {
        markerColor: 'black',

        actionText: 'DONE',

        onLocationSelect: () => ({}),

        debounceDuration: 300,

        components: [],

      };

      constructor(props) {
        super(props);

        if (Platform.OS === 'android')
     {
          UIManager.setLayoutAnimationEnabledExperimental && 
    UIManager.setLayoutAnimationEnabledExperimental(true);
        }
      }

      componentDidMount() {
        Events.listen('InputBlur', this.constructor.displayName, this._onTextBlur);
        Events.listen('InputFocus', this.constructor.displayName, this._onTextFocus);
        Events.listen('PlaceSelected', this.constructor.displayName, this._onPlaceSelected);
      }

      componentWillUnmount() {
        Events.rm('InputBlur', this.constructor.displayName);
        Events.rm('InputFocus', this.constructor.displayName);
        Events.rm('PlaceSelected', this.constructor.displayName);
      }

      state = {
        inputScale: new Animated.Value(1),
        inFocus: false,
        region: {
          ...DEFAULT_DELTA,
          ...this.props.initialLocation,

        },
      };

      _animateInput = () => {
        Animated.timing(this.state.inputScale, {
          toValue: this.state.inFocus ? 1.2 : 1,
          duration: 300,
        }).start();
      };

      _onMapRegionChange = region => {
        this._setRegion(region, false);
        if (this.state.inFocus) {
          this._input.blur();
        }
      };

      _onMapRegionChangeComplete = region => {
        this._input.fetchAddressForLocation(region);
      };

      _onTextFocus = () => {
        this.state.inFocus = true;
        this._animateInput();
      };

      _onTextBlur = () => {
        this.state.inFocus = false;
        this._animateInput();
      };

      _setRegion = (region, animate = true) => {
        this.state.region = { ...this.state.region, ...region };
        if (animate) this._map.animateToRegion(this.state.region);
      };

      _onPlaceSelected = placeId => {
        this._input.blur();
        axios.get(`${PLACE_DETAIL_URL}?key=${this.props.apiKey}&placeid=${placeId}`).then(({ data }) => {
          let region = (({ lat, lng }) => ({ latitude: lat, longitude: lng }))(data.result.geometry.location);
          this._setRegion(region);
        });
      };

      _getCurrentLocation = () => {
        navigator.geolocation.getCurrentPosition(position => {
          let location = (({ latitude, longitude }) => ({ latitude, longitude }))(position.coords);
          this._setRegion(location);
        });
      };

      render() {
        let { inputScale } = this.state;
        return (
          <View style={styles.container}>
            <MapView
              ref={mapView => (this._map = mapView)}
              style={styles.mapView}
              region={this.state.region}
              showsMyLocationButton={true}
              showsUserLocation={false}
              onPress={({ nativeEvent }) => this._setRegion(nativeEvent.coordinate)}
              onRegionChange={this._onMapRegionChange}
              onRegionChangeComplete={this._onMapRegionChangeComplete}
            />
            <Entypo
              name={'location-pin'}
              size={30}
              color={this.props.markerColor}
              style={{ backgroundColor: 'transparent' }}
            />
            <View style={styles.fullWidthContainer}>
              <AutoCompleteInput
                ref={input => (this._input = input)}
                apiKey={this.props.apiKey}
                style={[styles.input, { transform: [{ scale: inputScale }] }]}
                debounceDuration={this.props.debounceDuration}
                components={this.props.components}
              />
            </View>
            <TouchableOpacity
              style={[styles.currentLocBtn, { backgroundColor: this.props.markerColor }]}
              onPress={this._getCurrentLocation}
            >
              <MaterialIcons name={'my-location'} color={'white'} size={25} />
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.actionButton, this.props.actionButtonStyle]}
              onPress={() => this.props.onLocationSelect({ ...this.state.region, address: this._input.getAddress() })}
            >
              <View>
                <Text style={[styles.actionText, this.props.actionTextStyle]}>{this.props.actionText}</Text>
              </View>
            </TouchableOpacity>
            {this.props.children}
          </View>
        );
      }
    }
yzxexxkh

yzxexxkh1#

如果您使用showsUserLocation属性,则需要将ACCESS_FINE_LOCATION权限添加到AndroidManifest.xml中
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
希望能有所帮助!

wgeznvg7

wgeznvg72#

首先设置默认区域,这样它就不会在启动时崩溃。

const LATITUDE = 40.665364;
const LONGITUDE = -74.213377;
const LATITUDE_DELTA = 0.0043;
const LONGITUDE_DELTA = 0.0034;

set region props default value this.state.region which is null,which cause this error try adding its default value in state.这样

state = {
    region:{
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA
      }
}


<MapView
          ref={map => (this.map = map)}
          customMapStyle={uber_style}
          initialRegion={{
            latitude: LATITUDE,
            longitude: LONGITUDE,
            latitudeDelta: LATITUDE_DELTA,
            longitudeDelta: LONGITUDE_DELTA
          }}
          region={this.state.region}
          onMapReady={this.onMapLayout}
          maxZoomLevel={this.state.maxZoomLevel}
          provider={PROVIDER_GOOGLE}
          loadingIndicatorColor="#e21d1d"
          style={{
            flex: 1,
            width: Metrics.screenWidth,
            height: Metrics.screenHeight
          }}
          showsBuildings={true}
          loadingEnabled={true}
          //   showsUserLocation={true}
          onRegionChangeComplete={this.onRegionChangeComplete}
        >
vkc1a9a2

vkc1a9a23#

下面是我的示例代码:

var coords = this.props.navigation.state.params.locationvalue; //getting location from props.
            try {
                this.map.animateToRegion({
                    ...this.state.locationArea,
                    latitude: coords.latitude,
                    longitude: coords.longitude
                });
                this.setState(prevState => {
                    return {
                        locationArea: {
                            ...prevState.locationArea,
                            latitude: coords.latitude,
                            longitude: coords.longitude
                        }
                    };
                });
            } catch (error) {
                console.log("error map.animateRegion(): " + JSON.stringify(error))
            }

在这里,我在使用. map.animateToRegion方法时传递了错误的纬度和经度值。
在MapView中使用animateToRegion时,可以检查是否传递了纬度和经度的精确值。我希望这个解决方案有所帮助。

7eumitmz

7eumitmz4#

对我来说,这个问题是一个typo错误。区域latlongstring中。也不应该是blankundefined
您可以使用NumberparseFloat进行解析。

const LATITUDE = '70.664'; //type string
 const LONGITUDE = '-58.23077';

解决方法是:

region:{
    latitude: parseFloat(LATITUDE), //or Number(LATITUDE)
    longitude: parseFloat(LONGITUDE),
    latitudeDelta: 0.02,
    longitudeDelta: 0.02,
  }
jmp7cifd

jmp7cifd5#

尝试从https://github.com/react-native-maps/react-native-maps/issues/4842#issuecomment-1713357892修复,它的工作:
使用patch-package npm包创建补丁文件。
步骤如下:
将修补程序包作为项目依赖项安装,

yarn add patch-package

将以下内容添加到package.json脚本部分:

"postinstall": "patch-package"

转到node_modules/react-native-maps/android/build.gradle更新文件

implementation "com.google.android.gms:play-services-location:20.0.0"

implementation "com.google.android.gms:play-services-location:21.0.0"

创建修补程序文件

npx patch-package react-native-maps --include "android/build.gradle"

相关问题