如何创建在React-Native中检测自动位置的地图 [英] how to create maps which detect automatic location in React-Native

查看:110
本文介绍了如何创建在React-Native中检测自动位置的地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在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位置);
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);

$ b返回(
< View style = {styles.container}>
< MapView
ref =map
mapType =terrain
style = {styles.map}
initialPosition = {this.state.initialPosition}
lastPosition = {this.state。 lastPosition}
>
< / MapView>
< / View>

可以请你改正吗?

预先感谢

解决方案

您可以使用React原生地理位置来完成此操作:

https://facebook.github.io/react-native/docs/geolocation.html



现在已经有一个很好的例子可以这样做:

  componentDidMount:function(){
navigator.geolocation.getCurrentPosition(
(position )=> {
var i nitialPosition = 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});
});



$ b你现在有了initialPosition(经度和纬度)硬编码值。当位置发生变化时,watchPosition会调用成功回调。



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






更新后的答案: Genymotion模拟器来运行这个。如果您还要在Genymotion上运行此代码,请确保您已安装 Google Play支持,否则反应原生地图将无法使用。 如果您使用的是物理设备,则无需执行此步骤。
$ b 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 /数据已启用,否则您的设备无法检索您的当前位置。

  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;

//(初始静态位置)孟买
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
}
});
},
(错误)=> alert(error.message),
{enableHighAccuracy:true,timeout:20000,maximumAge:1000}
);

this.watchID = navigator.geolocation。 watchPosition((position)=> {
const newRegion = {
l atitude: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});

$ b返回(
< 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)',
paddingHorizo​​ntal:18,
paddingVertical:12,
borderRadius:20,
},
});

module.exports = CustomMap;

运行上面的代码,您会发现原来的静态位置(孟买)



如果您需要跟踪位置变化,请使用 watchPosition onRegionChange ,否则如果您只需要获取初始位置,请移除 watchPosition 步骤。


I have created maps in react-native referring to https://github.com/lelandrichardson/react-native-maps map is created but i want to detect automatic location using gps. Here is the code which renders map with static latitude and longitude. Here's my updated code. But it still not rendering perfect location

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>

can you please correct it?

Thanks in advance

解决方案

You can do that using React-native geolocation:
https://facebook.github.io/react-native/docs/geolocation.html

There is already a good example there on how you can do that:

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

You now have the initialPosition (latitude and longitude), use it instead of your hard coded value. The watchPosition invokes the success callback whenever the location changes.

I am currently using this to find local restaurants in our app.


Updated Answer:

I am using Genymotion emulator to run this. If you are also going to run this code on Genymotion, please make sure you have installed Google Play support, otherwise react-native-maps won't work. You don't have to do this step if you are using a physical device.

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

Regarding Geolocation, please make sure you have added ACCESS_FINE_LOCATION permission in the AndroidManifest.xml:

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

Otherwise you will get an error: "Looks like the app doesn't have the permission to access location."

Also please make sure that your GPS/Wifi/Data is enabled, otherwise your device cannot retrieve your current location.

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;

Running the above code, you should find that your original static location (Mumbai) is overwritten with your current location from the device through componentDidMount when getCurrentPosition is called.

If you need to track changes in position, use watchPosition in combination with onRegionChange, otherwise if you just need to get the initial position remove watchPosition step.

这篇关于如何创建在React-Native中检测自动位置的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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