【问题标题】:how to create maps which detect automatic location in React-Native如何在 React-Native 中创建检测自动位置的地图
【发布时间】:2016-06-30 12:06:58
【问题描述】:

我在 react-native 中创建了地图,参考 https://github.com/lelandrichardson/react-native-maps 地图已创建,但我想使用 gps 检测自动位置。这是使用静态纬度和经度呈现地图的代码。 这是我更新的代码。但它仍然无法呈现完美的位置

getInitialState() {
    return {
        initialPosition: 'unknown',
        lastPosition: 'unknown',
    };
  },

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        var initialPosition = JSON.stringify(position);
        this.setState({initialPosition});
      },
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    );
    this.watchID = navigator.geolocation.watchPosition((position) => {
      var lastPosition = JSON.stringify(position);
      this.setState({lastPosition});
    });
  },

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

  render() {
    return (
      <View style={styles.container}>
        <MapView
          ref="map"
          mapType="terrain"
          style={styles.map}
          initialPosition={this.state.initialPosition}
          lastPosition={this.state.lastPosition}
        >
        </MapView>
      </View>

你能纠正一下吗?

提前致谢

【问题讨论】:

    标签: javascript android gps maps react-native


    【解决方案1】:

    您可以使用 React-native 地理位置来做到这一点:
    https://facebook.github.io/react-native/docs/geolocation.html

    那里已经有一个很好的例子来说明如何做到这一点:

    componentDidMount: function() {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          var initialPosition = JSON.stringify(position);
          this.setState({initialPosition});
        },
        (error) => alert(error.message),
        {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
      );
      this.watchID = navigator.geolocation.watchPosition((position) => {
        var lastPosition = JSON.stringify(position);
        this.setState({lastPosition});
      });
    }
    

    您现在有了初始位置(纬度和经度),使用它来代替您的硬编码值。只要位置发生变化,watchPosition 就会调用成功回调。

    我目前正在使用它在我们的应用中查找当地餐馆。


    更新答案:

    我正在使用 Genymotion 模拟器来运行它。如果您还打算在 Genymotion 上运行此代码,请确保您已安装 Google Play 支持,否则 react-native-maps 将无法工作。 如果您使用的是物理设备,则无需执行此步骤。

    https://github.com/codepath/android_guides/wiki/Genymotion-2.0-Emulators-with-Google-Play-support

    关于地理位置,请确保您在AndroidManifest.xml中添加了ACCESS_FINE_LOCATION权限:

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

    否则你会得到一个错误:“看起来该应用没有访问位置的权限。”

    另外请确保您的 GPS/Wifi/Data 已启用,否则您的设备将无法检索您当前的位置。

    var React = require('react');
    var ReactNative = require('react-native');
    var {
      StyleSheet,
      PropTypes,
      View,
      Text,
      Dimensions,
      TouchableOpacity,
    } = ReactNative;
    
    var MapView = require('react-native-maps');
    
    var { width, height } = Dimensions.get('window');
    const ASPECT_RATIO = width / height;
    
    // (Initial Static Location) Mumbai
    const LATITUDE = 19.0760;
    const LONGITUDE = 72.8777;
    
    const LATITUDE_DELTA = 0.01;
    const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
    
    var CustomMap = React.createClass({
      getInitialState() {
        return {
          region: {
            latitude: LATITUDE,
            longitude: LONGITUDE,
            latitudeDelta: LATITUDE_DELTA,
            longitudeDelta: LONGITUDE_DELTA
          },
        };
      },
    
      componentDidMount: function() {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            this.setState({
              region: {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                latitudeDelta: LATITUDE_DELTA,
                longitudeDelta: LONGITUDE_DELTA
              }
            });
          },
          (error) => alert(error.message),
          {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
        );
    
        this.watchID = navigator.geolocation.watchPosition((position) => {
          const newRegion = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
            latitudeDelta: LATITUDE_DELTA,
            longitudeDelta: LONGITUDE_DELTA
          }
    
          this.onRegionChange(newRegion);
        });
      },
    
      componentWillUnmount: function() {
        navigator.geolocation.clearWatch(this.watchID);
      },
    
      onRegionChange(region) {
        this.setState({ region });
      },
    
      render() {
        return (
          <View style={styles.container}>
            <MapView
              ref="map"
              mapType="terrain"
              style={styles.map}
              region={this.state.region}
              onRegionChange={this.onRegionChange}
            >
            </MapView>
            <View style={styles.bubble}>
              <Text style={{ textAlign: 'center'}}>
                {`${this.state.region.latitude.toPrecision(7)}, ${this.state.region.longitude.toPrecision(7)}`}
              </Text>
            </View>
          </View>
        );
      },
    });
    
    var 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,
      },
      bubble: {
        backgroundColor: 'rgba(255,255,255,0.7)',
        paddingHorizontal: 18,
        paddingVertical: 12,
        borderRadius: 20,
      },
    });
    
    module.exports = CustomMap;
    

    运行上面的代码,你应该会发现,当调用 getCurrentPosition 时,你原来的静态位置(孟买)被设备通过 componentDidMount 覆盖的当前位置。

    如果需要跟踪位置变化,请结合onRegionChange使用watchPosition,否则如果只需要获取初始位置删除watchPosition强>一步。

    【讨论】:

    • 嘿,我已经更新了我的代码,您可以将其视为问题,但完美的位置仍未呈现
    • 你在使用genymotion吗?您确定您的 GPS 已启用吗?您是否尝试过控制台记录位置,以确保 getCurrentPosition 返回有效位置?我还注意到您没有在 getCurrentPosition 调用中处理错误。尝试添加“(error) => alert(error.message)”,看看是否有任何错误。
    • 我正在使用物理设备进行测试。我已经删除了错误部分尝试添加它但没有成功。我的代码正确吗?
    • 很高兴听到。您介意将我的答案标记为正确吗?谢谢。
    • 你能回答给定链接上的问题stackoverflow.com/questions/38157354/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    相关资源
    最近更新 更多