0、關于Geolocation
Geolocation,地理位置API。用于擷取使用者的位置資訊。它不算是現有的HTML5标準的“直系”成員,但是是W3C的一個标準。它幾乎就是一個真正的JavaScript API!
1、位置相關
1.1、經緯度表示位置
要想知道使用者的位置,就需要有一個坐标系統,這就是我們的經緯度。一般我們用度/分/秒表示經緯度,如果需要将經緯度轉換為小數,可以使用如下函數:
function degreesToDecimal(degrees, minutes, seconds){
return degrees + (minutes / 60) + (seconds / 3600);
}
1.2、API如何确定你的位置
浏覽器要擷取你的位置資訊,并不要求你非得使用最新的智能手機,即使桌面浏覽器也能擷取你的位置。那麼是如何擷取到位置的呢?
其實,擷取位置資訊的方式有很多,比如:
- IP位址 --通過ip位址庫擷取你的位置
- GPS --通過全球定位系統擷取你的位置(高精度)
- 蜂窩電話 --通過三角定位擷取你的位置
- Wi-Fi -- 同樣适用類似蜂窩電話的三角定位擷取位置
我們沒辦法知道裝置是使用的何種方法擷取我們的位置資訊,一些聰明的浏覽器很可能會使用多種方式來确定你的位置。
2、如何使用Geolocation
在使用Geolocation之前,我們需要先是否支援,通過如下代碼:
if(navigator.geolocation){
//Supported.
} else {
window.alert('No geolocation support.');
}
2.1、擷取位置
擷取位置資訊的方法是一個異步方法,我們應該如下來使用它:
if(navigator.geolocation){
var callback = function(pos){
console.log('你的位置是:', pos);
};
navigator.geolocation.getCurrentPosition(callback);
} else {
window.alert('No geolocation support.');
}
其中pos長什麼樣呢?大概是如下這個樣子的:
{
coords: { // Coordinates
accuracy: 137082,
altitude: null,
altitudeAccuracy: null,
heading: null,
latitude: 24.1848198,
longitude: 120.63149479999998,
speed: null
},
timestamp: 1453877895563
}
其中latitude和longitude就是我們的經緯度了。
該方法的文法是:navigator.geolocation.getCurrentPosition(success[, error[, options]]),具體參數含義,請接着往下看。
2.2、監控位置變化
在2.1中,我們知道如何擷取位置,那如何監控位置變化呢?很容易相當的辦法,就是我們定時去擷取位置資訊,然後比對。那麼有沒有更好的方式呢?當然,Geolocation API已經幫我們考慮好了。如下:
//正常時,會擷取到一個地理位置資訊
var watchSuccess = function(pos){
var latitude = pos.coords.latitude;
var longitude = pos.coords.longitude;
console.log('你的經緯度是:', latitude, longitude);
};
//錯誤時,函數會接收一個錯誤對象
var watchError = function(err){
console.warn(err, err.code, err.message);
};
var watcherId = navigator.geolocation.watchPosition(watchSuccess, watchError);
watchPosition方法的文法是:id = navigator.geolocation.watchPosition(success[, error[, options]])。是以,我們還可以針對這個方法設定參數:
var options = {
enableHighAccuracy: false, //預設false,為true時,則選擇最高的精度擷取位置
timeout: 5000, //每次擷取位置資訊的最長時間,預設是無限的
maximumAge: 0 // 緩存時間(毫秒),如果為0,則每次擷取最新的
};
2.3 清除監控
既然我們有監控方法,那麼該如何停止呢?這就要借助清除監控的方法了,代碼如下:
navigator.geolocation.clearWatch(watcherId);
watcherId是2.2中監控時的傳回值。
2.4、如何計算距離?
給予兩個坐标點,如何計算兩者之間的距離呢?一般采用半正矢(Haversine)公式,具體代碼如下:
function degreesToRadians(degrees){ var radians = (degrees * Math.PI) / 180; return radians; }
function computeDistince(startCoords, destCoords){ var Radius = 6371; //每度在地球上的距離(km)
var startLatRads = degreesToRadians(startCoords.latitude);
var startLongRads = degreesToRadians(startCoords.longitude);
var destLatRads = degreesToRadians(destCoords.latitude);
var destLongRads = degreesToRadians(destCoords.longitude);
var distince = Math.acos(
Math.sin(startLatRads) * Math.sin(destLatRads) +
Math.cos(startLatRads) * Math.cos(destLatRads) *
Math.cos(startLongRads - destLongRads)
) * Radius;
return distince;
}
3、擴充
地理位置API單獨使用意義不大,一般來說,結合地圖就可以實作很複雜的功能了。
待續...