定位

你需要在 info.plist 中添加 NSLocationWhenInUseUsageDescription 键来定位,当你用 react-native init 来创建一个项目时,默认情况下定位是能够使用的。

定位遵循 MDN 规范:
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation

方法

static getCurrentPosition(geo_success: Function, geo_error?: Function, geo_options?: Object)

static watchPosition(success: Function, error?: Function, options?: Object)

static clearWatch(watchID: number)

static stopObserving()

例子

Edit on GitHub

  1. /* eslint no-console: 0 */
  2. 'use strict';
  3. var React = require('react-native');
  4. var {
  5. StyleSheet,
  6. Text,
  7. View,
  8. } = React;
  9. exports.framework = 'React';
  10. exports.title = 'Geolocation';
  11. exports.description = 'Examples of using the Geolocation API.';
  12. exports.examples = [
  13. {
  14. title: 'navigator.geolocation',
  15. render: function(): ReactElement {
  16. return <GeolocationExample />;
  17. },
  18. }
  19. ];
  20. var GeolocationExample = React.createClass({
  21. watchID: (null: ?number),
  22. getInitialState: function() {
  23. return {
  24. initialPosition: 'unknown',
  25. lastPosition: 'unknown',
  26. };
  27. },
  28. componentDidMount: function() {
  29. navigator.geolocation.getCurrentPosition(
  30. (initialPosition) => this.setState({initialPosition}),
  31. (error) => console.error(error)
  32. );
  33. this.watchID = navigator.geolocation.watchPosition((lastPosition) => {
  34. this.setState({lastPosition});
  35. });
  36. },
  37. componentWillUnmount: function() {
  38. navigator.geolocation.clearWatch(this.watchID);
  39. },
  40. render: function() {
  41. return (
  42. <View>
  43. <Text>
  44. <Text style={styles.title}>Initial position: </Text>
  45. {JSON.stringify(this.state.initialPosition)}
  46. </Text>
  47. <Text>
  48. <Text style={styles.title}>Current position: </Text>
  49. {JSON.stringify(this.state.lastPosition)}
  50. </Text>
  51. </View>
  52. );
  53. }
  54. });
  55. var styles = StyleSheet.create({
  56. title: {
  57. fontWeight: '500',
  58. },
  59. });