HTML5新機能 〜 Geolocation APIで現在位置を取得する


http://wbs-newworld.appspot.com/html5studyGeolocation.html

今回利用したのは、Geolocation API機能。これを利用して、現在位置を取得し、google maps APIも利用して現在位置を地図上に表示している。
例によって、検証アプリを作成した。
JSのメインは下記コード。ただし、jqueryは使用している。

<script type="text/javascript">
	$(document).ready(
        	function() {
		var update = function(position) {
		var coordinate = position.coords;
		var lat = coordinate.latitude;
		var lng = coordinate.longitude;
		var mapSrc = 'http://maps.google.com/maps/api/staticmap?center='+lat+','+lng+'&markers='+lat+','+lng+'&zoom=13&size=400x400&maptype=roadmap&sensor=false';
							document.getElementById("mapArea").innerHTML += "<img src='" +  mapSrc + "'/>";
						}

$('#geolocation').click(function() {
  if (!navigator.geolocation){ 
   document.getElementById("mapArea").innerHTML += "Geolocation APIを利用できません";
   return;
  }else {
   //Geolocation APIを使用する
   navigator.geolocation.getCurrentPosition(update);
  }
 });
});
</script>

上記JSによって、下記HTMLで現在位置を地図に描画する。

<body>
 <h1>Geolocation APIを試す</h1>
 <section class="view">
  <div id="mapArea"></div>
 </section>
 <input type="button" value="現在位置を地図に表示" id="geolocation" />
</body>