使用 react-native-maps 在 ReactNative 中获取当前位置、纬度和经度 [英] Get current location, latitude and longitude in ReactNative using react-native-maps

查看:209
本文介绍了使用 react-native-maps 在 ReactNative 中获取当前位置、纬度和经度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am developing a map location. When I click in some particular place I get the latitude and longitude, but not the current location, latitude and longitude.

我不知道如何找到.

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

How can I get them and how can I put the marker at that position?

这是我的代码:

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

推荐答案

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

I did it following these steps using react-native@0.42.3 and react-native-maps@^0.13.1 and using react-native@0.44.0 and react-native-maps@^0.15.2 at the date:

state中设置一个mapRegion对象,最后一个longitude和最后一个latitude:

Set a mapRegion object in the state, the last longitude and the last latitude as null:

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

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

Then within your componentDidMount() function watch for each change in the current position:

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

当你的 this.state.mapRegion 有变化时更新它们,传递实际坐标和 delta 值(我的可能与你的不同,所以调整它们):

When there are changes update them in your this.state.mapRegion, passing the actual coords and the delta values (mine can be different to yours, so adapt them):

  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() 函数,该函数用于为 componentDidMount() 函数中的元素设置"新值:

Then you need the onRegionChange() function, that's being used to "set" new values to your elements within the componentDidMount() function:

  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() 上卸载地理位置:

Unmount the geolocation on componentWillUnmount():

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

并渲染 MapView 传递您当前的 mapRegion 对象,其中的 MapView.Marker 只是为了向您显示当前的 >latitudelongitude 当它们改变时:

And render the MapView passing your current mapRegion object, the MapView.Marker inside of it is just to show you the current latitude and longitude when they change:

  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您的地图,以便使用设备的整个宽度和高度正确呈现它.

Add the StyleSheet.absoluteFillObject for your map in order to render it properly using the whole width and height of your device.

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

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

So for your onPress() function you could do something similar to the onRegionChange(), that's to get the actual coordinates and to set them:

  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代码>未安装)

Check the full code on expo.io (although react-native-maps isn't installed)

这篇关于使用 react-native-maps 在 ReactNative 中获取当前位置、纬度和经度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆