はじめに
現在オリジナルプロダクトを作成しており、その中で現在地を取得し周辺の店舗情報を取得、表示する機能を実装しました。
Rails + erb構成となっています。
使用するAPI
-
Maps JavaScript API
Google Mapを表示するためのAPI
https://developers.google.com/maps/documentation/javascript/overview?hl=ja -
Geolocation API
位置情報の取得をするAPI
https://developers.google.com/maps/documentation/geolocation/overview?hl=ja -
Places API
周辺の店舗情報を取得するAPI
https://developers.google.com/maps/documentation/places/web-service/overview?hl=ja -
参考にした記事
https://qiita.com/Haruka-Ogawa/items/997401a2edcd20e61037
実装内容
1. APIキーの設定
Google Maps APIが使用できるように環境変数へ設定しスクリプトを読み込ませる
- key=<%= ENV["GOOGLE_MAPS_API_KEY"] %> → 環境変数からAPIキーを取得
- libraries=places → Places APIを利用するために指定
- callback=initMap → Google Mapの初期化関数を指定
<script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV["GOOGLE_MAPS_API_KEY"] %>&libraries=places&callback=initMap" async defer></script>
2. コードの全体
<script>
window.initMap = function () {
navigator.geolocation.getCurrentPosition((position) => {
const userLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
const map = new google.maps.Map(document.getElementById('map'), {
center: userLocation,
zoom: 15
});
const image = "https://maps.google.com/mapfiles/ms/icons/blue-dot.png";
new google.maps.Marker({
position: userLocation,
map: map,
title: "あなたの現在地",
icon: image
});
nearShowStore(map, userLocation);
});
};
function nearShowStore(map, userLocation) {
const service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: userLocation,
radius: 5000,
keyword: "古着屋 リサイクルショップ"
}, (results, status) => {
results.forEach((place) => {
const marker = new google.maps.Marker({
position: place.geometry.location,
map: map,
title: place.name,
});
const contents = `
<div>
<strong>${place.name}</strong><br>
<strong>住所:</strong>${place.vicinity}
</div>`;
const infoWindow = new google.maps.InfoWindow({
content: contents
});
marker.addListener('mouseover', () => {
infoWindow.open(map, marker);
});
marker.addListener('mouseout', () => {
infoWindow.close();
});
});
});
}
</script>
3. 各コードの解説
window.initMap = function () {}
-
Google Maps APIの読み込み完了時に自動で実行される初期化関数
-
callback=initMap に対応するため、グローバルスコープに定義する必要がある
navigator.geolocation.getCurrentPosition()
- ブラウザの現在地取得API(Geolocation API)
- 成功時に position.coords.latitude / longitude を取得
new google.maps.Map()
- 取得した位置情報を中心に地図を表示
- zoom: 15 はマップの拡大率
new google.maps.Marker()
- 現在地に青いマーカー(カスタムアイコン)を設置
PlacesService().nearbySearch()
- userLocation を中心に、半径5000m以内の「古着屋」「リサイクルショップ」を検索
- 検索結果ごとにマーカーを設置し、クリックすると InfoWindow を表示
まとめ
- Google Maps API を使えば、現在地の地図表示と周辺店舗の検索表示が簡単にできる
- Geolocation API で現在地を取得し、Places API でキーワード検索が可能
- マーカーとクリック時の情報表示(InfoWindow)ができる