dayjournal memo

Total 975 articles!!

Try #063 – Amazon Location Serviceで住所検索機能を構築してみた

Yasunori Kirimoto's avatar

画像




画像




Amazon Location Serviceで住所検索機能を構築してみました!


先日Amazon Location Serviceが正式に一般公開されました。

Amazon Location Serviceとは、AWS内で利用できる位置情報アプリケーションを構築するためのサービスになります。現時点の機能として、地図表示機能・住所検索機能・ルート検索機能・ジオフェンス機能・トラッキング機能の5種類を利用できます。今回は、住所検索機能を追加しマップアプリケーションを構築してみました。



事前準備



Amazon Location Place indexesの設定

はじめに、AWSコンソールでAmazon Location Place indexesの設定をします。


「Place indexes」をクリックします。

画像


「Create place indexes」をクリックします。

画像


住所検索名の入力と利用データを選択します。今回は「SamplePlace」としました。

画像


作成された住所検索をクリックします。

画像


ここで表示されている「Name」と「ARN」を今後の設定で利用するのでコピーしておきます。

画像


これでAmazon Location Place indexesの設定は完了になります。



フロントエンド


次に、実際にマップアプリケーションを構築していきます。

Amazon Location Serviceの地図表示機能の構成ができていると、基本的には「MapPane.vue」の変更のみになります。


実行環境

  • node v16.3.0
  • npm v7.15.1

事前に、AWS SDK for JavaScriptのパッケージをインストールします。

npm install aws-sdk

全体構成

画像


package.json

{
  "name": "amazon-location-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@aws-amplify/ui-vue": "^1.0.12",
    "aws-amplify": "^4.1.1",
    "aws-sdk": "^2.935.0",
    "core-js": "^3.6.5",
    "maplibre-gl": "^1.14.1-rc.2",
    "vue": "^2.6.11",
    "vue-router": "^3.2.0",
    "vuetify": "^2.4.0",
    "vuex": "^3.4.0"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-plugin-vuex": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2",
    "sass": "~1.32.0",
    "sass-loader": "^10.0.0",
    "vue-cli-plugin-vuetify": "~2.4.1",
    "vue-template-compiler": "^2.6.11",
    "vuetify-loader": "^1.7.0"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}


/src/components


MapPane.vue

<!--マップコンポーネント-->
<template>
    <div class="mapPane">
        <!--マップ表示-->
        <div id="map"></div>
    </div>
</template>

<script>
    // MapLibre GL JSを読み込み
    import maplibregl from 'maplibre-gl';
    // Amplify読み込み
    import { Auth, Signer } from 'aws-amplify';
    import awsconfig from '../aws-exports';
    // Amazon Location Service読み込み
    import Location from 'aws-sdk/clients/location'
    // マップオブジェクト定義
    let map;

    export default {
        name: 'MapPane',
        data() {
            return {
                credentials: null,
                client: null,
                params: null,
            };
        },
        mounted: async function() {
            // 認証情報取得
            this.credentials = await Auth.currentCredentials();
            // マップオブジェクト生成
            this.mapCreate();
            // 住所検索
            this.addPlaceSearch();
        },
        methods: {
            // マップオブジェクト生成
            mapCreate: function() {
                // Amazon Location Maps読み込み
                map = new maplibregl.Map({
                    container: 'map',
                    style: 'sample',
                    center: [141.35585, 43.03851],
                    zoom: 14,
                    bearing: 0,
                    pitch: 60,
                    hash: true,
                    transformRequest: this.transformRequest,
                });

                // コントロール関係表示
                map.addControl(new maplibregl.NavigationControl());
            },
            // Amazon Location Maps設定
            transformRequest: function(url, resourceType) {
                if (resourceType === 'Style' && !url.includes('://')) {
                    // スタイル設定
                    url = `https://maps.geo.${awsconfig.aws_project_region}.amazonaws.com/maps/v0/maps/${url}/style-descriptor`;
                }
                if (url.includes('amazonaws.com')) {
                    return {
                        url: Signer.signUrl(url, {
                            access_key: this.credentials.accessKeyId,
                            secret_key: this.credentials.secretAccessKey,
                            session_token: this.credentials.sessionToken,
                        }),
                    };
                }
                return { url };
            },
            // Amazon Location Place indexes設定
            addPlaceSearch: function() {
                // Amazon Location Service設定
                this.client = new Location({
                    credentials: this.credentials,
                    region: awsconfig.aws_project_region,
                });
                // 住所検索設定
                this.params = {
                    IndexName: 'SamplePlace',
                    MaxResults: 1,
                    Text: 'サッポロファクトリー',
                };
                // 住所検索
                this.client.searchPlaceIndexForText(this.params, (err, data) => {
                    // 住所データ取得
                    const label = data.Results[0].Place.Label;
                    const lng = data.Results[0].Place.Geometry.Point[0];
                    const lat = data.Results[0].Place.Geometry.Point[1];
                    // 住所データ表示
                    map.on('load', function() {
                        // ポップアップ追加
                        const popup = new maplibregl.Popup({ 
                            offset: 40 
                        })
                        .setText(label);
                        // マーカー追加
                        const marker = new maplibregl.Marker({
                            // マーカーの色指定
                            color: '#005773'
                        })
                        .setLngLat([lng, lat])
                        .setPopup(popup);
                        marker.addTo(map);
                    });
                });
            },
        },
    };
</script>

<style scoped>
    #map {
        z-index: 0;
        height: 800px;
    }
</style>

Amazon Location Serviceを読み込みます。

// Amazon Location Service読み込み
import Location from 'aws-sdk/clients/location'

Amazon Location Serviceの設定と住所検索の設定をします。IndexNameに作成した住所検索の「Name」を指定します。今回は「サッポロファクトリー」を検索してみました。

// Amazon Location Service設定
this.client = new Location({
    credentials: this.credentials,
    region: awsconfig.aws_project_region
});
// 住所検索設定
this.params = {
    IndexName: 'SamplePlace',
    MaxResults: 1,
    Text: 'サッポロファクトリー',
};

Amazon Location Place indexesを利用し、住所検索結果を地図上に描画します。

// 住所検索
this.client.searchPlaceIndexForText(this.params, (err, data) => {
    // 住所データ取得
    const label = data.Results[0].Place.Label;
    const lng = data.Results[0].Place.Geometry.Point[0];
    const lat = data.Results[0].Place.Geometry.Point[1];
    // 住所データ表示
    map.on('load', function() {
        // ポップアップ追加
        const popup = new maplibregl.Popup({
            offset: 40
        })
        .setText(label);
        // マーカー追加
        const marker = new maplibregl.Marker({
            // マーカーの色指定
            color: '#005773'
        })
        .setLngLat([lng, lat])
        .setPopup(popup);
        marker.addTo(map);
    });
});


Amplifyのロール設定

最後にAmplifyのロールにAmazon Location Place indexesのポリシーを追加します。


ログイン機能で利用しているロールを検索します。「amplify-xxxxx-authRole」を選択します。

画像


「インラインポリシーの追加」をクリックします。

画像


「JSON」を選択しポリシーを設定します。Resourceは作成した住所検索の「ARN」を設定します。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Routes",
            "Effect": "Allow",
            "Action": "geo:SearchPlaceIndexForText",
            "Resource": "arn:aws:geo:us-west-2:xxxxx:place-index/SamplePlace"
        }
    ]
}

画像


これでAmplifyのロール設定は完了になります。



簡易ローカルサーバーで確認してみます。

npm run serve


ローカルサーバーを立ち上げて、ログインしてみます。Amazon Location Place indexesの表示を確認できました。

画像




Amazon Location Serviceで住所検索機能を構築できました!


Amazon Location Serviceを利用すると、手軽に住所検索が構築できることを確認できました。オプションも色々とあったりするので、このサンプルを参考にゼヒ色々と試して頂ければと思います。他の機能についても引き続き探っていきたいと思います!



MapLibre GL JSとVue.jsについて、他にも記事を書いています。よろしければぜひ。
tags - MapLibre GL JS
tags - Vue.js



book

Q&A