Google Maps JavaScript Apiを利用し、
座標と名称の掲載されたjsonデータを読み込み、地図用にマーカーを配置するサンプルを紹介します。
このサンプルでは、新宿の周辺の指定した座標にマーカーを配置します。
サンプル
まずは動作サンプルを確認してください。
セッティング
マップの利用にはAPIキーの取得が必要です。
APIキーの取得方法に関しては、こちらの記事が参考になりました。
http://bashalog.c-brains.jp/17/08/25-200000.php
さらに、Google Maps JavaScript Apiは、SSL認証されているURLでなければ表示できないようです。
表示する際のページURLはhttps://で始まるURLにしてください。
参考ページ
Google Maps Api のリファレンスの以下ページを参考にして自分で改良しました。
地震の情報を読み込む
https://developers.google.com/maps/documentation/javascript/examples/layer-data-quakes
html
<div id="map"></div>
JSON
feed_callback({ "features": [{ "properties": { "name": "ポイントA" }, "geometry": { "coordinates": [139.695718, 35.689748] } }, { "properties": { "name": "ポイントB" }, "geometry": { "coordinates": [139.697735, 35.693233] } }, { "properties": { "name": "ポイントC" }, "geometry": { "coordinates": [139.702563, 35.694976] } }, { "properties": { "name": "ポイントD" }, "geometry": { "coordinates": [139.696748, 35.688824] } }, { "properties": { "name": "ポイントE" }, "geometry": { "coordinates": [139.697842, 35.684868] } }] });
Javascript
<script> var map; function initMap() { //マップを生成 map = new google.maps.Map(document.getElementById('map'), { //初期設定。新宿に座標を合わせる。 zoom: 15, center: new google.maps.LatLng(35.689587, 139.691663), mapTypeId: google.maps.MapTypeId.ROADMAP }); //jsonデータを読み込み var script = document.createElement('script'); script.src = 'tokyo_GeoJSONP.js'; document.getElementsByTagName('head')[0].appendChild(script); } window.feed_callback = function(results) { //マップにマーカーを生成 for (var i = 0; i < results.features.length; i++) { var coords = results.features[i].geometry.coordinates; var latLng = new google.maps.LatLng(coords[1],coords[0]); var marker = new google.maps.Marker({ position: latLng, map: map }); //吹き出しの中身の文言を引数で送る。 attachMessage(marker, results.features[i].properties.name); } } //マーカーをクリックしたときに、吹き出しを出す。 function attachMessage(marker, msg) { google.maps.event.addListener(marker, 'click', function(event) { new google.maps.InfoWindow({ content: msg }).open(marker.getMap(), marker); }); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDtWBXpjCFNqK_HdRP-eTYI0B2PjLJYEAM&callback=initMap"> </script>
CSS
<style> #map { width:100%; height: 600px; } html, body { height: 100%; margin: 0; padding: 0; } </style>
以上、試してみてください。