从展览地点获取经纬度,以获取地图

时间:2018-11-18 07:02:28

标签: location android-mapview expo

我在expo的位置文档中找到了此代码:

state = {
location: null,
errorMessage: null,
};

componentWillMount() {
    if (Platform.OS === 'android' && !Constants.isDevice) {
  this.setState({
    errorMessage: 'Oops, this will not work on Sketch in an Android 
    emulator. Try it on your device!',
    });
    } else {
  this._getLocationAsync();
   }
  }

    _getLocationAsync = async () => {
      let { status } = await Permissions.askAsync(Permissions.LOCATION);
   if (status !== 'granted') {
      this.setState({
    errorMessage: 'Permission to access location was denied',
   });
   }

     let location = await Location.getCurrentPositionAsync({});
   this.setState({ location });
    };

  render() {
   let text = 'Waiting..';
   if (this.state.errorMessage) {
    text = this.state.errorMessage;
   } else if (this.state.location) {
    text = JSON.stringify(this.state.location);
    }

   return (
     <View style={styles.container}>
     <Text style={styles.paragraph}>{text}</Text>
       </View>
      );
      }
     }

通过返回纬度,经度,准确性时间戳等信息,对我来说效果很好。

有人可以告诉我如何获取坐标并将其绘制在地图上吗?我想使用lat,long状态并将其从我的位置访问的值传递到该状态,以进一步将其放入mapview的初始区域

任何可以帮助的人?

1 个答案:

答案 0 :(得分:0)

我知道这个答案有点晚了,但是如果有人碰到它,这就是我所做的:

在状态中添加了地区属性

state = {
    location: null,
    region: null,
    errorMessage: null,
};

在getLocations中,我将从getCurrentPositionAsync()调用返回的位置对象转换为Region:

getLocationAsync = async () => {
        let { status } = await Permissions.askAsync(Permissions.LOCATION);
        if (status !== 'granted') {
            this.setState({
                errorMessage: 'Permission to access location was denied',
            });
        }

        let location = await Location.getCurrentPositionAsync({});

        const region = {
            latitude: location.coords.latitude,
            longitude: location.coords.longitude,
            latitudeDelta: 1.0,
            longitudeDelta: 1.0
        }

        this.setState({ location, region });
    };

最后,在render方法中,我使用state的region属性在mapview中设置区域:

render() {
        return (
            <MapView
                initialRegion={this.state.region}
            />
        );
    }

获取位置的异步调用完成后,地图将跳至当前位置。