開発者ドキュメント

ReactNativeでのジオロケーションの使用

React Nativeは、Web上でネイティブな GeolocationAPIを利用します。 このAPIは、次のようなさまざまなメソッドを返します。 getCurrentPosition、 と watchPosition ReactNativeポリフィルで利用できます。 React Nativeアプリでの使用方法を示すために、以下を使用して統合します。 react-native-cli.

入門

使用する react-native-cli テンプレートがなく、開始するための定型コードがほとんどないことを意味します。 次のコマンドを使用してプロジェクトを生成します。 ローカルマシンにまだインストールしていない場合は、以下に示す最初のコマンドを使用してください。

# to install the cli
$ npm install -g react-native-cli

# to scafold an RN project
$ react-native init geo-example

したがって、プロジェクトディレクトリが生成されたら、そのディレクトリに移動して実行します npm start すべてが正しくインストールされているかどうかを確認します。 Macを使用している場合は、 ios 検証するシミュレータ。 WindowsおよびLinuxユーザーの場合、Androidエミュレーターが友だちになります。

GeolocationAPIへのアクセス

GeolocationAPIはグローバルとして存在します navigator Webと同じように、ReactNativeのオブジェクト。 経由でアクセスできます navigator.geolocation ソースコードにあり、インポートする必要はありません。

デモンストレーションの目的で、 getCurrentPosition GeolocationAPIのメソッド。 このメソッドを使用すると、モバイルアプリはユーザーの場所を要求し、成功コールバック、エラーコールバック、構成オブジェクトの3つのパラメーターを受け入れることができます。

navigator.geolocation.getCurrentPosition(
  position => {
    const location = JSON.stringify(position);

    this.setState({ location });
  },
  error => Alert.alert(error.message),
  { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);

上記の成功コールバックには position エラーなしで実行された場合、次のプロパティを持つオブジェクトである引数:

{
  "timestamp": 1533729980953.91
  "coords": {
    "accuracy": 5,
    "altitude": 0,
    "altitudeAccuracy": -1,
    "heading": -1,
    "latitude": 37.785834,
    "longitude": -122.406417,
    "speed": -1
  }
}

変更します App.js 開始するには、ReactNativeプロジェクトで。 まず、テキストを表示する基本的なクラスコンポーネントを定義します。 Find My Coords?:

App.js
import React, { Component } from "react";
import { View, Text } from "react-native";

export default class App extends Component {
  render() {
    return (
      <View>
        <Text>Find My Coords?</Text>
      </View>
    );
  }
}

GeolocationAPIの実装

それでは、GeolocationAPI関数を実装しましょう getCurrentPosition 私たちのアプリで。 開ける App.js 次のコードを記述します。

App.js
import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Alert,
  TouchableOpacity
} from "react-native";

export default class App extends Component {
  state = {
    location: null
  };

  findCoordinates = () => {
    navigator.geolocation.getCurrentPosition(
      position => {
        const location = JSON.stringify(position);

        this.setState({ location });
      },
      error => Alert.alert(error.message),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
    );
  };

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={this.findCoordinates}>
          <Text style={styles.welcome}>Find My Coords?</Text>
          <Text>Location: {this.state.location}</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

TouchableOpacityのインポートを開始します。 これは、ユーザーのタッチに正確に応答するラッパーです。 React Nativeモバイルアプリでは、そのラッパーコンポーネントを頻繁に使用します。 Webアプリケーションのボタンと考えてください。 この新しくインポートされたラッパーは、指定されたメソッドをトリガーするonPressプロパティを受け入れます。 findCoordinates 私たちの場合には。

findCoordinates ユーザーの場所を取得するためのロジックを保持します。 また、ローカル状態を使用して、位置オブジェクトによって提供されたデータから座標を表示しています。 テキスト Find My Coords? クリック可能になりました。

React Nativeを使用して、少しスタイルを整えましょう。 StyleSheet:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  welcome: {
    fontSize: 20,
    textAlign: "center",
    margin: 10
  },
  instructions: {
    textAlign: "center",
    color: "#333333",
    marginBottom: 5
  }
});

この時点では、例は期待どおりに機能しません。 ユーザーの場所にアクセスするための許可を求める必要があります。 次にそれを修正しましょう。

許可を求める

iOS、プロジェクトがを使用して作成される場合、ジオロケーションはデフォルトで有効になっています react-native-cli. それを使用するには、というキーを含める必要があります <key>NSLocationWhenInUseUsageDescription</key> の中に info.plist 内にあるファイル ios/findCoordsApp ディレクトリ。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>findCoordsApp</string>
    [..]
    <key>NSLocationWhenInUseUsageDescription</key>
    <string></string>
    <key>NSAppTransportSecurity</key>
    <!--See http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/ -->
  [...]
</dict>
</plist>

為に Android、次の行を追加する必要があります android/app/src/AndroidManifest.xml:

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

まとめ

これで、アプリケーションを実行すると、次の画面が表示されます。

テキストをクリックすると、アプリケーションがユーザーの場所を要求することを許可するかどうかを尋ねられます。

[許可]を押すと、次の画面が表示されます。

これは非常に単純な例でしたが、そこからさらに興味深い/便利なものを作成することができます。 ReactNativeアプリケーションでのGeolocationAPIの操作について詳しく知りたい場合は、公式のドキュメントを参照してください。

モバイルバージョンを終了