最初の Amazon Location Maps and Places アプリケーションを作成する
このセクションでは、Maps and Places を使用して最初のアプリケーションを作成します。
前提条件:
Amazon Location Service コンソールを使用して認証する のステップで API キーを既に作成済みの場合は、開始できます。
API キーをまだ作成していない場合は、アプリケーションの構築を続行する前に Amazon Location Service コンソールを使用して認証する に従ってください。ご質問がある場合は、「API キーを使用して認証する」および「Amazon Location がサポートされているリージョン」を参照してください。
MapLibre GL JS で Amazon Location Service マップアプリケーションを作成するためのステップバイステップのチュートリアルを次に示します。このガイドでは、マップの設定、スタイルオプションの追加、場所検索機能の有効化について説明します。
このセクションでは、最初のページとフォルダ構造を設定します。
必要なライブラリとスタイルシートを追加する
index.html ファイルを作成します。マップをレンダリングするには、MapLibre GL JS と MapLibre GL Geocoder が必要です。MapLibre と Geocoder のスタイルシートと JavaScript スクリプトを追加します。
以下のコードをコピーして index.html ファイルに貼り付けます。
<!DOCTYPE html> <html lang="en"> <head> <title>Amazon Location Service - Getting Started with First Map App</title> <meta charset='utf-8'> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Interactive map application using Amazon Location Service"> <!--Link to MapLibre CSS and JavaScript library for map rendering and visualization --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.css" /> <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.js"></script> <!--Link to MapLibre Geocoder CSS and JavaScript library for place search and geocoding --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-geocoder@1.7.0/dist/maplibre-gl-geocoder.css" /> <script src="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-geocoder@1.7.0/dist/maplibre-gl-geocoder.js"></script> <!--Link to amazon-location JavaScript librarie --> <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-utilities-auth-helper@1"></script> <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-client@1.2"></script> <!-- Link to the first Amazon Location Map App's CSS and JavaScript --> <script src="utils.js"></script> <link rel="stylesheet" href="style.css"/> </head> <body> <main> </main> <script> // Step 1: Setup API Key and AWS Region // Step 2.1 Add maps to application // Step 2.2 initialize the map // Step 3: Add places features to application // Step 3.1: Get GeoPlaces instance. It will be used for addion search box and map click functionality // Step 3.2: Add search box to the map // Step 3.3.: Setup map click functionality // Add functions </script> </body> </html>
マップコンテナを作成する
HTML ファイルの <body> 要素の下で、マップを保持する <div> 要素を HTML で作成します。この <div> を CSS でスタイル設定して、アプリケーションに必要なディメンションを設定できます。GitHub リポジトリから、CSS ファイル style.css をダウンロードする必要があります。これにより、ビジネスロジックに集中できます。
style.css および index.html ファイルを同じフォルダに保存します。
style.css ファイルを GitHub
<main role="main" aria-label="Map Container"> <div id="map"></div> </main>
API キーと AWS リージョンの詳細を追加する
API キーを使用して認証する で作成した API キーを、キーが作成された AWS リージョンと共にこのファイルに追加します。
<!DOCTYPE html> <html lang="en"> ..... ..... <body> <main role="main" aria-label="Map Container"> <div id="map"></div> </main> <script> // Step 1: Setup API Key and AWS Region const API_KEY = "Your_API_Key"; const AWS_REGION = "Region_where_you_created_API_Key"; // Step 2: Add maps to application // Step 2.1 initialize the map // Step 2.2 Add navigation controls to the map // Step 3: Add places feature to application // Step 3.1: Get GeoPlaces instance. It will be used for addion search box and map click functionality // Step 3.2: Add search box to the map // Step 3.3.: Setup map click functionality </script> </body> </html>
このセクションでは、アプリケーションにマップ機能を追加します。開始するためには、ファイルがこのフォルダ構造内にある必要があります。
まだダウンロードしていない場合は、GitHubstyle.css ファイルをダウンロードしてください。
|---FirstApp [Folder] |-------------- index.html [File] |-------------- style.css [File]
マップを初期化する関数を作成します。
マップを設定するには、initializeMap(...) 行の後に次の関数 //Add functions を作成します。
最初の中心位置とズームレベルを選択します。この例では、マップの中心をカナダのバンクーバーに設定し、ズームレベルを 10 に設定します。簡単にズームできるようにするためナビゲーションコントロールを追加します。
/** * Initializes the map with the specified style and color scheme. */ function initializeMap(mapStyle = "Standard", colorScheme = "Dark") { const styleUrl = `https://maps.geo.${AWS_REGION}.amazonaws.com/v2/styles/${mapStyle}/descriptor?key=${API_KEY}&color-scheme=${colorScheme}`; const map = new maplibregl.Map({ container: 'map', // The ID of the map container style: styleUrl, // The style URL for the map center: [-123.116226, 49.246292], // Starting center coordinates zoom: 10, // Initial zoom level validateStyle: false // Disable style validation }); return map; // Return the initialized map }
マップを初期化する
initializeMap(...) を呼び出してマップを初期化します。オプションで、initializeMap 関数の後に任意のスタイルとカラースキームを使用して初期化できます。他のスタイルオプションについては、「AWS マップスタイルとカスタマイズ」を参照してください。
// Step 1: Setup API Key and AWS Region const API_KEY = "Your_API_Key"; const AWS_REGION = "Region_where_you_created_API_Key"; // Step 2.1 Add maps to application // Step 2.2 initialize the map const map = initializeMap("Standard","Light"); // Step 3: Add places features to application
ブラウザで index.html を開いて実行中のマップを表示します。
ナビゲーションコントロールを追加する
オプションで、ナビゲーションコントロール (ズームとローテーション) をマップに追加できます。これは、initializeMap(...) を呼び出した後に実行する必要があります。
// Step 2.1 initialize the map const map = initializeMap("Standard","Light"); // Step 2.2 Add navigation controls to the map map.addControl(new maplibregl.NavigationControl()); // Step 3: Add places features to application
マップコードを確認する
お疲れ様でした。最初のアプリでマップを使用できるようになりました。ブラウザで index.html を開きます。style.css が index.html と同じフォルダにあることを確認してください。
最終的な HTML は以下のようになります。
<!DOCTYPE html> <html lang="en"> <head> <title>Amazon Location Service - Getting Started with First Map App</title> <meta charset='utf-8'> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Interactive map application using Amazon Location Service"> <!-- Link to MapLibre CSS and JavaScript library for map rendering and visualization --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.css" /> <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.js"></script> <!-- Link to MapLibre Geocoder CSS and JavaScript library for place search and geocoding --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-geocoder@1.7.0/dist/maplibre-gl-geocoder.css" /> <script src="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-geocoder@1.7.0/dist/maplibre-gl-geocoder.js"></script> <!-- Link to amazon-location JavaScript library --> <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-utilities-auth-helper@1"></script> <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-client@1.2"></script> <!-- Link to the first Amazon Location Map App's CSS and JavaScript --> <script src="utils.js"></script> <link rel="stylesheet" href="style.css"/> </head> <body> <main role="main" aria-label="Map Container"> <div id="map"></div> </main> <script> const API_KEY = "Your_API_Key"; const AWS_REGION = "Region_where_you_created_API_Key"; function initializeMap(mapStyle, colorScheme) { const styleUrl = `https://maps.geo.${AWS_REGION}.amazonaws.com/v2/styles/${mapStyle}/descriptor?key=${API_KEY}&color-scheme=${colorScheme}`; const map = new maplibregl.Map({ container: 'map', // ID of the HTML element for the map style: styleUrl, // URL for the map style center: [-123.116226, 49.246292], // Initial map center [longitude, latitude] zoom: 10 // Initial zoom level }); map.addControl(new maplibregl.NavigationControl()); return map; } const map = initializeMap("Standard", "Light"); </script> </body> </html>
このセクションでは、アプリケーションに場所機能を設定します。GitHub、utils.js
開始するためには、ファイルがこのフォルダ構造内にある必要があります。
|---FirstApp [Folder] |-------------- index.html [File] |-------------- style.css [File] |-------------- utils.js [File]
GeoPlaces を作成する関数を作成する
検索機能を追加するには、AuthHelper と AmazonLocationClient を使用して GeoPlaces クラスを初期化します。index.html の </script> タグの前に次の getGeoPlaces(map) 関数を追加します。
/** * Gets a GeoPlaces instance for Places operations. */ function getGeoPlaces(map) { const authHelper = amazonLocationClient.withAPIKey(API_KEY, AWS_REGION); // Authenticate using the API key and AWS region const locationClient = new amazonLocationClient.GeoPlacesClient(authHelper.getClientConfig()); // Create a GeoPlaces client const geoPlaces = new GeoPlaces(locationClient, map); // Create GeoPlaces instance return geoPlaces; // Return the GeoPlaces instance }
検索ボックスをアプリケーションに追加する関数を作成する
index.html の </script> タグの前に次の addSearchBox(map, geoPlaces)、renderPopup(feature)、createPopup(feature) 関数を追加して、検索機能の設定を完了します。
/** * Adds search box to the map. */ function addSearchBox(map, geoPlaces) { const searchBox = new MaplibreGeocoder(geoPlaces, { maplibregl, showResultsWhileTyping: true, // Show results while typing debounceSearch: 300, // Debounce search requests limit: 30, // Limit number of results popuprender: renderPopup, // Function to render popup reverseGeocode: true, // Enable reverse geocoding zoom: 14, // Zoom level on result selection placeholder: "Search text or nearby (lat,long)" // Placeholder text for search box. }); // Add the search box to the map map.addControl(searchBox, 'top-left'); // Event listener for when a search result is selected searchBox.on('result', async (event) => { const { id, result_type } = event.result; // Get result ID and type if (result_type === "Place") { // Check if the result is a place const placeResults = await geoPlaces.searchByPlaceId(id); // Fetch details for the selected place if (placeResults.features.length) { createPopup(placeResults.features[0]).addTo(map); // Create and add popup for the place } } }); } /** * Renders the popup content for a given feature. */ function renderPopup(feature) { return ` <div class="popup-content"> <span class="${feature.place_type.toLowerCase()} badge">${feature.place_type}</span><br> ${feature.place_name} </div>`; } /** * Creates a popup for a given feature and sets its position. */ function createPopup(feature) { return new maplibregl.Popup({ offset: 30 }) // Create a new popup .setLngLat(feature.geometry.coordinates) // Set the popup position .setHTML(renderPopup(feature)); // Set the popup content }
アプリケーションに検索ボックスを追加する
セクション 3.1 で定義されているように getGeoPlaces(map) を呼び出して GeoPlaces オブジェクトを作成してから、addSearchBox(map, geoPlaces) を呼び出して検索ボックスをアプリケーションに追加します。
// Step 2: Add maps to application // Step 2.1 initialize the map const map = initializeMap("Standard","Light"); // Step 2.2 Add navigation controls to the map map.addControl(new maplibregl.NavigationControl()); // Step 3: Add places feature to application // Step 3.1: Get GeoPlaces instance. It will be used for adding search box and map click functionality const geoPlaces = getGeoPlaces(map); // Step 3.2: Add search box to the map addSearchBox(map, geoPlaces);
場所の検索を使用できるようになりました。ブラウザで index.html を開いて動作を確認します。
マップをクリック時にポップアップを表示するための関数を追加する
マップをクリックしたときにポップアップを表示する関数 addMapClick(map, geoPlaces) を作成します。この関数を </script> タグの直前に追加します。
/** * Sets up reverse geocoding on map click events. */ function addMapClick(map, geoPlaces) { map.on('click', async ({ lngLat }) => { // Listen for click events on the map const response = await geoPlaces.reverseGeocode({ query: [lngLat.lng, lngLat.lat], limit: 1, click: true }); // Perform reverse geocoding if (response.features.length) { // If there are results const clickMarker = new maplibregl.Marker({ color: "orange" }); // Create a marker const feature = response.features[0]; // Get the clicked feature const clickedPopup = createPopup(feature); // Create popup for the clicked feature clickMarker.setLngLat(feature.geometry.coordinates) // Set marker position .setPopup(clickedPopup) // Attach popup to marker .addTo(map); // Add marker to the map clickedPopup.on('close', () => clickMarker.remove()).addTo(map); // Remove marker when popup is closed } }); }
マップクリック機能を追加する関数を呼び出す
マップクリックアクションを有効にするには、addSearchBox(map, geoPlaces) を含む行の後に addMapClick(map, geoPlaces) を呼び出します。
// Step 3: Add places feature to application // Step 3.1: Get GeoPlaces instance. It will be used for adding search box and map click functionality const geoPlaces = getGeoPlaces(map); // Step 3.2: Add search box to the map addSearchBox(map, geoPlaces); // Step 3.3: Setup map click functionality addMapClick(map, geoPlaces);
Maps and Places アプリケーションを確認する
お疲れ様でした。最初のアプリケーションが Maps and Places を使用することができるようになりました。ブラウザで index.html を開きます。style.css と utils.js が index.html と同じフォルダにあることを確認します。
最終的な HTML は以下のようになります。
<!DOCTYPE html> <html lang="en"> <head> <title>Amazon Location Service - Getting Started with First Map App</title> <meta charset='utf-8'> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Interactive map application using Amazon Location Service"> <!--Link to MapLibre CSS and JavaScript library for map rendering and visualization --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.css" /> <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.js"></script> <!--Link to MapLibre Geocoder CSS and JavaScript library for place search and geocoding --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-geocoder@1.7.0/dist/maplibre-gl-geocoder.css" /> <script src="https://cdn.jsdelivr.net/npm/@maplibre/maplibre-gl-geocoder@1.7.0/dist/maplibre-gl-geocoder.js"></script> <!--Link to amazon-location JavaScript librarie --> <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-utilities-auth-helper@1"></script> <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-client@1.2"></script> <!-- Link to the first Amazon Location Map App's CSS and JavaScript --> <script src="utils.js"></script> <link rel="stylesheet" href="style.css"/> </head> <body> <main role="main" aria-label="Map Container"> <div id="map"></div> </main> <script> // Step 1: Setup API Key and AWS Region const API_KEY = "Your_API_Key"; const AWS_REGION = "Region_where_you_created_API_Key"; // Step 2: Add maps to application // Step 2.1 initialize the map const map = initializeMap("Standard","Light"); // Step 2.2 Add navigation controls to the map map.addControl(new maplibregl.NavigationControl()); // Step 3: Add places feature to application // Step 3.1: Get GeoPlaces instance. It will be used for addion search box and map click functionality const geoPlaces = getGeoPlaces(map); // Step 3.2: Add search box to the map addSearchBox(map, geoPlaces); // Step 3.3.: Setup map click functionality addMapClick(map, geoPlaces); /** * Functions to add maps and places feature. */ /** * Initializes the map with the specified style and color scheme. */ function initializeMap(mapStyle = "Standard", colorScheme = "Dark") { const styleUrl = `https://maps.geo.${AWS_REGION}.amazonaws.com/v2/styles/${mapStyle}/descriptor?key=${API_KEY}&color-scheme=${colorScheme}`; const map = new maplibregl.Map({ container: 'map', // The ID of the map container style: styleUrl, // The style URL for the map center: [-123.116226, 49.246292], // Starting center coordinates zoom: 10, // Initial zoom level validateStyle: false // Disable style validation }); return map; // Return the initialized map } /** * Gets a GeoPlaces instance for Places operations. */ function getGeoPlaces(map) { const authHelper = amazonLocationClient.withAPIKey(API_KEY, AWS_REGION); // Authenticate using the API key and AWS region const locationClient = new amazonLocationClient.GeoPlacesClient(authHelper.getClientConfig()); // Create a GeoPlaces client const geoPlaces = new GeoPlaces(locationClient, map); // Create GeoPlaces instance return geoPlaces; // Return the GeoPlaces instance } /** * Adds search box to the map. */ function addSearchBox(map, geoPlaces) { const searchBox = new MaplibreGeocoder(geoPlaces, { maplibregl, showResultsWhileTyping: true, // Show results while typing debounceSearch: 300, // Debounce search requests limit: 30, // Limit number of results popuprender: renderPopup, // Function to render popup reverseGeocode: true, // Enable reverse geocoding zoom: 14, // Zoom level on result selection placeholder: "Search text or nearby (lat,long)" // Place holder text for search box. }); // Add the search box to the map map.addControl(searchBox, 'top-left'); // Event listener for when a search result is selected searchBox.on('result', async (event) => { const { id, result_type } = event.result; // Get result ID and type if (result_type === "Place") { // Check if the result is a place const placeResults = await geoPlaces.searchByPlaceId(id); // Fetch details for the selected place if (placeResults.features.length) { createPopup(placeResults.features[0]).addTo(map); // Create and add popup for the place } } }); } /** * Renders the popup content for a given feature. */ function renderPopup(feature) { return ` <div class="popup-content"> <span class="${feature.place_type.toLowerCase()} badge">${feature.place_type}</span><br> ${feature.place_name} </div>`; } /** * Creates a popup for a given feature and sets its position. */ function createPopup(feature) { return new maplibregl.Popup({ offset: 30 }) // Create a new popup .setLngLat(feature.geometry.coordinates) // Set the popup position .setHTML(renderPopup(feature)); // Set the popup content } /** * Sets up reverse geocoding on map click events. */ function addMapClick(map, geoPlaces) { map.on('click', async ({ lngLat }) => { // Listen for click events on the map const response = await geoPlaces.reverseGeocode({ query: [lngLat.lng, lngLat.lat], limit: 1, click:true }); // Perform reverse geocoding if (response.features.length) { // If there are results const clickMarker = new maplibregl.Marker({ color: "orange" }); // Create a marker const feature = response.features[0]; // Get the clicked feature const clickedPopup = createPopup(feature); // Create popup for the clicked feature clickMarker.setLngLat(feature.geometry.coordinates) // Set marker position .setPopup(clickedPopup) // Attach popup to marker .addTo(map); // Add marker to the map clickedPopup.on('close', () => clickMarker.remove()).addTo(map); // Remove marker when popup is closed } }); } </script> </body> </html>
クイックスタートチュートリアルを完了したので、Amazon Location Service を使用してアプリケーションを構築する方法を理解できるでしょう。Amazon Location をさらに活用するには、以下のリソースをご覧ください。
-
クエリ提案の詳細 -
SuggestionAPI が返す結果の詳細を取得するには、ReverseGeocodeクラスを拡張するか、GeoPlacesと同様の手法を使用することを検討してください。 -
ビジネスニーズに適した API を選択する - 要件に最適な Amazon Location API を決定するには、「適切な API を選択する」のリソースを確認してください。
-
Amazon Location の「ハウツー」ガイドを確認する - チュートリアルやその他のリソースについては、「Amazon Location Service デベロッパーガイド」を参照してください。
-
ドキュメントと製品情報 - 詳細なドキュメントについては、「Amazon Location Service デベロッパーガイド」を参照してください。製品の詳細については、「Amazon Location Service の製品
」ページを参照してください。