<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>避難所案内</title> <link rel="stylesheet" href="leaflet.css" /> <script src="leaflet.js"></script> <style> #map { height: 800px; } </style> </head> <body> <h1>避難所案内</h1> <div id="map"></div> <script> const map = L.map('map').setView([38.9141, 139.8367], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); const locations = [ {name: "宮野浦小学校", lat: 38.909393, lon: 139.807617,}, {name: "宮野浦学区コミュニティ防災センター,会館中",lat: 38.904711,lon: 139.812017}, {name: "第四中学校", lat: 38.88217816,lon: 139.83486259}, {name: "浜田小学校", lat: 38.91690407,lon: 139.84681517}, {name: "広野小学校", lat: 38.849796, lon: 139.84404}, {name: "黒森小学校", lat: 38.8510811, lon: 139.82263279}, ]; // 今回は、時間がなかった、配列にしてしまった、csvどうするんだっけ locations.forEach(loc => { L.marker([loc.lat, loc.lon]).addTo(map) .bindPopup(loc.name); }); function getCurrentPosition() { // めっちゃちけえ場所 return new Promise((resolve, reject) => {if (!navigator.geolocation) { reject(new Error('ブラウザに対応してないよ!')); } else { navigator.geolocation.getCurrentPosition(resolve, reject, { //位置じょーほー tyuui: true, timeout: 5000, // 5秒 time: 0 }); } }); } function find(userLat, userLon) { let near = locations[0]; let min = Infinity; // 無限大 locations.forEach(loc => { const distance = Math.sqrt( Math.pow(loc.lat - userLat, 2) + Math.pow(loc.lon - userLon, 2)); if (distance < min) { min = distance; near = loc; } }); // 緯度と軽度のさを二乗してそのへーほーこんの数値をとる return near; } async function route() { try { const position = await getCurrentPosition(); //https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/async_function const userLat = position.coords.latitude; const userLon = position.coords.longitude; const userMarker = L.marker([userLat, userLon]).addTo(map) .bindPopup('現在地').openPopup(); const nearest = find(userLat, userLon); const routeLine = L.polyline([ [userLat, userLon], [nearest.lat, nearest.lon]], {color: 'blue', weight: 3}).addTo(map); map.fitBounds(routeLine.getBounds()); alert(`最も近い避難所は${nearest.name}ですね`); //けーこく } catch (error) { console.error('位置情報の取得に失敗しましたよ:', error); alert('位置情報の取得に失敗しました、ブラウザの設定を確認してくださいな'); } } route(); </script> </body>