首页 > 解决方案 > 将折线与本机地图一起使用时出现空引用错误

问题描述

当我使用折线时,它给了我这个错误: attempt to invoke interface method 'java.util.iterator java.util.list.iterator()' on a null object

起初,我以为我做错了什么,或者我误用了 google-map API,所以我尝试了一些硬编码的坐标(如下面的代码所示),但没有任何进展。如果我删除折线部分,代码将运行良好。我用谷歌搜索希望找到任何解决方案,但也没有任何成功。

在安装了 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',
  },
});



标签: javascriptandroidgoogle-mapsreact-nativereact-native-android

解决方案


//use condional rendering
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,
direct : false

}

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, direct:true})

} 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, 
      }}
    >
{this.state.direct &&    
<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>
)

} }


推荐阅读