Ошибка нулевой ссылки при использовании Polyline с картами реагирования - PullRequest
0 голосов
/ 26 июня 2019

Когда я использую Polyline, это дает мне эту ошибку: attempt to invoke interface method 'java.util.iterator java.util.list.iterator()' on a null object

Сначала я подумал, что сделал что-то не так, или я неправильно использовал API-интерфейс google-map, поэтому я попытался использовать некоторые жестко запрограммированные координаты (как показано в моем коде ниже), но без какого-либо прогресса. Код будет работать нормально, если я удалю часть Polyline. Я погуглил в надежде найти какое-то решение, но безуспешно.

  • немного информации о платформе разработчика:
  • Экспо версия 2.19.1
  • версия пряжи 1.16.0
  • Версия узла 10.15.2

Тестирование на физическом устройстве с установленным Android PI.

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Permissions, MapView } from 'expo'

// import Polyline from '@mapbox/polyline'
import { Polyline } from 'react-native-maps'

const locations = require('./locations.json')

export default class App extends React.Component {

  state = {
    latitude: null,
    longitude: null,
    locations: locations
  }

  componentDidMount() {
    this.GetLocations()
  }


  GetLocations = async () => {
    const { status } = await Permissions.getAsync(Permissions.LOCATION)
    if (status !== 'granted') {
      const response = await Permissions.askAsync(Permissions.LOCATION)
    }

    navigator.geolocation.getCurrentPosition(
      ({ coords: { latitude, longitude }}) => this.setState({ latitude, longitude}, this.mergeCoords),
      (err) => console.log(`Error: ${err}`)
    )

    const { locations: [sampleLocation] } = this.state
    this.setState({
      desLatitude: sampleLocation.coords.latitude,
      desLongitude: sampleLocation.coords.longitude,
    }, this.mergeCoords)
  }

  mergeCoords = () => {
    const { latitude, longitude, desLatitude, desLongitude } = this.state
    const hasStartAndEnd = ( latitude !== null && desLatitude !== null )

    // if the line have start and end 
    if (hasStartAndEnd) {
      const concatStart = `${latitude},${longitude}`
      const concatEnd = `${desLatitude},${desLongitude}`
      this.getDirections(concatStart, concatEnd)
    }
  }


  async getDirections(startLoc, desLoc) {
    try {
      // const res =  await fetch(`https://maps.googleapis.com/maps/api/directions/json?key=MY_API_KEY&origin=${startLoc}&destination=${desLoc}`)
      // const resJson = await res.json()
      // const points = Polyline.decode(resJson.routes[0].overview_polyline.points)
      // const coords = points.map( point => {
      //   return {
      //     latitude: point[0],
      //     longitude: point[1]
      //   }
      // })


      const coords = {
        latitude: 31.262353,        
        longitude: 29.989506,     
      }
      console.log("point, coords: ", coord)
      this.setState({coords})

    } catch(err) {
      console.log('Error: ', err)
    }
  }

  render() {
    const { latitude, longitude, coords } = this.state

    if (latitude) {
      return (
        <MapView 
          style={{ flex: 1 }}
          showsUserLocation
          initialRegion={{
            latitude,
            longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421, 
          }}
        >
          <MapView.Polyline
            strokeWidth={2}
            strokeColor="red"
            coordinates={coords}
          />

        </MapView>
      )
    }

    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        <Text>We need your permissions !!</Text>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});



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