HTML5的Geolocation地理位置定位API使用教程
watchPosition方法的使用方式和getCurrentPosition类似,不同的是,success函数会执行多次,一旦获取到最新的位置数据,success函数就会被触发,与之相似地,如果连续获取最新的数据失败时,error函数也会被执行多次。
JavaScript Code复制内容到剪贴板
navigator.geolocation.clearWatch(watchId); 上面就是Geolocation的常用的三个API,日常开发中我们可根据实际情况选用合适的方法,进而获取用户的位置信息。
JavaScript Code复制内容到剪贴板
if ('geolocation' in navigator) { // getting usr's position } else { // tips: your position is not available } 最后,我们用一个简单的例子来演示在开发中是如何使用Geolocation的:
JavaScript Code复制内容到剪贴板
var API = { //get recommended data by current longitude and latitude getSurroundingRecommendations: function(longitude, latitude, callback) { //simulate data obtaining from server. setTimeout(function() { var data = [ { //item }, { //item } ]; callback(data); }, 500); } };
document.addEventListener('DOMContentLoaded', function() { //detect if Geolocation is supported if (!'geolocation' in navigator) { console.log('Geolocation is not supported in your browser'); return; }
var successHandler = function(position) { var coords = position.coords, longitude = coords.longitude, latitude = coords.latitude;
API.getSurroundingRecommendations(longitude, latitude, function(data) { console.log(data); }); }, errorHandler = function(error) { console.log(error.code, error.message); }, options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 };
navigator.geolocation.getCurrentPosition(successHandler, errorHandler, options);
}, false);
(编辑:焦作站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |