2016-02-10 28 views
2

我試圖訪問iOS React Native應用程序中的地理位置。我正在查看documentation中的示例,但它完全沒有幫助。在這個例子中,我不明白如何使用Geolocation API。React Native - 地理位置

我的第一反應是做這樣的事情:

var React = require('react-native'); 
var { 
    Geolocation 
} = React; 

然後在我的代碼,這樣做:

Geolocation.getCurrentPosition((position) => { 
    console.log(position); 
}, 
(error) => { 
    console.log(error); 
}); 

不過,這似乎失敗。在這個例子中,它使用的地理位置如下:

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

然而,在導航儀的來源和爲什麼它連接到它的地理位置屬性是不完全清楚。我沒有得到什麼?

在此先感謝。

更新:

原來的解決方案是簡單地:

var Geolocation = require('Geolocation'); 

我感到困惑作爲PushNotificationIOS(衛生組織文檔是在相同的區域中的地理定位)被用於經由陣營本機:

var React = require('react-native'); 
var { 
    PushNotificationIOS 
} = React; 

回答

1

爲什麼你不使用這個例子?我不知道navigator來自哪裏,但我用這種方式,它工作正常。

您是否還在Info.plist中添加了NSLocationWhenInUseUsageDescription密鑰?

+2

但是我想知道我的軟件是如何工作的,而不僅僅是盲目地遵循例子。無論如何,我明白了,結果比我想象的要容易。我更新了OP。 – coldbuffet

+1

是的,它似乎像'navigator'是一個全球性的。正如在React文檔示例中,我不需要'require('Geolocation')'來使用'navigator.geolocation'。 –

0

**它給你的當前位置屬性並更新位置**

定義所有在構造函數中this.state變量,然後使用它。

- Don't forget to give location permission in manifest file 

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

componentDidMount(){ 
     //Alert.alert('Updated'); 
     this.watchId = navigator.geolocation.watchPosition(
      (position) => { 
       // lastpos = JSON.stringify(position); 
       this.getDeviceStatus(); 
       this.setState({ 
       latitude: position.coords.latitude, 
       longitude: position.coords.longitude, 
       speed: position.coords.speed, 
       accuracy: position.coords.accuracy, 
       heading: position.coords.heading, 
       timestamp: position.timestamp, 
       altitude: position.coords.altitude 
       }); 
      }, 
      (error) => this.setState({ error: error.message }), 
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 5 }, 
     ); 
    } 
    getDeviceStatus() 
    { 
     //Alert.alert('Device'); 
    } 
    componentWillUnmount() { 
     navigator.geolocation.clearWatch(this.watchId); 
     } 

render(){ 
    return(

      <Text> {this.state.latitude} </Text> 
      <Text> {this.state.longitude} </Text> 
      <Text> {this.state.speed} </Text> 
      <Text> {this.state.accuracy} </Text> 
      <Text> {this.state.heading} </Text> 
      <Text> {this.state.timestamp} </Text>         
      <Text> {this.state.altitude} </Text> 

    ) 
} 

出口默認LivePos;

相關問題