Skip to content

Instantly share code, notes, and snippets.

@takuya-saito-sketch-0822
Created October 23, 2024 16:07
Show Gist options
  • Select an option

  • Save takuya-saito-sketch-0822/e9426b4473b40e5778dc6c95f5a8c33d to your computer and use it in GitHub Desktop.

Select an option

Save takuya-saito-sketch-0822/e9426b4473b40e5778dc6c95f5a8c33d to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>現在位置をGoogle Mapに表示</title>
<style>
#map {
height: 100vh;
width: 100%;
}
</style>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=<ここを書き換えてください>&callback=initMap">
</script>
</head>
<body>
<h1>現在位置をGoogle Mapに表示</h1>
<div id="map"></div>
<script>
let map, marker;
function initMap() {
// マップの初期位置は仮に東京に設定
const defaultLocation = { lat: 35.6895, lng: 139.6917 };
map = new google.maps.Map(document.getElementById("map"), {
center: defaultLocation,
zoom: 12,
});
// 現在位置を取得
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const userLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
// マップを現在位置に移動
map.setCenter(userLocation);
// 現在位置にマーカーを表示
marker = new google.maps.Marker({
position: userLocation,
map: map,
title: "あなたの現在位置",
});
},
() => {
handleLocationError(true, map.getCenter());
}
);
} else {
// Geolocation APIがサポートされていない場合
handleLocationError(false, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, pos) {
const infoWindow = new google.maps.InfoWindow({
content: browserHasGeolocation
? "Error: 現在位置を取得できませんでした。"
: "Error: このブラウザはGeolocationをサポートしていません。",
position: pos,
});
infoWindow.open(map);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment