html 5-位置感知(jsベースの地理的位置決めgeolocation API)Google Mapsと組み合わせる


1.ブラウザが地理的APIをサポートしているかどうかを検出する
//             API(navigator.geolocation)
if (navigator.geolocation) {
 }else{
    alert("Your browser does not support Geolocation!");
}

2.地理的APIがサポートする方法getCurrentPosition
getCurrentPosition(successHandler,errorHandler,options)パラメータ:1.successHandlerは関数であり、位置の決定に成功するとこの関数を呼び出す.errorHandlerは関数であり、位置を正常に決定できない場合はこの関数を呼び出すことができます.オプション3.optionsパラメータでは、地理的位置決め方法をカスタマイズできます.オプション
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successHandler,errorHandler,options)
 }else{
    alert("Your browser does not support Geolocation!");
}
//    API           POSITION
function successHandler(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
}
//    API         
function errorHandler(error){
    switch(error.code) {
        case error.TIMEOUT:
            showError("A timeout occured! Please try again!");
            break;
        case error.POSITION_UNAVAILABLE:
            showError('We can\'t detect your location. Sorry!');
            break;
        case error.PERMISSION_DENIED:
            showError('Please allow geolocation access for this to work.');
            break;
        case error.UNKNOWN_ERROR:
            showError('An unknown error occured!');
            break;
    }
}
//timeout           ,          
var options = {
    enableHighAccuracy:false,
    timeout:Infinity,
    maximumAge:0
};

3.地理的APIがサポートする方法watchPositionとclearWatch
watchPositionはgetCurrentPositionと似ていますが、watchPositionは常に位置を検出し、位置が変化すると関数を呼び出して新しい位置を報告し、clearWatchを呼び出すと検出をクリアします.
<!doctype html>
<html>
<head>
    .....
</head>
<body>
    <form>
        <input type="button" id="watch" value="Watch me">
        <input type="button" id="clearWatch" value="Clear watch ">
    </form>
</body>
</html>
function getLocation(){
    if(nagivator.geolocation) {
        var watchButton = document.getElementById("watch");
        watchButton.onclick = watchLocation;
        var clearWatchButton = document.getElementById("clearWatch");
        clearWatchButton.onclick = clearWatch;
    } else{
        alert("no geolocation support");
    }
}
//watchid       
var watchId = null;
function watchLocation(){
    watchId = navigator.geolocation.watchPosition(successHandler,errorHandler);
}
function clearWatch(){
    if(watchid) {
        navigator.geolocation.clearWatch(watchId);
        watchId = null;
    }
}

4.Google Mapsと連携したビジュアル表示
地理的位置APIは位置追跡のみ可能であるが、視覚的に表示することはできない.Google Mapsと組み合わせて可視化表示を行います.jsはGoogle Mapsの使用する機能を得ます
<script //sensor=false          ,sensor=true          src=https://maps.google.com/maps/api/js?sensor=true> </script>
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successHandler)
 }else{
    alert("Your browser does not support Geolocation!");
}
//    API           POSITION
function successHandler(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    showMap(position.coords);
}

function showMap(coords){
    //Google API              ,             
    var googlemap = new google.maps.LatLng(coords.latitude,coords.longitude);
    //          
    var mapptions = {
        zoom:10,
        center:googlemap,
        mapTypeId:google.maps.MapTypeId.RPADMAP
    };
    var mapDiv = document.getElementById("map");
    //  Google API        (         )
    map = new google.maps.Map(mapDiv,mapOptions);
}

ビジュアルマップにピンを追加
var title = "Your location";
var content = "you are here:" + coords.latitude +","+cpprds.longitude;
addMarker(map,googlemap,title,content);

function addMarker(map,latlong,title,content){
    var markerOptions = {
        position:latlong,
        map:map,
        title:title,
        //true                   
        clickable:true
    };
    var marker = new google.maps.Marker(markerOptions);
    var infoWindowOptions = {
        content:content,
        position:latlong
    };
    //      
    var infoWindow = new google.maps.InfoWindow(infoWindowOptions);
    google.maps.event.addListener(marker,"click",function(){
    infoWindow.open(map);
    })
};

5.完全なプログラムを与える
var options = {
    enableHighAccuracy:true,
    timeout:100,
    maximumAge:0
};
window.onload = getLocation;

function getLocation(){
    if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successHandler,errorHandler,options)
     }else{
        alert("Your browser does not support Geolocation!");
    }
}

function successHandler(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    var div = document.getElementById("location");
    //               
    div.innerHTML = latitude + longitude;
    div.innerHTML+="(found in" + options.timeout +"ms)";

    showMap(position.coords);
}

function errorHandler(error){
    switch(error.code) {
        case error.TIMEOUT:
            showError("A timeout occured! Please try again!");
            break;
        case error.POSITION_UNAVAILABLE:
            showError('We can\'t detect your location. Sorry!');
            break;
        case error.PERMISSION_DENIED:
            showError('Please allow geolocation access for this to work.');
            break;
        case error.UNKNOWN_ERROR:
            showError('An unknown error occured!');
            break;
    }
    //     ,    ,  timeout    100ms
    options.timeout+=100;
    navigator.geolocation.getCurrentPosition(successHandler,errorHandler,options);
    div.innerHTML+="checking again with timeout="+options.timeout;
}
function showMap(coords){
    //Google API              ,             
    var googlemap = new google.maps.LatLng(coords.latitude,coords.longitude);
    //          
    var mapptions = {
        zoom:10,
        center:googlemap,
        mapTypeId:google.maps.MapTypeId.RPADMAP
    };
    var mapDiv = document.getElementById("map");
    //  Google API        (         )
    map = new google.maps.Map(mapDiv,mapOptions);
}