手機端定位獲取使用者位置資訊
阿新 • • 發佈:2019-01-05
很多時候,我們需要獲取手機端使用者的位置資訊,當然這需要使用者的同意授權才能進行獲取,下面介紹下我在專案中使用的定位
由於本專案web端使用的是高德地圖,因此手機端定位也使用高德的定位介面
<html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width"> <title>瀏覽器定位</title> <link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/> <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=你的key"></script> <script type="text/javascript" src="http://cache.amap.com/lbs/static/addToolbar.js"></script> <body> <div id='container'></div> <div id="tip"></div> <script type="text/javascript"> var map, geolocation; //載入地圖,呼叫瀏覽器定位服務 map = new AMap.Map('container', { resizeEnable: true }); map.plugin('AMap.Geolocation', function() { geolocation = new AMap.Geolocation({ enableHighAccuracy: true,//是否使用高精度定位,預設:true timeout: 10000, //超過10秒後停止定位,預設:無窮大 buttonOffset: new AMap.Pixel(10, 20),//定位按鈕與設定的停靠位置的偏移量,預設:Pixel(10, 20) zoomToAccuracy: true, //定位成功後調整地圖視野範圍使定位位置及精度範圍視野內可見,預設:false buttonPosition:'RB' }); map.addControl(geolocation); geolocation.getCurrentPosition(); AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位資訊 AMap.event.addListener(geolocation, 'error', onError); //返回定位出錯資訊 }); //解析定位結果 function onComplete(data) { var str=['定位成功']; str.push('經度:' + data.position.getLng()); str.push('緯度:' + data.position.getLat()); if(data.accuracy){ str.push('精度:' + data.accuracy + ' 米'); }//如為IP精確定位結果則沒有精度資訊 str.push('是否經過偏移:' + (data.isConverted ? '是' : '否')); var point = data.position.getLng()+","+data.position.getLat(); poiToaddress(point); document.getElementById('tip').innerHTML = str.join('<br>'); } //解析定位錯誤資訊 function onError(data) { document.getElementById('tip').innerHTML = '定位失敗'; } //座標點轉地址 function poiToaddress(poi) { AMap.plugin(["AMap.Geocoder"], function () { var geocoder = new AMap.Geocoder({ city: "0315", //城市,預設:“全國” radius: 500 //範圍,預設:500,以已知座標為中心點,radius為半徑,返回範圍內興趣點和道路資訊 }); geocoder.getAddress(poi, function (status, result) { if (status === 'complete' && result.info === 'OK') { var address = result.regeocode.formattedAddress; //返回地址描述 address2point(address); console.log("地址::"+address); } }); }) } //地址轉座標 function address2point(address) { AMap.plugin(["AMap.Geocoder"], function () { var geocoder = new AMap.Geocoder({ city: "0315", //城市,預設:“全國” radius: 500 //範圍,預設:500,以已知座標為中心點,radius為半徑,返回範圍內興趣點和道路資訊 }); geocoder.getLocation(address, function (status, result) { if (status === 'complete' && result.info === 'OK') { var geocode = result.geocodes[0]; var resultStr = geocode.location.lng + "," + geocode.location.lat; console.log(“座標::”+resultStr); } }); }) } </script> </body> </html>
讓我們一起遨遊在程式碼的海洋裡!