現在位置を取得してGoogle Mapsリンクを表示させるJavaScriptです。
Google Mapsのリンクの部分を経路のリンクなどに変えて使えばユーザー現在地を取得して目的地までの経路のGoogle Mapsにリンクするなどにも使えます。
▼HTML
<h1>現在位置を取得してGoogle Mapsリンクを表示</h1>
<button id="getLocation">現在位置を取得</button>
<p id="location"></p>
<a id="mapLink" href="#" target="_blank" style="display: none;">Google Mapsで見る</a>
▼Javascript
document.getElementById('getLocation').addEventListener('click', function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const locationText = `緯度: ${latitude}, 経度: ${longitude}`;
document.getElementById('location').innerText = locationText;
const mapLink = `https://www.google.com/maps?q=${latitude},${longitude}`;
const mapLinkElement = document.getElementById('mapLink');
mapLinkElement.href = mapLink;
mapLinkElement.style.display = 'inline';
mapLinkElement.innerText = 'Google Mapsで見る';
}, function(error) {
console.error(error);
alert('位置情報を取得できませんでした。');
});
} else {
alert('このブラウザは位置情報をサポートしていません。');
}
});
