html5--位置感知(基于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是函数,成功确定位置则调用这个函数
2.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);
}

你可能感兴趣的:(html5,js地理定位,位置感知)