HTML5新的API

1. Geolocation API

获取地理位置的API,geolocation是挂载在navigator对象上,该对象包括3个方法,第一个方法是getCurrentPosition,该方法接受3个参数,依次是成功的回调,失败的回调,可选的选项对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
navigator.geolocation.getCurrentPosition(function(position){
//成功的回调
var la = position.coords.latitude; //经度
var lo = position.coords.longitude; //维度
var ac = position.coords.accuracy; //经纬度坐标的精度(米/m)
var ts = position.timestamp; //时间戳
}, function(e){
//失败的回调
console.log("error code :" + e.code);
//e.code: 1 (用户拒绝共享),2(位置无效),3(超时)
console.log("error message :" + e.message);
}, {
//参数配置
enableHeighAccuracy: true, //布尔值,表示是否使用最准确的位置信息(开启后移动端较耗电)
timeout: 5000, //等待位置的最长时间
maximumAge: 25000 //表示上一次获取坐标信息的有效时间(如不需跟踪用户则可设为Infinity)
})

navigator.geolocation的第二个和第三个方法分别是:watchPosition()和clearWatch():
watchPosition方法是跟踪用户位置,效果相当于定时调用getCurrentPosition方法。

1
2
3
4
5
6
7
8
9
10
11
var watchId = navigator.geolocation.watchPosition(function(position){
//成功回调
var la = position.coords.latitude; //经度
var lo = position.coords.longitude; //维度
}, function(e){
//失败回调
console.log("error code :" + e.code);
//e.code: 1 (用户拒绝共享),2(位置无效),3(超时)
console.log("error message :" + e.message);
})
clearWatch(watchId); //取消位置跟踪

2. File API

该API支持前端去读取计算机中的文件。FileReader类型实现的是一种异步文件读取机制。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
document.querySelector("#fileBtn").addEventListener("change", function(e){
var target = e.target;
var file = target.files;
var reader = new FileReader();
reader.readAsText(file[0]); // 以纯文本的形式读取值,读取的值会存到result中
//reader.readAsDataURL(file[0]); //文件已数据URI的形式保存
//reader.readAsBinaryString(file[0]); // 一个字符串保存在result中
//reader.readAsArrayBuffer(file[0]); //一个包含文件内容的ArrayBuffer保存在result中

reader.onerror = function(){
alert("上传失败");
//reader.error.code:
//1(未找到文件),2(安全性错误),3(读取中断),4(文件不可读),5(编码错误)
};

reader.onprogress = function(){ //是否又读取了新数据,50ms触发一次

}
reader.onload = function(){
alert(reader.result);
}
}, false);

baishiwen wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!