使用 react-native-maps 在 ReactNative 中获取当前位置、经纬度

Get current location, latitude and longitude in ReactNative using react-native-maps

我正在开发地图位置。当我单击某个特定位置时,我会得到经纬度,但不会得到当前位置、纬度和经度。

不知道怎么查

我怎样才能得到它们,我怎样才能把标记放在那个位置?

这是我的代码:

class Maps extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      region: {
        latitude:       LATITUDE,
        longitude:      LONGITUDE,
        latitudeDelta:  LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      },
      marker: {
        latlng:{
          latitude:       null,
          longitude:      null,
          latitudeDelta:  LATITUDE_DELTA,
          longitudeDelta: LONGITUDE_DELTA
        }
      }
    }
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition (
      (position) => { alert("value:" + position) },
      (error)    => { console.log(error) },
      {
        enableHighAccuracy: true,
        timeout:            20000,
        maximumAge:         10000
      }
    )
  }

  onMapPress(e) {
    alert("coordinates:" + JSON.stringify(e.nativeEvent.coordinate))
      this.setState({
        marker: [{ coordinate: e.nativeEvent.coordinate }]
      })
    }

  render() {
    return (
      <View style={styles.container}>
        <View style={{flexGrow:1}}>
          <MapView
            ref="map"
            provider={this.props.provider}
            style={styles.map}
            onPress={this.onMapPress.bind(this)}
            provider = {PROVIDER_DEFAULT}
            mapType="standard"
            zoomEnabled={true}
            pitchEnabled={true}
            showsUserLocation={true}
            followsUserLocation={true}
            showsCompass={true}
            showsBuildings={true}
            showsTraffic={true}
            showsIndoors={true}>
          </MapView>
        </View>
      </View>
    )
  }
}

我建议您阅读这份关于地理定位的官方文档:https://facebook.github.io/react-native/docs/geolocation.html

然后,根据当前位置,您可以将该信息放入您的状态:

navigator.geolocation.getCurrentPosition((position) => {
    this.setState({position: {longitude: position.longitude, latitude: position.latitude}});
}, (error) => {
    alert(JSON.stringify(error))
}, {
    enableHighAccuracy: true,
    timeout: 20000,
    maximumAge: 1000
});

接下来,您将能够在渲染方法中使用标记组成最终视图:

render() {
  return (
    <MapView ...>
      <MapView.Marker
        coordinate={this.state.position}
        title="title"
        description="description"
      />
    </MapView>
  )
}

我是按照这些步骤使用 react-native@0.42.3react-native-maps@^0.13.1 并使用 react-native@0.44.0react-native-maps@^0.15.2 在日期完成的:

state、最后一个longitude和最后一个latitude设置一个mapRegion对象为null:

state = {
  mapRegion: null,
  lastLat: null,
  lastLong: null,
}

然后在你的 componentDidMount() 函数中观察当前位置的每个变化:

  componentDidMount() {
    this.watchID = navigator.geolocation.watchPosition((position) => {
      ...
    });
  }

如果有更改,请在您的 this.state.mapRegion 中更新它们,传递实际坐标和 delta 值(我的可能与您的不同,因此请调整它们):

  componentDidMount() {
    this.watchID = navigator.geolocation.watchPosition((position) => {
      // Create the object to update this.state.mapRegion through the onRegionChange function
      let region = {
        latitude:       position.coords.latitude,
        longitude:      position.coords.longitude,
        latitudeDelta:  0.00922*1.5,
        longitudeDelta: 0.00421*1.5
      }
      this.onRegionChange(region, region.latitude, region.longitude);
    }, (error)=>console.log(error));
  }

然后您需要 onRegionChange() 函数,该函数用于 "set" 为 componentDidMount() 函数中的元素添加新值:

  onRegionChange(region, lastLat, lastLong) {
    this.setState({
      mapRegion: region,
      // If there are no new values set the current ones
      lastLat: lastLat || this.state.lastLat,
      lastLong: lastLong || this.state.lastLong
    });
  }

卸载 componentWillUnmount() 上的地理定位:

  componentWillUnmount() {
    navigator.geolocation.clearWatch(this.watchID);
  }

并渲染 MapView 传递你当前的 mapRegion 对象,其中的 MapView.Marker 只是向你展示当前的 latitudelongitude当他们改变时:

  render() {
    return (
      <View style={{flex: 1}}>
        <MapView
          style={styles.map}
          region={this.state.mapRegion}
          showsUserLocation={true}
          followUserLocation={true}
          onRegionChange={this.onRegionChange.bind(this)}>
          <MapView.Marker
            coordinate={{
              latitude: (this.state.lastLat + 0.00050) || -36.82339,
              longitude: (this.state.lastLong + 0.00050) || -73.03569,
            }}>
            <View>
              <Text style={{color: '#000'}}>
                { this.state.lastLong } / { this.state.lastLat }
              </Text>
            </View>
          </MapView.Marker>
        </MapView>
      </View>
    );
  }

为您的地图添加 StyleSheet.absoluteFillObject 以便使用您设备的整个宽度和高度正确渲染它。

const styles = StyleSheet.create({
  map: {
    ...StyleSheet.absoluteFillObject,
  }
});

因此,对于您的 onPress() 函数,您可以执行类似于 onRegionChange() 的操作,即获取实际坐标并进行设置:

  onMapPress(e) {
    let region = {
      latitude:       e.nativeEvent.coordinate.latitude,
      longitude:      e.nativeEvent.coordinate.longitude,
      latitudeDelta:  0.00922*1.5,
      longitudeDelta: 0.00421*1.5
    }
    this.onRegionChange(region, region.latitude, region.longitude);
  }

检查 expo.io 上的完整代码(尽管 react-native-maps 未安装)

使用以下代码查找位置权限:

try {
    const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
    )
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        alert("You can use the location")
    }
    else {
        alert("Location permission denied")
    }
}
catch (err) {
    console.warn(err)
}

使用以下代码获取当前位置的经纬度:

this.watchID = navigator.geolocation.watchPosition((position) => {
    let region = {
        latitude:       position.coords.latitude,
        longitude:      position.coords.longitude,
        latitudeDelta:  0.00922*1.5,
        longitudeDelta: 0.00421*1.5
    }
}