简体   繁体   English

将 Polyline 与 react-native 地图一起使用时出现空引用错误

[英]Null reference error while using Polyline with react-native maps

When I use Polyline it gives me this error: attempt to invoke interface method 'java.util.iterator java.util.list.iterator()' on a null object当我使用 Polyline 时,它​​给了我这个错误: attempt to invoke interface method 'java.util.iterator java.util.list.iterator()' on a null object

At first, I thought I made something wrong or I mis-used google-map API so I tried with some hard-coded coords (as shown in my code below) but without any progress.起初,我以为我做错了什么,或者我误用了 google-map API,所以我尝试了一些硬编码的坐标(如下面的代码所示),但没有任何进展。 The code will run fine if I remove the Polyline part.如果我删除 Polyline 部分,代码将运行良好。 I googled hoping to find any solution but without any success also.我用谷歌搜索希望找到任何解决方案,但也没有任何成功。

  • some info my about dev platform:我关于开发平台的一些信息:
  • expo version 2.19.1世博会版本 2.19.1
  • yarn version 1.16.0纱线版本 1.16.0
  • Node version 10.15.2节点版本 10.15.2

Testing on a physical device with android PI installed.在安装了 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',
  },
});



//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>
)

} } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 autoGenerateWrapperClass为null react-native - autoGenerateWrapperClass is null react-native 使用 react-native(javascript) 在 Firestore 中的文档参考 - Document reference in firestore using react-native(javascript) 使用带有 http://localhost:3456/fileName/ 的 epubjs 时,本机 android 应用程序中出现空响应错误 - empty response error in react-native android app while using epubjs with http://localhost:3456/fileName/ 运行 `react-native run-android` 时出错 - Getting error while running `react-native run-android` 通过AsyncStorage React-native输入数据时出错 - Getting error while entering data via AsyncStorage React-native React-Native:将组件导入App.js时出错 - React-Native : error while import component to App.js 尝试登录时反应本机,Firebase网络错误 - React-native, Firebase network error while trying to log in React-Native AirBnb地图未渲染 - React-Native AirBnb Maps not rendering React-native,地图,在“ MapView”中将道具“ region.latitude”标记为必需,但其值为null - React-native, maps,The prop 'region.latitude' is marked as required in 'MapView' but it's value is null 如何在具有许多点(纬度和经度)的反应原生地图上绘制折线? - How to draw polyline on react native maps with many points(latitude and longitude)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM