Google Maps APIのHello world的なチュートリアルを以前やったので、今回はデベロッパーガイドを読みながらお試し。
Geolocation API(navigator.geolocation.getCurrentPosition)で緯度・経度を取得し、地図表示する:use_getCurrentPosition.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Google Maps API version3</title>
<style type="text/css">
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
padding: 0px;
}
#map_canvas {
height: 100%;
}
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var initialLocation;
var latlng = new google.maps.LatLng(35.658517, 139.701334); // 渋谷駅
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (navigator.geolocation) {
// window.alert("Geolocation APIに対応しています");
navigator.geolocation.getCurrentPosition(
successCallback, errorCallback, {timeout:60000}
);
function successCallback(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
}
function errorCallback(error) {
var message = "";
switch (error.code) {
case error.POSITION_UNAVAILABLE:
message = "位置情報を取得できませんでした";
break;
case error.PERMISSION_DENIED:
message = "位置情報の取得許可を取得できませんでした";
break;
case error.TIMEOUT:
message = "位置情報を取得中にタイムアウトしました";
break;
}
window.alert(message);
}
}
else {
window.alert("Geolocation APIに対応していません");
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
参考サイト
関連エントリー