electron獲取位置坐標信息的方法小結
前端獲取位置坐標信息,有以下幾種方法:
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,
//使用設置時間內的緩存數據,單位毫秒
//默認為0,即始終請求新數據
//如設為Infinity,則始終使用緩存數據
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=***
去調用的話,精度不高,只去到所在城市的中心點,所以基本沒啥用,想要提高精度,增加自己的投入就好。
還有一種,就是直接用map的api:
https://map.baidu.com/?qt=ipLocation&t=${Date.now()}暫時來說,還沒遇到使用上的限制,直接通過axios去調用即可(ajax等其他方式調用也行,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;
// 轉換成 gcj02 坐標
const gcj02 = coordtransform.bd09togcj02(gcj02Lng, gcj02Lat);
// 再轉換為 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進行坐標轉換,當你直接調用接口獲取數據,在使用的時候發(fā)現(xiàn)坐標不是很準確,多半是需要轉換一下之后再使用。
npm安裝一下就好
npm i coordtransform
關于electron應用獲取坐標數據,navigator的話,需要https或者是攜帶證書,搞起來比較麻煩,直接使用第三方服務就比較簡單了,上面的方法都是現(xiàn)在常用的獲取坐標的方式,可以參考一下,有問題大家不妨討論討論。
以上就是electron獲取位置坐標信息的方法小結的詳細內容,更多關于electron獲取坐標信息的資料請關注腳本之家其它相關文章!
相關文章
bootstrap配合Masonry插件實現(xiàn)瀑布式布局
這篇文章主要為大家詳細介紹了bootstrap配合Masonry插件實現(xiàn)瀑布式布局,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-01-01
深入理解JavaScript Promise鏈式調用與錯誤處理機制
在JavaScript的異步編程中,Promise是一個非常重要的概念,它允許我們以鏈式的方式處理異步操作,使得代碼更加清晰和易于管理,本文將通過一系列代碼示例,深入探討Promise的鏈式調用和錯誤處理機制,需要的朋友可以參考下2024-09-09

