location.js 19 KB

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