React Native Null Reference - Maps & Markers (Android)

巧了我就是萌 提交于 2020-01-05 05:30:27

问题


Hey Guys Iam getting an error on my Android Devices.

On Iphone it works very well I'am getting my Markers in maps but on Android iam getting this Error

Click for the Image

Since i upgraded the Code with geolib where iam filtering markers out which are not near to me it won't work on Android...

Anybody an idea?

this is my Code:

import React from 'react';
import MapView from 'react-native-maps';
import Marker from 'react-native-maps';
import Geolib from 'geolib';

import {
  View,
  Text,
  StyleSheet,
  Button,
} from "react-native";

const geolib = require('geolib');

class Grillplaetze extends React.Component {

  constructor() {

      super();
      this.state = {
        markers: [],
        loaded: false
      }

    }

    componentDidMount() {
      this.getPosition();
    }

    getPosition(){
  navigator.geolocation.getCurrentPosition(
    (position) => {
    console.log(position);
      this.setState({
        region: {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          latitudeDelta:  0.020,
          longitudeDelta:  0.020,
        }
      }, () => this.getLocations());
    },
    (error) => this.setState({ error: error.message }),
    { enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 },
  );
}

    getLocations() {

  return fetch('http://media-panda.de/bp/whs.geojson')
  .then(response => response.json())
  .then(responseData => {
    let { region } = this.state;
    let { latitude, longitude } = region;

    let markers = responseData.features.map(feature =>  {
      let coords = feature.geometry.coordinates
      return {
        coordinate: {
          latitude: coords[1],
          longitude: coords[0],
        }
      }
    }).filter(marker => {
      let distance = this.calculateDistance(latitude, longitude, marker.coordinate.latitude, marker.coordinate.longitude);
      return distance <= 500;
    });

    this.setState({
      markers: markers,
      loaded: true,
    });
  }).done();
  }

  calculateDistance(origLat, origLon, markerLat, markerLon) {
    return geolib.getDistance(
      {latitude: origLat, longitude: origLon},
      {latitude: markerLat, longitude: markerLon}
    );
  }


  render() {

  return (
      <View style={styles.container}>
      <MapView.Animated
        style={styles.map}
        region={this.state.region}
        showsUserLocation={true}
      >
       {this.state.markers.map(marker => (
          <MapView.Marker
            coordinate={marker.coordinate}
          />
       ))}
       <MapView.Circle
                key = { (this.state.latitude + this.state.longitude).toString() }
                center = { this.state.region }
                radius = { 500 }
                strokeWidth = { 1 }
                strokeColor = { '#1a66ff' }
                fillColor = { 'rgba(230,238,255,0.5)' }

        />
       </MapView.Animated>
      </View>
     );
  }
}

export default Grillplaetze;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',

  },
  map: {
    width: "100%",
    height: "100%",
  },
})

回答1:


Your errors aren't related to your implementation of the geolib but instead they are due to your implementation of the MapView.Circle.

If we look at the documentation the MapView.Circle we see the following:

|   Prop   |   Type   |   Default  |                     Note                       |
|----------|----------|------------|------------------------------------------------|
| `center` | `LatLng` | (Required) | The coordinate of the center of the circle .   
| `radius` | `Number` | (Required) | The radius of the circle to be drawn (in meters)

Both the center and the radius are required fields.

If we look at your code:

<MapView.Circle
  key = { (this.state.latitude + this.state.longitude).toString() }
  center = { this.state.region }
  radius = { 500 }
  strokeWidth = { 1 }
  strokeColor = { '#1a66ff' }
  fillColor = { 'rgba(230,238,255,0.5)' }
/>

It would appear that you have set them, however you have not actually set the region. You can confirm this by checking your initial state.

constructor () {
  super();
  this.state = {
    markers: [],
    loaded: false
  }
}

Notice that you have not set an initial region for the map. This is what is causing your error. The app is trying to handle the undefined value for the region.

To overcome this the easiest way is to set an initial region for the map in state.

Something like this:

constructor () {
  super();
  this.state = {
    markers: [],
    loaded: false,
    region: {
      latitude: 0,
      longitude: 0,
      latitudeDelta: 0.020,
      longitudeDelta: 0.020
    },
    latitude: 1,
    longitude: 1
  };
}

If you app is for a specific region then it may make sense to pick an initial region that is close to where you app is going to be used.

Also note in your MapView.Circle code you are also using undefined values of latitude and longitude for the key. I don't think that you need to define a key property for the MapView.Circle. I cannot find any mention of this being a requirement in the documentation.

Making the above changes allows the code to work.


Some other points.

  1. You are importing geolib twice. You only need to do it once. You should either have import GeoLib from 'geolib'; or const geolib = require('geolib'); you don't need both. Seeing as you are using geolib with a lower case, I would just remove import GeoLib from 'geolib';
  2. You are importing Markers from react-native-maps in the wrong way. It should be imported as import { Markers } from 'react-native-maps, however you are using the Markers as MapView.Markers which is absolutely fin. I think you can remove the unused and incorrect import Markers from 'react-native-maps
  3. MapView.Animated I am not 100% that this is correct or required. I haven't seen it used in this way before. However if it is not causing you issues then I suppose it isn't really a problem.
  4. You should also add a key prop on your Markers so that you suppress the warning that it is missing. This should be something unique.


来源:https://stackoverflow.com/questions/55141383/react-native-null-reference-maps-markers-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!