article

Tsuneki@Amazon avatar image
Tsuneki@Amazon posted

サンプルコード紹介:リアルタイム位置情報を利用するスキルの実装方法

Alexaスキル向け位置情報サービスを使用して、ユーザーのリアルタイムの位置情報を活用したスキルを作成することができます。

今回は、より簡単に実装できるようにサンプルコードを掲載します。


Alexaスキル向け位置情報サービスは以下の5つステップで実装することができます。


① パーミッションの設定

  開発者コンソールの「アクセス権限」で「位置情報サービス」を有効にする


② デバイスの位置情報サービスのサポート状況を確認

③ Geolocationオブジェクトを取得

④ パーミッションが許諾されているかの確認

locationServicesオブジェクトまたはcoordinateオブジェクトから必要な情報を取得


const PERMISSIONS = ["alexa::devices:all:geolocation:read"];
const messages = {
  NOTIFY_MISSING_PERMISSIONS:
    "アクセス権が有効になっていないようです。アレクサアプリで位置情報へのアクセス権を有効にしてください",
  NOTIFY_DEVICE_NOT_SUPPORT:
    "このデバイスでは位置情報サービスを利用することはできません。Alexaアプリからお試しください。",
  ERROR: "すみません。エラーが発生しました。",
};


//GetGeoLocationIntentのHandler
const GetGeoLocationIntent = {
  canHandle(handlerInput) {
    return (
      handlerInput.requestEnvelope.request.type === "IntentRequest" &&
      handlerInput.requestEnvelope.request.intent.name ===
        "GetGeoLocationIntent"
    );
  },
  handle(handlerInput) {
    var context = handlerInput.requestEnvelope.context;
    var isGeolocationSupported =
      context.System.device.supportedInterfaces.Geolocation;

  //② デバイスがGeolocationをサポートしているかを確認
    if (isGeolocationSupported) {

  //③ Geolocationオブジェクトを取得
      const geoObject = context.Geolocation;

  //④ デバイスで位置情報の使用許諾を促す処理
      if (!geoObject || !geoObject.coordinate) {
        return handlerInput.responseBuilder
          .speak(messages.NOTIFY_MISSING_PERMISSIONS)
          .withAskForPermissionsConsentCard(PERMISSIONS)
          .getResponse();

      } else {

    //⑤ coordinateオブジェクトから緯度と経度を取得
        const latitude = geoObject.coordinate.latitudeInDegrees;
        const longtitude = geoObject.coordinate.longitudeInDegrees;
        const speechText =
          "現在地の緯度は" + latitude + "。経度は" + longtitude + "です。";
        return handlerInput.responseBuilder
          .speak(speechText)
          .withSimpleCard("現在地", speechText)
          .getResponse();
      }
    } else {
      return handlerInput.responseBuilder
        .speak(messages.NOTIFY_DEVICE_NOT_SUPPORT)
        .getResponse();
    }
  }
};


ご指摘、ご要望がございましたら、お気軽にコメント願います。


Alexa Skills Kit (ASK) (日本語) スペースでは、スキル開発に関する質問や、他のメンバーの質問に対する回答を投稿することができます。お気軽に投稿ください。

alexaskillawards2019
10 |5000

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Article

Contributors

tsuneki contributed to this article

Related Articles