表示したい場所に
<div id="map"></div>
</body>前に
<script src="script.js" defer></script>
script.js ファイルは以下のように記載
APIキーは以下より取得
https://developers.google.com/maps/documentation/javascript/get-api-key
lat: 35.676353, lng: 139.777089の部分は表示する場所を以下で調べて記載
https://user.numazu-ct.ac.jp/~tsato/webmap/sphere/coordinates/advanced.html
document.addEventListener('DOMContentLoaded', function () { if (document.querySelectorAll('#map').length > 0) { if (document.querySelector('html').lang) lang = document.querySelector('html').lang; else lang = 'ja'; var js_file = document.createElement('script'); js_file.type = 'text/javascript'; js_file.src = 'https://maps.googleapis.com/maps/api/js?callback=initMap&signed_in=true&key=APIキーを取得して記載&language=' + lang; document.getElementsByTagName('head')[0].appendChild(js_file); } }); var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: 35.676353, lng: 139.777089}, zoom: 8 }); fetch('markers.json') .then(function(response){return response.json()}) .then(plotMarkers); } var markers; var bounds; function plotMarkers(m) { markers = []; bounds = new google.maps.LatLngBounds(); m.forEach(function (marker) { var position = new google.maps.LatLng(marker.lat, marker.lng); markers.push( new google.maps.Marker({ position: position, map: map, animation: google.maps.Animation.DROP }) ); bounds.extend(position); }); map.fitBounds(bounds); }
fetch(‘markers.json’)
のmarkers.jsonを別で作る
[ { "lat": 35.676353, "lng": 139.777089 } ]