electron獲取位置坐標信息的方法小結(jié)
前端獲取位置坐標信息,有以下幾種方法:
1.通過原生方法獲取
優(yōu)點:自定隨意編寫邏輯
缺點:需要授權,或者某些場景沒辦法獲取
function handlePosition (position: GeolocationPosition) {
console.debug(position);
/*
{
coords: {
accuracy: 1804475.2390180232
altitude: null
altitudeAccuracy: null
heading: null
latitude: 123.123
longitude: 123.123
speed: null
}
}
*/
}
function handlePositionError (e: GeolocationPositionError) {
switch (e.code) {
case e.PERMISSION_DENIED:
logger.info('位置服務被拒絕', e.message);
break;
case e.POSITION_UNAVAILABLE:
logger.info('暫時獲取不到位置信息', e.message);
break;
case e.TIMEOUT:
logger.info('獲取信息超時', e.message);
break;
default:
logger.info('未知錯誤', e.message);
break;
}
};
function setLocation () {
const options = {
//是否使用高精度設備,如GPS。默認是true
enableHighAccuracy: true,
//超時時間,單位毫秒,默認為0
timeout: 5000,
//使用設置時間內(nèi)的緩存數(shù)據(jù),單位毫秒
//默認為0,即始終請求新數(shù)據(jù)
//如設為Infinity,則始終使用緩存數(shù)據(jù)
maximumAge: 0,
};
if (navigator.permissions) {
navigator.permissions.query({ name: 'geolocation' }).then(function (result) {
console.debug('permissions:', result.state);
if (result.state === 'granted') {
navigator.geolocation.getCurrentPosition(handlePosition, handlePositionError, options);
} else if (result.state === 'prompt') {
navigator.geolocation.getCurrentPosition(handlePosition, handlePositionError, options);
} else if (result.state === 'denied') {
alert('Permission denied. Please allow location access in your browser settings.');
}
});
} else {
navigator.geolocation.getCurrentPosition(handlePosition, handlePositionError, options);
}
}2.直接使用第三方服務
例如:百度地圖等一些線上的服務商,只要你自己在使用過程當中沒什么限制。
以百度為例,如果是直接自己創(chuàng)建ak,通過
https://api.map.baidu.com/location/ip?ip=***&coor=bd09ll&ak=***
去調(diào)用的話,精度不高,只去到所在城市的中心點,所以基本沒啥用,想要提高精度,增加自己的投入就好。
還有一種,就是直接用map的api:
https://map.baidu.com/?qt=ipLocation&t=${Date.now()}暫時來說,還沒遇到使用上的限制,直接通過axios去調(diào)用即可(ajax等其他方式調(diào)用也行,get就好了)
function setLocationByBaidu(){
axios.get(`https://map.baidu.com/?qt=ipLocation&t=${Date.now()}`).then(response => {
const gcj02Lng = response.data.rgc.result.location.lng;
const gcj02Lat = response.data.rgc.result.location.lat;
// 轉(zhuǎn)換成 gcj02 坐標
const gcj02 = coordtransform.bd09togcj02(gcj02Lng, gcj02Lat);
// 再轉(zhuǎn)換為 wgs84 坐標
const wgs84 = coordtransform.gcj02towgs84(gcj02[0], gcj02[1]);
console.debug('db09 坐標:', response.data.rgc.result.location.lng, response.data.rgc.result.location.lat);
console.debug('gcj02 坐標:', gcj02);
console.debug('WGS84 坐標:', wgs84);
});
});
}上面的方法使用到了coordtransform進行坐標轉(zhuǎn)換,當你直接調(diào)用接口獲取數(shù)據(jù),在使用的時候發(fā)現(xiàn)坐標不是很準確,多半是需要轉(zhuǎn)換一下之后再使用。
npm安裝一下就好
npm i coordtransform
關于electron應用獲取坐標數(shù)據(jù),navigator的話,需要https或者是攜帶證書,搞起來比較麻煩,直接使用第三方服務就比較簡單了,上面的方法都是現(xiàn)在常用的獲取坐標的方式,可以參考一下,有問題大家不妨討論討論。
以上就是electron獲取位置坐標信息的方法小結(jié)的詳細內(nèi)容,更多關于electron獲取坐標信息的資料請關注腳本之家其它相關文章!
相關文章
JS switch判斷 三目運算 while 及 屬性操作代碼
這篇文章主要介紹了JS switch判斷 三目運算 while 及 屬性操作代碼,需要的朋友可以參考下2017-09-09
深入解析Javascript閉包的功能及實現(xiàn)方法
這篇文章主要為大家詳細解析Javascript閉包的功能及實現(xiàn)方法,感興趣的小伙伴們可以參考一下2016-07-07

