<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GPS機能</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
#location {
margin-top: 20px;
}
#errorMessage {
color: red;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>現在地の取得</h1>
<button id="getLocationButton">現在地を取得する</button>
<div id="location">
<p id="latitude"></p>
<p id="longitude"></p>
</div>
<p id="errorMessage"></p>
<script>
// HTML要素を取得
const getLocationButton = document.getElementById("getLocationButton");
const latitudeElement = document.getElementById("latitude");
const longitudeElement = document.getElementById("longitude");
const errorMessage = document.getElementById("errorMessage");
// ボタンがクリックされたときの処理
getLocationButton.addEventListener("click", () => {
// Geolocation APIがブラウザでサポートされているか確認
if (!navigator.geolocation) {
errorMessage.textContent = "このブラウザでは現在地取得機能がサポートされていません。";
return;
}
// 現在地を取得
navigator.geolocation.getCurrentPosition(
(position) => {
// 成功時の処理
const latitude = position.coords.latitude; // 緯度
const longitude = position.coords.longitude; // 経度
// 画面に表示
latitudeElement.textContent = `緯度: ${latitude}`;
longitudeElement.textContent = `経度: ${longitude}`;
errorMessage.textContent = ""; // エラーメッセージをクリア
},
(error) => {
// エラー時の処理
switch (error.code) {
case error.PERMISSION_DENIED:
errorMessage.textContent = "位置情報の利用が許可されていません。";
break;
case error.POSITION_UNAVAILABLE:
errorMessage.textContent = "位置情報を取得できませんでした。";
break;
case error.TIMEOUT:
errorMessage.textContent = "位置情報の取得に時間がかかりすぎました。";
break;
default:
errorMessage.textContent = "不明なエラーが発生しました。";
}
}
);
});
</script>
</body>
</html>