読み取り専用のNavigator.geolocationは、ウェブコンテンツがデバイスの位置情報にアクセスするためのGeolocationオブジェクトを返す。
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
#map {
height: 50%;
margin-top: 10px;
}
html, body {
height: 100%;
margin: 10px;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 2
});
var infoWindow = new google.maps.InfoWindow({map: map});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap">
</script>
</body>
</html>
![]()
一通り終わったと思ったらこれか?
なるほど、navigator.geolocation.getCurrentPositionで位置情報を取得していますね。
<script>
var options = {
enableHighAccuracy : true,
timeout: 5000,
maximumAge: 0
};
function success(pos){
var crd = pos.coords;
console.log('your current position is:');
console.log('latitude : ' + crd.latitude);
console.log('longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters');
};
function error(err){
console.warn('ERROR(' + err.code + '):' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error, options);
</script>