如何使用react-native-maps

时间:2017-11-29 17:31:51

标签: android react-native geolocation react-native-maps

我尝试使用react-native贴图在Android设备上的当前用户地理位置渲染地图。

以下是我到目前为止所做的事情:

import React, { Component } from 'react';

import {
  View,
  StyleSheet,
  Dimensions,
} from 'react-native';

import MapView from 'react-native-maps';

const {width, height} = Dimensions.get('window')

const SCREEN_HEIGHT = height
const SCREEN_WIDTH = width
const ASPECT_RATIO = width / height
const LATITUDE_DELTA = 0.0922
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO

class MapComponent extends Component {
  constructor() {
    super()
    this.state = {
      initialPosition: {
        latitude: 0,
        longitude: 0,
        latitudeDelta: 0,
        longitudeDelta: 0,
      },
    }
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition((position) => {
      var lat = parseFloat(position.coords.latitude)
      var long = parseFloat(position.coords.longitude)

      var initialRegion = {
        latitude: lat,
        longitude: long,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      }

      this.setState({initialPosition: initialRegion})
    },
    (error) => alert(JSON.stringify(error)),
    {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000});
  }


  renderScreen = () => {
      return (
        <View style={styles.container}>
          <MapView
            style={styles.map}
            initialRegion={this.state.initialPosition}/>
        </View>
      );
  }

  render() {
    return (
      this.renderScreen()
    );
  }
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  map: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
});

export default MapComponent;

地图会按预期呈现,但不会在当前设备地理位置中呈现。 (它呈现在海洋中央)

权限已在AndroidManifest.xml中设置为:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

20秒后,我收到一条警报说,&#34;位置请求已超时&#34; &#34;代码3&#34;

我做错了什么?

4 个答案:

答案 0 :(得分:0)

它在我的机器上运行良好。我所做的唯一更改是在StyleSheet中。

container: {
    position: 'absolute',
    height : SCREEN_HEIGHT,
    width : SCREEN_WIDTH,
    justifyContent: 'flex-end',
    alignItems: 'center',
}

此后,它呈现了我的位置。您可以在其后添加标记以显示您的位置。

答案 1 :(得分:0)

这对我有用。第三种选择是创建问题的原因。

navigator.geolocation.getCurrentPosition() =>{

},
 err => {

},
{ enableHighAccuracy: false, timeout: 20000}, //this worked for me

答案 2 :(得分:0)

navigator.geolocation.getCurrentPosition()已过时。
请改用@react-native-community/geolocation

npm install @react-native-community/geolocation --save

答案 3 :(得分:0)

1.npm安装@ react-native-community / geolocation --save
2.从'@ react-native-community / geolocation'导入地理位置;
3.navigator.geolocation.getCurrentPosition => Geolocation.getCurrentPosition