location.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. import myAmapFun from "@/utils/initmap.js"
  2. import {showConfirm} from '@/utils/common'
  3. // #ifdef H5
  4. var jweixin = require('jweixin-module');
  5. // #endif
  6. var __CFG = null;
  7. //系统参数
  8. __CFG = __CFG || {
  9. 'lat': '',
  10. 'lng': '',
  11. 'address': '',
  12. 'city':'',
  13. "UxLocation": {
  14. "lng": "",
  15. "lat": "",
  16. "address": "",
  17. 'city':'',
  18. 'temperature':'',
  19. 'weather':'',
  20. 'icon':''
  21. },
  22. iconWeatherMap:[{tit:'风',val:'weaiona',children:['有风', '平静', '微风', '和风', '清风', '强风/劲风', '疾风', '大风', '烈风', '风暴', '狂爆风', '飓风', '热带风暴', '龙卷风']},
  23. {tit:'多云',val:'weaionb',children:['少云','多云']},
  24. {tit:'晴间多云',val:'weaionc',children:['晴间多云', ]},
  25. {tit:'雪',val:'weaiond',children:['雪', '阵雪', '小雪', '中雪', '大雪', '暴雪', '小雪-中雪', '中雪-大雪', '大雪-暴雪', '冷']},
  26. {tit:'雾',val:'weaione',children:['浮尘', '扬沙', '沙尘暴', '强沙尘暴', '雾', '浓雾', '强浓雾', '轻雾', '大雾', '特强浓雾']},
  27. {tit:'晴',val:'weaionf',children:['晴', '热']},
  28. {tit:'雨夹雪',val:'weaiong',children:['雨雪天气', '雨夹雪', '阵雨夹雪']},
  29. {tit:'雨',val:'weaionh',children:['阵雨', '雷阵雨', '雷阵雨并伴有冰雹', '小雨', '中雨', '大雨', '暴雨', '大暴雨', '特大暴雨', '强阵雨', '强雷阵雨', '极端降雨', '毛毛雨/细雨', '雨', '小雨-中雨', '中雨-大雨', '大雨-暴雨', '暴雨-大暴雨', '大暴雨-特大暴雨', '冻雨']},
  30. {tit:'阴',val:'weaioni',children:['阴','未知']},
  31. {tit:'霾',val:'weaionj',children:['霾', '中度霾', '重度霾', '严重霾',]},
  32. ],
  33. };
  34. function setUxLocation(UxLocation){
  35. UxLocation = UxLocation || {};
  36. __CFG.lng = UxLocation.lng || '';
  37. __CFG.lat = UxLocation.lat || '';
  38. __CFG.address = UxLocation.address || UxLocation.addr || '';
  39. __CFG.city = UxLocation.city || UxLocation.city || '';
  40. __CFG.UxLocation = UxLocation;
  41. }
  42. //设置浏览器cookie
  43. function set_cookie(key, value, expire, path){
  44. var keys = __CFG.C_PREFIX + key;
  45. path = path || '/';
  46. var a = keys + "=" + value;
  47. if(typeof(expire) != 'undefined'){
  48. var date = new Date();
  49. expire = parseInt(expire,10);
  50. date.setTime(date.getTime() + expire*1000);
  51. a += "; expires="+date.toGMTString();
  52. }
  53. a += ";path="+path;
  54. if(__CFG.C_DOMAIN){
  55. a += ";domain="+__CFG.C_DOMAIN;
  56. }
  57. document.cookie = a;
  58. };
  59. //删除浏览器cookie
  60. function remove_cookie(key){
  61. if (!key) {
  62. return false;
  63. } else {
  64. var keys = __CFG.C_PREFIX + key;
  65. document.cookie = keys+"=;expires="+(new Date(0)).toGMTString();
  66. }
  67. };
  68. //获取浏览器cookie
  69. function get_cookie(key) {
  70. if (!key) {
  71. return false;
  72. } else {
  73. var keys = __CFG.C_PREFIX + key;
  74. var reg = new RegExp("(^| )" + keys + "=([^;]*)(;|\x24)");
  75. var result = reg.exec(document.cookie);
  76. if (result) {
  77. return result[2] || '';
  78. }
  79. return '';
  80. }
  81. };
  82. //判断是否微信
  83. function checkIsWeixin() {
  84. if (/(micromessenger)/.test(navigator.userAgent.toLowerCase())) {
  85. return true;
  86. } else {
  87. return false;
  88. }
  89. };
  90. //初始化sdk配置
  91. function initJssdk(callback ,url){
  92. callback = typeof(callback) == 'function' ? callback : function(res) {};
  93. //服务端进行签名 ,可使用uni.request替换。 签名算法请看文档
  94. // http('client/app/get_wechat',{url:url},function(res){
  95. // if(res.data){
  96. // jweixin.config({
  97. // debug: false,
  98. // appId: res.data.wxjs_config.appId,// 必填,公众号的唯一标识
  99. // timestamp:res.data.wxjs_config.timestamp,// 必填,生成签名的时间戳
  100. // nonceStr: res.data.wxjs_config.nonceStr,// 必填,生成签名的随机串
  101. // signature:res.data.wxjs_config.signature, // 必填,签名,见附录1
  102. // jsApiList: ['checkJsAPi','getLocation','onMenuShareAppMessage','onMenuShareTimeline','onMenuShareQQ','onMenuShareQZone','onMenuShareWeibo','updateAppMessageShareData','updateTimelineShareData','chooseWXPay']
  103. // });
  104. // //配置完成后,再执行分享等功能
  105. // if(callback){
  106. // callback(res.data.wxjs_config);
  107. // }
  108. // }
  109. // },true);
  110. };
  111. // 定位当前位置
  112. function getLocal(callback){
  113. callback = typeof(callback) == 'function' ? callback : function(res) {};
  114. var urls = window.location.href;
  115. initJssdk(function(signData){
  116. uni.showLoading({
  117. title: '微信定位中...'
  118. })
  119. var uxlocation = {"lng": "", "lat": "", "address": ""};
  120. jweixin.ready(function () {
  121. jweixin.getLocation({
  122. type: 'gcj02',
  123. success: function (res) {
  124. uxlocation.lng = res.longitude || '';
  125. uxlocation.lat = res.latitude || '';
  126. setUxLocation(uxlocation);
  127. AMap.plugin('AMap.Geocoder', function() {
  128. var geocoder = new AMap.Geocoder({extensions:'all'});
  129. AMap.event.addListener(geocoder, 'error', error)
  130. var lnglat = [Number(res.longitude), Number(res.latitude)]
  131. geocoder.getAddress(lnglat, function(status, result) {
  132. if (status === 'complete' && result.info === 'OK') {
  133. console.log('complete:',result);
  134. uni.hideLoading();
  135. // result为对应的地理位置详细信息
  136. var addr = '';
  137. if(result.regeocode.pois && result.regeocode.pois.length > 0){
  138. addr = result.regeocode.pois[0].name;
  139. }else if(result.regeocode.formattedAddress){
  140. addr = result.regeocode.formattedAddress;
  141. }else{
  142. addr = result.regeocode.addressComponent.city + result.regeocode.addressComponent.district
  143. }
  144. uxlocation.address = addr;
  145. setUxLocation(uxlocation);
  146. callback();
  147. }else{
  148. uni.hideLoading();
  149. callback();
  150. }
  151. });
  152. function error(res){
  153. // getGeoLocation(res.longitude,res.latitude);
  154. alert('地址信息解析失败');
  155. callback();
  156. }
  157. });
  158. },
  159. fail: function (res) {
  160. uni.hideLoading();
  161. alert('微信获取位置失败');
  162. uni.navigateTo({
  163. url: '/pages/addr/selectReceive'
  164. })
  165. },
  166. cancel: function (res) {
  167. uni.hideLoading();
  168. alert('用户拒绝获取位置');
  169. uni.navigateTo({
  170. url: '/pages/addr/selectReceive'
  171. })
  172. }
  173. });
  174. });
  175. },urls)
  176. };
  177. function getLocation(callback) {
  178. callback = typeof(callback) == 'function' ? callback : function(res) {};
  179. var num=1;
  180. var that = this;
  181. // #ifdef H5
  182. myAmapFun.getWeather({
  183. success(res){
  184. console.log(res)
  185. var uxlocation ={};
  186. //temperature 温度
  187. //weather 天气现象
  188. uxlocation.city = res.city.data;
  189. uxlocation.temperature = res.temperature.data;
  190. uxlocation.weather = res.weather.data;
  191. setUxLocation(uxlocation);
  192. callback(res.liveData);
  193. },
  194. fail(err){
  195. console.log('fail')
  196. }
  197. })
  198. // setTimeout(function (){
  199. // AMap.plugin(['AMap.Geolocation','AMap.Geocoder', 'AMap.Weather'], function() {
  200. // var geolocation = new AMap.Geolocation({
  201. // enableHighAccuracy: false, // 是否使用高精度定位,默认:true
  202. // // timeout: 10000, // 设置定位超时时间,默认:无穷大
  203. // // showMarker: true, //定位成功后在定位到的位置显示点标记,默认:true
  204. // // showCircle: true, //定位成功后用圆圈表示定位精度范围,默认:true
  205. // // panToLocation: true, //定位成功后将定位到的位置作为地图中心点,默认:true
  206. // // zoomToAccuracy:true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
  207. // extensions:'all' // 返回周边POI、道路交叉口等信息
  208. // })
  209. // geolocation.getCurrentPosition()
  210. // AMap.event.addListener(geolocation, 'complete', onComplete)
  211. // AMap.event.addListener(geolocation, 'error', onError)
  212. // var weather = new AMap.Weather();
  213. // function onComplete(data) {
  214. // // data是具体的定位信息
  215. // // that.$store.dispatch('UPDATE_ADDRESS', data.formattedAddress)
  216. // // weather.getForecast(data.addressComponent.adcode, function(err, data) {
  217. // // console.log(err, data);
  218. // // });
  219. // var lng=data.position.lng
  220. // var lat=data.position.lat
  221. // console.log(data)
  222. // weather.getLive(data.addressComponent.adcode, function(err, ress) {
  223. // console.log(err)
  224. // let weatherObj = {
  225. // temperature: ress.temperature,
  226. // currentCity: ress.city,
  227. // weatherDesc: ress.weather
  228. // }
  229. // console.log(ress)
  230. // callback(weatherObj);
  231. // });
  232. // }
  233. // function onError(data) {
  234. // // 定位出错
  235. // if (data.info == 'NOT_SUPPORTED') {
  236. // uni.showModal({
  237. // title: '提示',
  238. // content: '当前浏览器不支持定位功能' || '定位失败'
  239. // })
  240. // } else if (data.info == 'FAILED') {
  241. // uni.showModal({
  242. // title: '提示',
  243. // content: data.message || '定位失败'
  244. // })
  245. // }
  246. // }
  247. // })
  248. // }, 500);
  249. // // #endif
  250. // // #ifdef MP-WEIXIN
  251. // uni.getSetting({
  252. // success(res) {
  253. // if(res.authSetting['scope.userLocation'] != undefined){
  254. // if (res.authSetting['scope.userLocation']) {
  255. // getLocationaddr(callback)
  256. // // 已经授权,可以直接调用 getLocation 获取地理位置
  257. // } else {
  258. // showConfirm('您还未开启定位,是否去开启定位?').then(cres => {
  259. // if (cres.confirm) {
  260. // uni.openSetting({
  261. // success(res2) {
  262. // if (res2.authSetting['scope.userLocation']) {
  263. // }
  264. // }
  265. // });
  266. // callback(-1)
  267. // }
  268. // })
  269. // };
  270. // }else{
  271. // getLocationaddr(callback)
  272. // }
  273. // },
  274. // fail(err) {
  275. // console.log(err)
  276. // },
  277. // })
  278. // #endif
  279. // #ifdef APP-PLUS
  280. let system = uni.getSystemInfoSync();
  281. if(system.platform === "android"){
  282. var context = plus.android.importClass("android.content.Context");
  283. var locationManger = plus.android.importClass("android.location.LocationManager");
  284. var main = plus.android.runtimeMainActivity();
  285. var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
  286. if(!mainSvr.isProviderEnabled(locationManger.GPS_PROVIDER)){
  287. uni.showModal({
  288. title:"提示",
  289. content:"请授权位置获取地址",
  290. showCancel:false,
  291. success() {
  292. if(!mainSvr.isProviderEnabled(locationManger.GPS_PROVIDER)){
  293. var Intent = plus.android.importClass("android.content.Intent");
  294. var Settings = plus.android.importClass("android.provider.Settings");
  295. var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  296. main.startActivity(intent);
  297. }else{
  298. console.log("定位已开启")
  299. _self.setSite()
  300. }
  301. }
  302. })
  303. }else{
  304. plus.android.requestPermissions(
  305. ['android.permission.ACCESS_FINE_LOCATION'], // 理论上支持多个权限同时查询,但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
  306. function(resultObj) {
  307. var result = 0;
  308. for (var i = 0; i < resultObj.granted.length; i++) {
  309. var grantedPermission = resultObj.granted[i];
  310. console.log('已获取的权限:' + grantedPermission);
  311. result = 1
  312. }
  313. for (var i = 0; i < resultObj.deniedPresent.length; i++) {
  314. var deniedPresentPermission = resultObj.deniedPresent[i];
  315. console.log('拒绝本次申请的权限:' + deniedPresentPermission);
  316. result = 0
  317. }
  318. for (var i = 0; i < resultObj.deniedAlways.length; i++) {
  319. var deniedAlwaysPermission = resultObj.deniedAlways[i];
  320. console.log('永久拒绝申请的权限:' + deniedAlwaysPermission);
  321. result = -1
  322. }
  323. // resolve(result);
  324. // 若所需权限被拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限
  325. if (result != 1) {
  326. showConfirm('您还未开启定位,是否去开启定位?').then(res => {
  327. if (res.confirm) {
  328. gotoAppPermissionSetting()
  329. callback(result)
  330. }
  331. })
  332. }else{
  333. getLocationaddr(callback)
  334. }
  335. },
  336. function(error) {
  337. console.log('申请权限错误:' + error.code + " = " + error.message);
  338. // resolve({
  339. // code: error.code,
  340. // message: error.message
  341. // });
  342. }
  343. );
  344. }
  345. }
  346. // #endif
  347. };
  348. // 跳转到**应用**的权限页面
  349. function gotoAppPermissionSetting() {
  350. var isIos
  351. // #ifdef APP-PLUS
  352. isIos = (plus.os.name == "iOS")
  353. // #endif
  354. if (isIos) {
  355. var UIApplication = plus.ios.import("UIApplication");
  356. var application2 = UIApplication.sharedApplication();
  357. var NSURL2 = plus.ios.import("NSURL");
  358. // var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");
  359. var setting2 = NSURL2.URLWithString("app-settings:");
  360. application2.openURL(setting2);
  361. plus.ios.deleteObject(setting2);
  362. plus.ios.deleteObject(NSURL2);
  363. plus.ios.deleteObject(application2);
  364. } else {
  365. var Intent = plus.android.importClass("android.content.Intent");
  366. var Settings = plus.android.importClass("android.provider.Settings");
  367. var Uri = plus.android.importClass("android.net.Uri");
  368. var mainActivity = plus.android.runtimeMainActivity();
  369. var intent = new Intent();
  370. intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
  371. var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
  372. intent.setData(uri);
  373. mainActivity.startActivity(intent);
  374. }
  375. }
  376. function getLocationaddr(callback){
  377. callback = typeof(callback) == 'function' ? callback : function(res) {};
  378. var uxlocation = {"lng": "", "lat": "", "address": ""};
  379. uni.getLocation({
  380. type: 'gcj02',
  381. geocode: 'true',
  382. success: function(res) {
  383. uxlocation.lat = res.latitude;
  384. uxlocation.lng = res.longitude;
  385. // myAmapFun.getRegeo({
  386. // success: function(data) {
  387. // uxlocation.address = data[0].name+data[0].desc||data[0].regeocodeData.formatted_address;
  388. // uxlocation.city = data[0].regeocodeData.addressComponent.city;
  389. // setUxLocation(uxlocation);
  390. // callback(uxlocation);
  391. // },
  392. // fail: function(info) {
  393. // //失败回调
  394. // console.log(info,223)
  395. // }
  396. // })
  397. // 获取天气
  398. myAmapFun.getWeather({
  399. success(res){
  400. //temperature 温度
  401. //weather 天气现象
  402. uxlocation.city = res.city.data;
  403. uxlocation.temperature = res.temperature.data;
  404. uxlocation.weather = res.weather.data;
  405. var weather=res.weather.data;
  406. var weatherMap=__CFG.iconWeatherMap;
  407. var url=require('@/static/images/weather/weaionf.png');
  408. Object.keys(weatherMap).some((key) => {
  409. if (weatherMap[key].children.indexOf(weather)!=-1) {
  410. url=require(`@/static/images/weather/${weatherMap[key].val}.png`)
  411. return true;
  412. }
  413. })
  414. uxlocation.icon = url;
  415. setUxLocation(uxlocation);
  416. callback(res.liveData);
  417. },
  418. fail(err){
  419. console.log('fail')
  420. }
  421. })
  422. },
  423. fail: function(error) {
  424. uni.showToast({
  425. icon: 'none',
  426. title: '定位失败'
  427. })
  428. },
  429. complete: function(rs) {
  430. console.log('complete:'+JSON.stringify(rs))
  431. }
  432. })
  433. }
  434. const self = {
  435. getLocation,
  436. setUxLocation,
  437. checkIsWeixin,
  438. __CFG
  439. }
  440. export default self