如何在 Mobile Web App 中取得经纬度(转)

转载自ericsk ,地址如下:[url]http://blog.ericsk.org/archives/1347/comment-page-1[/url]


[b]以下为转载内容:[/b]

本篇文章提及的方法僅適用於 iPhone 3.0+ 及 Android-based 手機。

在寫 mobile web app 時,如果使用者是用 iPhone 3.0+ 或是 Android-based 手機來瀏覽網站時,其實還是有辦法取得手機的經緯度座標資料。以下先分別講述兩支手機各別的方法,然後再將兩個方法合成同一份 JavaScript 程式碼。
iPhone

iPhone 3.0 之後,iPhone Safari 直接支援 Geolocation API,所以你可以利用下面這段 JavaScript 程式碼來取得該 iPhone 的經緯度座標資料:

var getPosition = function(pos) {
// pos.coords.latitude 及 pos.coords.longitude 即為座標資料
};
var errorCallback = function(error) {
// 定位失敗,可能是無法定位或是使用者關閉手機的定位服務
};
navigator.geolocation.getCurrentPosition(getPosition,
errorCallback, {enableHighAccuracy: true});


Android-based

在目前 Android-based 的手機上,瀏覽器還不直接支援 Geolocation API,但是 Android-based 手機的瀏覽器都預先安裝好了 Google Gears,所以也可以透過 Google Gears 所提供的 Geolocation API 來取得座標資料:

// 先載入 Google Gears JS lib: 
// http://code.google.com/apis/gears/gears_init.js


....
if (window.google && google.gears) {
try {
var geo = google.gears.factory.create('beta.location');
geo.getCurrentPosition(getPosition,
errorCallback, {enableHighAccuracy: true});
} catch (e) {
// error
}
}


呼叫的方式與原生支援的 Geolocation API 一模一樣。
加入 IP-based Geolocation 支援

如果利用原生的 Geolocation API 或是 Google Gears 取得座標資料失敗時,其實還可以再使用 IP 作定位的動作,這時可以利用 Google AJAX API Loader 來作:

// 先載入 http://www.google.com/jsapi 取得 google ajax api loader

...
if (google.loader.ClientLocation) {
// google.loader.ClientLocation.latitude
// google.loader.ClientLocation.longitude
}

全部放在一起

最後,如果要把這些 code 全部放在一起,那就有可能會是這樣:

// 先載入:
// http://www.google.com/jsapi?key=去申請
// 還有 http://code.google.com/apis/gears/gears_init.js

....
....
var getPosition = function(pos) {
// pos.coords.latitude 及 pos.coords.longitude 即為座標資料
};
var errorCallback = function(error) {
fallbackToIPGeoLocation();
};
var fallbackToIPGeoLocation = function() {
if (google.loader.ClientLocation) {
// google.loader.ClientLocation.latitude
// google.loader.ClientLocation.longitude
} else {
// 投降了,真的無法定位
}
};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition,
errorCallback, {enableHighAccuracy: true});
} else {
if (window.google && google.gears) {
try {
var geo = google.gears.factory.create('beta.location');
geo.getCurrentPosition(getPosition,
errorCallback, {enableHighAccuracy: true});
} catch (e) {
fallbackToIPGeoLocation();
}
} else {
fallbackToIPGeoLocation();
}
}


如此一來便能在 mobile web app 中取得手機的經緯度座標資料了!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值