地理位置


HTML5 不仅仅指的是最新版的 HTML 标准,它还指代了目前一整套的 Web 应用技术。

在之前的章节中已经介绍过的 HTML5 API:

  • getElementsByClassName() 方法和 querySelectorAll() 方法以及文档元素的 dataset 属性
  • 元素的 classList 属性
  • XMLHttpRequest Level 2、跨域 HTTP 请求,EventSource API
  • Web 存储 API 和离线 Web 应用的应用缓存
  • <audio><video><canvas>、SVG图形

地理位置 API 允许 JavaScript 程序向浏览器询问用户的真实地理位置。

navigator.geolocation 对象:

  • navigator.geolocation.getCurrentPosition():获取用户当前位置
  • navigator.geolocation.watchPosition():获取当前位置同时不断监视当前位置
  • navigator.geolocation.clearWatch():停止监视用户位置

在包含 GPS 硬件的设备上,通过 GPS 单元可以获取精确的位置信息。不过通常都是通过 Web 获取,基于 IP 地址判断属于哪个城市。

// 通过获取地理位置信息在地图上显示当前位置
function getmap() {
    if (!navigator.geolocation)
        throw "Geolocation not supported!";

    var img = document.createElement("img");
    navigator.geolocation.getCurrentPosition(function (pos) {
        var latitude = pos.coords.latitude;  // 经度
        var longitude = pos.coords.longitude; // 纬度
        var accuracy = pos.coords.accuracy;  // 米

        var url = "http://maps.google.com/maps/staticmap?center=" + latitude + "," + longitude +
            "&size=640x640&sensor=true";

        var zoomlevel = 20; // 缩放级别
        if (accuracy > 80)
            zoomlevel -= Math.round(Math.log(accuracy/50)/Math.LN2);
        url += "&zoom=" + zoomlevel;

        img.src = url;
    });
    return img;
}
    
// 使用所有地理位置属性
function whereami(elt) {
    var options = {
        enableHighAccuracy: false,  // 获取高精度位置信息
        maximumAge: 300000,  // 缓存时间,5分钟
        timeout: 15000  // 获取位置信息时间,不超过15秒
    };
    
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error, options);
    } else {
        elt.innerHTML = "Geolocation not supported in this browser";
    }
    
    function error(e) {
        //1、用户不允许分享他的位置信息
        //2、浏览器无法确定位置
        //3、发生超时
        elt.innerHTML = "Geolocation error " + e.code + ": " + e.message;
    }
    
    function success(pos) {
        var msg = "At " +
                new Date(pos.timestamp).toUTCString() + " you were within " +
                pos.coords.accuracy + " meters of latitude " +
                pos.coords.latitude + " longitude " +
                pos.coords.longitude + ".";
    
        // 海拔信息
        if (pos.coords.altitude) {
            msg += " You are " + pos.coords.altitude + " +/- " +
                    pos.coords.altitudeAccuracy + " meters above sea level.";
        }
    
        // 速度和航向信息
        if (pos.coords.speed) {
            msg += " You are travelling at " +
                    pos.coords.speed + " m/s on heading " +
                    pos.coords.heading + ".";
        }
    
        elt.innerHTML = msg;
    }
}

点赞 取消点赞 收藏 取消收藏

<< 上一篇: 基于 Canvas 绘制图形

>> 下一篇: 历史记录与跨源消息