HTML 突袭HTML5之Javascript API扩展2—地理信息服务及地理位置API学习 现在比较火的一类服务叫做基于位置的服务(location-based service, LBS),这一类服务就是企业利用某点(例如用户所在的位置)坐标附近的区域提供服务的信息,比如常见的地图相关服务。在HTML5中,加入了新的地理位置API用来确定和分享地理位置。 隐私申明 在与远程Web服务器共享物理位置时,隐私是一个需要关注的问题。因此,地理位置API会要求用户先提供权限,然后Webhtml' target='_blank'>应用程序才能访问位置信息。首次访问请求地理位置数据的网页时,浏览器将显示一个通知栏,提示提供对用户位置的访问权限。按照浏览器的提示,选择相关的授权即可。 如果用户未授予权限,则不会向 Web 应用程序提供位置信息。调用相关API不会触发成功回调。 检查浏览器的支持情况 地理位置API在主流的浏览器的最新版中都支持了,但是为了兼容老的浏览器,还是要检查一下。如果地理位置 API 不可用,则 window.navigator.geolocation 将为 null,如下所示:
复制代码代码如下: function show_islocationenabled() { var str = "No, geolocation is not supported."; if (window.navigator.geolocation) { str = "Yes, geolocation is supported."; } alert( str ); }
复制代码代码如下: !DOCTYPE html html body p id="demo" Click the button to get your position: /p button Try It /button div id="mapholder" /div script var x=document.getElementById("demo"); function getLocation() { if (navigator.geolocation){ navigator.geolocation.getCurrentPosition(showPosition,showError); } else{ x.innerHTML="Geolocation is not supported by this browser."; } } function showPosition(position) { var latlon=position.coords.latitude+","+position.coords.longitude; var img_url="http://maps.googleapis.com/maps/api/staticmap?center=" + latlon + " zoom=9 size=400x300 sensor=false"; document.getElementById("mapholder").innerHTML=" img src='"+img_url+"' / } function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: x.innerHTML="User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML="Location information is unavailable." break; case error.TIMEOUT: x.innerHTML="The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML="An unknown error occurred." break; } } /script /body /html
复制代码代码如下: !DOCTYPE html html head title Geolocation API Example: Listening for Location Updates /title meta http-equiv="X-UA-Compatible" content="IE=9" / script type="text/javascript" function setText(val, e) { document.getElementById(e).value = val; } var nav = null; var watchID; function listenForPositionUpdates() { if (nav == null) { nav = window.navigator; } if (nav != null) { var geoloc = nav.geolocation; if (geoloc != null) { watchID = geoloc.watchPosition(successCallback); } else { alert("geolocation not supported"); } } else { alert("Navigator not found"); } } function clearWatch(watchID) { window.navigator.geolocation.clearWatch(watchID); } function successCallback(position) { setText(position.coords.latitude, "latitude"); setText(position.coords.longitude, "longitude"); } /script /head body label for="latitude" Latitude: /label input id="latitude" /