更新由以下人员管理的视图的属性“坐标”时出错:AIRMapMarker(React native)

时间:2018-04-20 12:02:14

标签: react-native

我一直在网上搜索有关此错误的正确文档,我没有运气,因为我无法确定此错误的原因。

这是我的整个代码:

第一部分:设置状态

export default class Whereto extends Component<{}> {

constructor(props) {
    super(props);

    this.state = {
        latitude: null,
        longitude: null,
        location: null,
        error: null,
        markers:[],

    };
}

第二部分组件已安装

componentDidMount() {
        navigator.geolocation.getCurrentPosition(
            (position) => {
                this.setState({
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude,
                    error: null,
                });

                //geocode api
                var myApiKey = '';

                fetch('https://maps.googleapis.com/maps/api/geocode/json?address=' + position.coords.latitude + ',' + position.coords.longitude + '&key=' + myApiKey)
                    .then((response) => response.json())
                    .then((responseJson) => {
                        //console.log('ADDRESS GEOCODE is BACK!! => ' + JSON.stringify(responseJson));
                        var locationName = responseJson.results[0].address_components.filter(x => x.types.filter(t => t === 'administrative_area_level_2').length > 0)[0].short_name;
                        //console.log(locationName);
                        this.setState({
                            location: locationName,
                        })
                    })

                //nearby api
                var apiPlaceskey = '';
                //https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&type=restaurant&keyword=cruise&key=YOUR_API_KEY

                fetch('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + position.coords.latitude + ',' + position.coords.longitude + '&radius=2000&type=bus_station&key=' + apiPlaceskey)
                    .then((respplaces) => respplaces.json())
                    .then((responseJson2) => {

                        const markers = responseJson2.results.map((result) => ({
                            latlng: {
                                latitude: result.geometry.location.lat,
                                longitude: result.geometry.location.lng,
                            }
                        }));

                        this.setState({ markers });
                    });


            },
            (error) => this.setState({error: error.message}),
            {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},

        );


    }

第三部分:在我的渲染和视图部分点按可触摸按钮时保留的功能

fetchDirections = () => {
        //directions api
        var apiDirectionskey = '';
        //const {location} = this.state;
        const {latitude} = this.state;
        const {longitude} = this.state;

        fetch('https://maps.googleapis.com/maps/api/directions/json?origin=' + latitude + ',' + longitude + '&destination=' + goingto + '&mode=transit&transit_mode=bus&key=' + apiDirectionskey)
            .then((resdirections) => resdirections.json())
            .then((responseJson3) => {

                console.log(responseJson3);

            });


        }

    render(){

        return(
            <View style={styles.container}>
                <Mainlogo/>
                <TextInput style={styles.boxInput} underlineColorAndroid='rgba(0,0,0,0)' placeholder="Going To?"
                           underlineColorAndroid='transparent'
                           onChangeText={(dest) => this.setState({goingto : dest})}
                />
                <TouchableOpacity style={styles.button} onPress={this.fetchDirections.bind(this)}>
                    <Text style={styles.textButton}> Go {this.props.type}</Text>
                </TouchableOpacity>

                <MapView style={styles.map}
                         region={{
                             latitude: this.state.latitude,
                             longitude: this.state.longitude,
                             latitudeDelta: 0.02,
                             longitudeDelta: 0.02
                         }}
                >

                </MapView>

                <MapView.Marker
                    coordinate={{
                        latitude: this.state.latitude,
                        longitude: this.state.longitude,
                        latitudeDelta: 0.02,
                        longitudeDelta: 0.02
                    }}
                    image={require('../img/my-pin-512.png')}
                    title={'you are here'}
                />

                {this.state.markers.map(marker => (
                    <MapView.Marker
                        coordinate={marker.latlng}
                        image={require('../img/busstop.png')}

                    />

                ))}





            </View>
        )

    }
}

要进入这个阶段,我的主要个人资料页面会触发一个touchableopacity。我意识到我正在使用componentsndDidMount和一个单独的fetch函数来调用另一个API调用。似乎没有足够的时间来篡改状态以导致空值

enter image description here

7 个答案:

答案 0 :(得分:1)

将初始状态值设置为0,而不是null。

[0] => Array ( [contractId] => 1 [pricingDetails] => Array (  
                    [0] => Array ( [pricingName] => Price2 [priceId] => 2 [ageGroup] => 1 [ageFrom] => 13 [ageTo] => 50 [price] => 77.00 ) 
                    [1] => Array ( [pricingName] => Price5 [priceId] => 5 [ageGroup] => 2 [ageFrom] => 3 [ageTo] => 12 [price] => 11.00 ) 
                    [2] => Array ( [pricingName] => Price6 [priceId] => 6 [ageGroup] => 2 [ageFrom] => 0 [ageTo] => 2 [price] => 0.00 ) 
                    [3] => Array ( [pricingName] => Price8 [priceId] => 8 [ageGroup] => 3 [ageFrom] => 51 [ageTo] => 149 [price] => 30.00 )  
[1] => Array ( [contractId] => 2 [pricingDetails] => Array ( 
                    [0] => Array ( [pricingName] => Price2 [priceId] => 11 [ageGroup] => 1 [ageFrom] => 13 [ageTo] => 50 [price] => 80.00 ) 
                    [1] => Array ( [pricingName] => Price5 [priceId] => 14 [ageGroup] => 2 [ageFrom] => 3 [ageTo] => 12 [price] => 15.00 ) 
                    [2] => Array ( [pricingName] => Price6 [priceId] => 15 [ageGroup] => 2 [ageFrom] => 0 [ageTo] => 2 [price] => 0.00 ) 
                    [3] => Array ( [pricingName] => Price8 [priceId] => 17 [ageGroup] => 3 [ageFrom] => 51 [ageTo] => 149 [price] => 35.00 ) 
                    ) ) ))

答案 1 :(得分:1)

通过此操作可以帮助我解决此问题:

coordinate={{
     latitude: props && props.position && Number(props.position.latitude) ? Number(props.position.latitude) : 0,
     longitude: props && props.position && Number(props.position.longitude) ? Number(props.position.longitude) : 0 
}}

答案 2 :(得分:0)

坐标中的初始值从null更改为[]解决了该问题。

<MapView.Polyline
    strokeWidth={2}
    strokeColor="#00ff00"
    coordinates={coords}
/>

答案 3 :(得分:0)

我收到的经纬度值是道具,所以对我有用的是:

<Marker
coordinate={{
            longitude: longitude ? longitude : 0,
            latitude: latitude ? latitude : 0
          }}
title={'owner location'}
/>

答案 4 :(得分:0)

解决方法是:在更新<Marker/>组件时,请确保未在坐标的纬度或经度中传递null。

在遍历对象时遇到相同的错误,该对象的某些字段为空。每当出现空值时,我默认将其设置为0来解决该问题。

答案 5 :(得分:0)

简单的答案是在 MapView、Markers、Circle 等中使用的坐标......应该是浮点/双精度值而不是字符串......

通常是{latitude: "27.123123",longitude: "85.2312321"},是不是问题应该是字符串应该是{latitude: 27.123123,longitude: 85.2312321}

答案 6 :(得分:0)

<Marker
      coordinate={{
        latitude: origin.details.geometry.location.lat,
        longitude: origin.details.geometry.location.lng}}
      title={'Origin'}
    />
      <Marker
      coordinate={{
        latitude: destination.details.geometry.location.lat,
        longitude: destination.details.geometry.location.lng}}
      title={'Destination'}
    />

我可能会迟到,但上面的技巧奏效了