スマートフォンのGPS機能から位置情報を取得
<html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <title>iPhone 位置情報取得</title> <script src="http://maps.google.com/maps/api/js?sensor=true"></script> <script> //経度緯度用変数を初期化 var latitude = ""; var longitude = ""; //正常に緯度経度情報が取得できた時に呼ばれる関数 function successFunc(e){ //前回の緯度経度情報と比較して、変わっていたら地図を更新 if( (e.coords.latitude != latitude) || (e.coords.longitude != longitude) ){ //緯度を取得 latitude = e.coords.latitude; //経度を取得 longitude = e.coords.longitude; //緯度経度を設定 var myLatLng = new google.maps.LatLng(latitude,longitude); //オプションを設定 var myOptions = { zoom: 16, center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP } //地図を生成し、指定したHTMLエレメントに表示 var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); } } //エラーが起きた場合に呼ばれる関数 function errorFunc(e) { switch (e.code) { case 1: alert("エラー:GPSの利用が許可されていません。GPSを使えるように設定してください。"); break; case 2: alert("エラー:位置情報が取得できませんでした。"); break; case 3: alert("エラー:タイムアウトしました。"); break; default: alert("エラー:位置情報を表示できませんでした。"); break; } } navigator.geolocation.watchPosition(successFunc, errorFunc); </script> </head> <body style="margin:0px; padding:0px;"> <div id="map_canvas" style="width:100%; height:100%"></div> </body> </html>
昨日のソースから中央にマーカーをつけてみる。
<html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <title>iPhone 位置情報取得・マーカー付</title> <script src="http://maps.google.com/maps/api/js?sensor=true"></script> <script> var latitude = ""; var longitude = ""; function successFunc(e){ if( (e.coords.latitude != latitude) || (e.coords.longitude != longitude) ){ latitude = e.coords.latitude; longitude = e.coords.longitude; var myLatLng = new google.maps.LatLng(latitude,longitude); var myOptions = { zoom: 16, center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP } //ここにマーカー命令を追加 var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var marker1 = new google.maps.Marker({ position: myLatLng, }); marker1.setMap(map); } } function errorFunc(e) { switch (e.code) { case 1: alert("エラー:GPSの利用が許可されていません。GPSを使えるように設定してください。"); break; case 2: alert("エラー:位置情報が取得できませんでした。"); break; case 3: alert("エラー:タイムアウトしました。"); break; default: alert("エラー:位置情報を表示できませんでした。"); break; } } navigator.geolocation.watchPosition(successFunc, errorFunc); </script> </head> <body style="margin:0px; padding:0px;"> <div id="map_canvas" style="width:320px; height:480px"></div> </body> </html>