国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > HTML > 正文

HTML5 Geolocation API的正確使用方法

2024-08-26 00:21:11
字體:
來源:轉載
供稿:網友

Geolocation是HTML5標準下的一個Web API,利用它可以獲取設備的當前位置信息(坐標),此API具有三個方法:getCurrentPosition、watchPosition和clearWatch,其中最常用的是getCurrentPosition方法,剩下兩個方法需要搭配使用!

使用方法:

瀏覽器兼容性檢測:

該api通過navigator.geolocation對象發布,只有在此對象存在的情況下,才可以使用它的地理定位服務,檢測方法如下:

if (navigator.geolocation) {    // 定位代碼寫在這里} else {    alert('Geolocation is not supported in your browser')}

獲取用戶的當前位置:

使用getCurrentLocation方法即可獲取用戶的位置信息,該方法有三個參數:

 

參數列表 類型 說明
handleSuccess Function 成功時調用函數handleSuccess
handleError Function 失敗時調用函數handleError
options Object 初始化參數

 

// 初始化參數const options = {  // 高精確度: true / false  enableHighAccuracy: true,  // 等待響應的最長時間 單位:毫秒  timeout: 5 * 1000,  // 應用程序愿意接受的緩存位置的最長時間  maximumAge: 0}// 成功回調函數 : data包含位置信息const handleSuccess = data => console.log(data)// 失敗回調函數 : error包含錯誤信息const handleError = error => console.log(error)if (navigator.geolocation) {    // 定位代碼寫在這里    navigator.geolocation.getCurrentPosition(handleSuccess, handleError, options)} else {    alert('Geolocation is not supported in your browser')}

下面是具有更多細節的代碼:

const handleSuccess = data => {  const {     coords, // 位置信息    timestamp // 成功獲取位置信息時的時間戳  } = data  const {    accuracy, // 返回結果的精度(米)    altitude, // 相對于水平面的高度    altitudeAccuracy, // 返回高度的精度(米)    heading, // 主機設備的行進方向,從正北方向順時針方向    latitude, // 緯度    longitude, // 經度    speed // 設備的行進速度  } = coords  // 打印出來看看  console.log('timestamp =', timestamp)  console.log('accuracy =', accuracy)  console.log('altitude =', altitude)  console.log('altitudeAccuracy =', altitudeAccuracy)  console.log('heading =', heading)  console.log('latitude =', latitude)  console.log('longitude =', longitude)  console.log('speed =', speed)}const handleError = error => {  switch (error.code) {    case 1:      console.log('位置服務請求被拒絕')      break    case 2:      console.log('暫時獲取不到位置信息')      break    case 3:      console.log('獲取信息超時')      break    case 4:      console.log('未知錯誤')      break  }}const opt = {  // 高精確度: true / false  enableHighAccuracy: true,  // 等待響應的最長時間 單位:毫秒  timeout: 5 * 1000,  // 應用程序愿意接受的緩存位置的最大年限  maximumAge: 0}if (navigator.geolocation) {  navigator.geolocation.getCurrentPosition(handleSuccess, handleError, opt)} else {  alert('Geolocation is not supported in your browser')}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到HTML教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 桓仁| 合作市| 布尔津县| 河北区| 丹巴县| 泌阳县| 合阳县| 河曲县| 湖北省| 文登市| 郸城县| 雷州市| 瑞丽市| 曲靖市| 万荣县| 普陀区| 昭苏县| 富顺县| 罗定市| 武鸣县| 桂东县| 青龙| 张家口市| 舒城县| 大理市| 庆城县| 扬中市| 遵义县| 许昌市| 龙泉市| 抚顺市| 紫云| 三亚市| 平原县| 偏关县| 广丰县| 浦县| 威远县| 年辖:市辖区| 德州市| 勃利县|