Google Maps JavaScript Apiを利用し、
現在位置付近のスポット情報をマーカーで示すサンプルを紹介します。
このサンプルは、現在地より半径「1km以内」の「レストラン」を検索します。
マーカーをクリック(タップ)すると、その施設の名前が吹き出しで表示されます。
このような形で表示できます。
サンプル
まずは動作サンプルを確認してください。
セッティング
マップの利用にはAPIキーの取得が必要です。
APIキーの取得方法に関しては、こちらの記事が参考になりました。
http://bashalog.c-brains.jp/17/08/25-200000.php
さらに、Google Maps JavaScript Apiは、SSL認証されているURLでなければ表示できないようです。
表示するURLはhttps://で始まるURLにしてください。
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDtWBXpjCFNqK_HdRP-eTYI0B2PjLJYEAM&language=ja&libraries=drawing,geometry,places,visualization" async defer></script>
html
「近所のレストランを検索」というボタンを押すと、半径1km以内の。レストランがマップ上に表示されます。
※Googleに登録されたレストランに限る。
<p><button onclick="getLocation()">近所のレストランを検索</button></p> <div id="map"></div>
javascript
レストラン以外も表示できます。
「プレイスタイプ」というGoogle既定のカテゴリであれば表示できます。
javascriptの以下の個所でプレイスタイプを指定します。
type: ['restaurant']
※例:病院は「hospital」 カフェは「cafe」など。
https://developers.google.com/places/supported_types
<script> var map; var infowindow; function getLocation(){ // 位置情報を取得する navigator.geolocation.getCurrentPosition( function(position) { // 現在地の緯度経度所得 var latitude = position.coords.latitude; var longitude = position.coords.longitude; alert('緯度:' + latitude + ' / 経度:' + longitude); var latlng = new google.maps.LatLng( latitude , longitude ) ; // 現在地の緯度経度を中心にマップを生成 map = new google.maps.Map(document.getElementById('map'), { center: latlng, zoom: 15 }); //現在地の緯度経度を中心にマップに円を描く var circleOptions = { map: map, center: new google.maps.LatLng( latitude , longitude ), radius: 1000,//1km strokeColor: "#009933", strokeOpacity: 1, strokeWeight: 1, fillColor: "#00ffcc", fillOpacity: 0.35 }; circle = new google.maps.Circle(circleOptions); //現在地から1キロ以内のレストランを検索 infowindow = new google.maps.InfoWindow(); var service = new google.maps.places.PlacesService(map); service.nearbySearch({ location: latlng, radius: 1000,//1km type: ['restaurant'] }, callback); },function(error) { // 失敗時の処理 alert('エラー:' + error); }); } //地図上にマーカーをプロット function callback(results, status) { if (status === google.maps.places.PlacesServiceStatus.OK) { for (var i = 0; i < results.length; i++) { createMarker(results[i]); } } } //地図上のマーカーをクリックした際の動作 function createMarker(place) { var placeLoc = place.geometry.location; var marker = new google.maps.Marker({ map: map, position: place.geometry.location }); //吹き出しの中身 google.maps.event.addListener(marker, 'click', function() { infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + '評価: ' + place.rating + '</div>'); infowindow.open(map, this); }); } </script>
以上、試してみてください。
“Google Maps Apiで現在地のスポット情報をマーカーで示すサンプル” への1件のフィードバック
コメントは停止中です。