今年初次接觸行動端 WEB 開發,邊學 HTML5 邊做,主要用了 jQuery Mobile。手機端第一次碰到定位功能時,才發現 PC 端瀏覽器首次呼叫會跳出「是否開啟定位功能」的提示。這個互動對某些產品情境來說並不理想,於是就開始研究各種替代方案,以下把結果整理出來。
標準做法是 navigator.geolocation 取得經緯度,再交給地圖服務商把座標換成行政區名稱。前提要先引入百度地圖 API:
<script src="https://api.map.baidu.com/api?v=1.4" type="text/javascript"></script>
var getLocation = function (successFunc, errorFunc) {
// 先寫入一個預設城市,避免定位失敗時畫面空白
var defCity = {
id: '000001',
name: '北京市',
date: curDateTime()
};
$.cookie('DEFAULTCITY', JSON.stringify(defCity), { expires: 1, path: '/' });
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var point = new BMap.Point(lon, lat); // 百度座標是經度在前
var gc = new BMap.Geocoder();
gc.getLocation(point, function (rs) {
var addComp = rs.addressComponents;
var curCity = {
id: '',
name: addComp.province,
date: curDateTime()
};
$.cookie('CURRENTCITY', JSON.stringify(curCity), { expires: 7, path: '/' });
if (successFunc != undefined) successFunc(addComp);
});
}, function (error) {
switch (error.code) {
case 1: alert("位置服務被拒絕。"); break;
case 2: alert("暫時獲取不到位置資訊。"); break;
case 3: alert("獲取位置資訊超時。"); break;
default: alert("未知錯誤。"); break;
}
// 失敗時回落到預設城市
var curCity = { id: '000001', name: '北京市', date: curDateTime() };
$.cookie('DEFAULTCITY', JSON.stringify(curCity), { expires: 1, path: '/' });
if (errorFunc != undefined) errorFunc(error);
}, { timeout: 5000, enableHighAccuracy: true });
} else {
alert("你的瀏覽器不支援地理位置功能。");
if (errorFunc != undefined) errorFunc("不支援地理位置");
}
};
error.code 的三個值分別代表:使用者拒絕授權、無法取得位置、以及逾時。實務上一定要處理這三種情況並提供預設值,否則使用者一按拒絕,整個頁面流程就斷了。
早期的做法是直接引入服務商提供的 JS 檔:
<script type="text/javascript" src="https://fw.qq.com/ipaddress"></script> <script type="text/javascript"> document.write(IPData[0]); // IP 位址 document.write(IPData[2]); // 省 document.write(IPData[3]); // 市 </script>
這個騰訊介面目前已經停用了。可用的替代方案有幾個:
// 新浪 https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js // 帶 ip 參數可測試指定 IP https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=127.0.0.1
<script type="text/javascript">
$.getScript('https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js', function () {
if (remote_ip_info.ret == '1') {
alert('國家:' + remote_ip_info.country + '\n省:' + remote_ip_info.province +
'\n市:' + remote_ip_info.city + '\n區:' + remote_ip_info.district +
'\nISP:' + remote_ip_info.isp + '\n類型:' + remote_ip_info.type);
} else {
alert('沒有找到匹配的 IP 資訊!');
}
});
</script>
其他曾經常見的來源:
// 淘寶(GET) https://ip.taobao.com/service/getIpInfo.php?ip=IP位址 // 太平洋 https://whois.pconline.com.cn/?ip=IP位址字串 // 搜狐(預設 GBK,可加 ?ie=utf-8 指定編碼) https://pv.sohu.com/cityjson https://txt.go.sohu.com/ip/soip // 網易有道 https://www.youdao.com/smartresult-xml/search.s?type=ip&q=IP位址
<script>
var ip = "124.127.108.133";
var url = "https://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
$.getJSON(url, function (json) {
var area = json.data.area;
var region = json.data.region;
alert("您所在的城市是:" + area + region);
});
</script>
<script>
var url = 'https://chaxun.1616.net/s.php?type=ip&output=json&callback=?&_=' + Math.random();
$.getJSON(url, function (data) {
alert(data.Ip);
});
</script>
第一,這些第三方 IP 查詢服務都是非官方介面,隨時可能改版或停止服務,正式環境請找有 SLA 的商業服務並做好快取,不要每次請求都打一次。
第二,透過 JSONP 動態插入 script 的做法要特別小心,因為它等同於執行對方回傳的任何程式碼。若服務支援 HTTPS 與 CORS,改用 fetch 會安全得多。
第三,IP 定位的精度只到城市層級,且受 VPN、行動網路出口節點影響很大,不適合當成需要準確性的判斷依據。
先寫到這,還有其他工作要處理,之後有空再回來測試其餘介面。若有更好的做法歡迎提供。