tiandituMap.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. <template>
  2. <view id="mapDiv" class="mapDiv" :apikey="apiKey" :prop="option" :change:prop="Trenderjs.initTMap">
  3. <view class="tool-btn">
  4. <view v-if="isGetLocation" class="position" @click.stop="Trenderjs.onPosition">
  5. <image class="position-icon" src="@/static/images/position.png" mode="aspectFit"></image>
  6. </view>
  7. <view class="position" @click.stop="$emit('openHint')">
  8. <image class="position-icon" src="@/static/images/hint.png" mode="aspectFit"></image>
  9. <text class="position-text">声明</text>
  10. </view>
  11. <view v-if="isFeedback" class="position" @click.stop="$emit('openFeedback')">
  12. <image class="position-icon" src="@/static/images/feedback.png" mode="aspectFit"></image>
  13. <text class="position-text">反馈</text>
  14. </view>
  15. </view>
  16. </view>
  17. </template>
  18. <script>
  19. import tools from './tools.js'
  20. import iconPath from '@/static/images/point.png'
  21. import { EventBus } from "@/utils/vueBus.js"
  22. import c from "@/config/index.js"
  23. export default {
  24. name: "tianditu",
  25. props: {
  26. apiKey: {
  27. type: String,
  28. require: true,
  29. default: ''
  30. },
  31. },
  32. data() {
  33. return {
  34. isGetLocation:c.isGetLocation,
  35. isFeedback:c.isFeedback,
  36. checkedDot: false,
  37. Tmap: null,
  38. option: {
  39. // dotPath:dotPath,
  40. type: '',
  41. apikey: '',
  42. lng: '',
  43. lat: '',
  44. png: iconPath
  45. }
  46. };
  47. },
  48. created() {
  49. console.log('===== ', this.option)
  50. },
  51. mounted() {
  52. },
  53. beforeDestroy() {
  54. // EventBus.$off('someEvent'); // 确保在组件销毁前移除事件监听
  55. },
  56. methods: {
  57. compliteonLoadTianDiTu() {
  58. this.$emit('onLoadTianDiTu')
  59. },
  60. initCharts(lng, lat, iconPng) {
  61. this.option = {
  62. ...this.option,
  63. apikey: this.apiKey,
  64. lng,
  65. lat,
  66. png: iconPng || this.option.png,
  67. type: 'open'
  68. }
  69. // setTimeout(() => {
  70. // this.Trenderjs.getLocation()
  71. // }, 5000)
  72. },
  73. upDataCharts(lng, lat) {
  74. this.option = {
  75. ...this.option,
  76. type: 'Icon',
  77. lng,
  78. lat,
  79. png: this.customIcon || this.option.png,
  80. type: 'update'
  81. }
  82. },
  83. async nextPoint(lnglat) {
  84. var that = this;
  85. let params = {
  86. postStr: JSON.stringify({
  87. lon: lnglat.lng,
  88. lat: lnglat.lat,
  89. ver: 1,
  90. }),
  91. type: 'geocode',
  92. tk: that.apiKey
  93. }
  94. let resData = await tools.createRequest('https://api.tianditu.gov.cn/geocoder', params, true)
  95. if (resData.status === '0') {
  96. const info = tools.formatterAdressLocation(resData.result, 1)
  97. this.option = {
  98. ...this.option,
  99. apikey: this.apiKey,
  100. lng: lnglat.lng,
  101. lat: lnglat.lat,
  102. png: this.customIcon || this.option.png,
  103. type: 'update'
  104. }
  105. this.$emit('onSelect', info)
  106. } else {
  107. tools.createMessage('数据异常', 1000, false, 'error')
  108. }
  109. },
  110. }
  111. }
  112. </script>
  113. <script module="Trenderjs" lang="renderjs">
  114. import { EventBus } from "@/utils/vueBus.js"
  115. import iconPath from '@/static/images/point.png'
  116. import dotPath from '@/static/images/dot.png'
  117. import locationPath from '@/static/images/location.png'
  118. import $confog from "@/config/index.js"
  119. import { mapGetters } from "vuex"
  120. const { type } = $confog
  121. var Tmap = null;
  122. const left = -(uni.upx2px(150));
  123. export default {
  124. props: {
  125. // 点位列表
  126. siteListArr: {
  127. type: Array,
  128. default: () => {
  129. }
  130. },
  131. searchDot: {
  132. type: Boolean,
  133. default: false
  134. },
  135. },
  136. data() {
  137. return {
  138. options: {},
  139. markerList: [],
  140. labelLsit: [],
  141. MyLngLat: {
  142. lng: '',
  143. lat: ''
  144. },
  145. // 中心点位
  146. centreDot: null,
  147. // 中心点位地址解析
  148. centreText: null,
  149. // 中心点信息
  150. centreMarker: '',
  151. // 我的点位信息
  152. MyMarker: null
  153. }
  154. },
  155. computed: {
  156. ...mapGetters(['useLocation'])
  157. },
  158. mounted() {
  159. },
  160. beforeDestroy() {
  161. this.removeMapEvent()
  162. },
  163. watch: {
  164. siteListArr: {
  165. handler(newL, oldL) {
  166. this.handleSiteList(newL)
  167. },
  168. deep: true,
  169. immediate: true
  170. },
  171. centreText: {
  172. handler(newL, oldL) {
  173. if (newL && newL !== oldL) {
  174. this.$emit("centre-text-callback", newL)
  175. }
  176. },
  177. deep: true
  178. },
  179. useLocation: {
  180. handler(newL, oldL) {
  181. if (this.MyMarker) this.setMyIcon()
  182. },
  183. deep: true
  184. }
  185. },
  186. methods: {
  187. handleSiteList(newArr) {
  188. this.clearIcon().then(async (res) => {
  189. const dotArr = []
  190. if (Tmap) await this.getMapCenter();
  191. const { Lng, Lat } = this.centreDot || {};
  192. let maxIcon = false;
  193. (newArr || []).forEach((el, index) => {
  194. el.maxIcon = false;
  195. // 通过搜索自动移动到收索返回的第一个点位
  196. if (index === 0 && this.searchDot) {
  197. this.SelectedDot(el, true, 12)
  198. }
  199. const { longitude, latitude, mapTypeIcon } = el;
  200. if (Lng == longitude && Lat == latitude) {
  201. el.maxIcon = true;
  202. maxIcon = true;
  203. };
  204. this.setIcon(el);
  205. });
  206. // 是否标记中心点
  207. if (!maxIcon) this.setCentre()
  208. this.setMyIcon()
  209. })
  210. // console.log('siteListArr = ', newL)
  211. // if (this.siteListArr && this.siteListArr.length) {
  212. // setTimeout(() => {
  213. // console.log("this.centreDot 1 = ", this.centreDot)
  214. // const { longitude, latitude, mapTypeIcon } = el;
  215. // }, 10);
  216. // }
  217. },
  218. getMapCenter() {
  219. return new Promise((resolve) => {
  220. const Fn = () => {
  221. if (Tmap) {
  222. const c = Tmap.getCenter();
  223. this.centreDot = {
  224. Lng: c.getLng(),
  225. Lat: c.getLat()
  226. };
  227. this.dotParse(c);
  228. resolve()
  229. } else {
  230. setTimeout(() => {
  231. Fn()
  232. }, 100);
  233. }
  234. };
  235. Fn()
  236. })
  237. },
  238. // 中心点位逆解析
  239. dotParse(v) {
  240. try {
  241. const geocode = new T.Geocoder();
  242. geocode.getLocation(v, (result) => {
  243. if (result.getStatus() == 0) {
  244. let t = '';
  245. const { poi } = result.getAddressComponent()
  246. try {
  247. if (poi && poi.indexOf('湖北省武汉市') === 0) {
  248. const lo = poi.split('湖北省武汉市')
  249. lo.forEach((el, index) => {
  250. if (index >= 1) {
  251. t = `${t}${el}`
  252. }
  253. })
  254. }
  255. } catch (error) {
  256. //TODO handle the exception
  257. }
  258. this.centreText = t || poi
  259. } else {
  260. this.centreText = null
  261. }
  262. });
  263. } catch (error) {
  264. this.centreText = null
  265. }
  266. },
  267. onPosition() {
  268. // const { longitude, latitude } = { longitude: 114.414431, latitude: 30.482926 };
  269. // this.SelectedDot({ longitude, latitude })
  270. // this.MyLngLat = {
  271. // lng: longitude,
  272. // lat: latitude
  273. // }
  274. // console.log("this.MyLngLat = " , this.MyLngLat)
  275. // this.setMyIcon()
  276. EventBus.$emit('TianDiTuSearch', (res) => {
  277. const { longitude, latitude } = res || {};
  278. if (longitude && latitude) {
  279. this.SelectedDot({ longitude, latitude })
  280. }
  281. // // this.SelectedDot({ longitude, latitude })
  282. // // this.MyLngLat = {
  283. // // lng: longitude,
  284. // // lat: latitude
  285. // // }
  286. // // this.clearIcon()
  287. })
  288. },
  289. addMapEvent() {
  290. //移除地图的移动停止事件
  291. this.getLocation()
  292. this.removeMapEvent()
  293. if (Tmap) {
  294. Tmap.addEventListener("moveend", this.MapMoveend);
  295. Tmap.addEventListener('zoomend', this.handleZoomEvent);
  296. }
  297. },
  298. removeMapEvent() {
  299. //移除地图的移动停止事件
  300. try {
  301. if (Tmap) {
  302. Tmap.removeEventListener("moveend", this.MapMoveend);
  303. Tmap.removeEventListener("zoomend", this.handleZoomEvent);
  304. }
  305. } catch (error) {
  306. //TODO handle the exception
  307. }
  308. },
  309. // 移动地图,获取中心点
  310. MapMoveend(e) {
  311. try {
  312. // if (type === 'H6') {
  313. // const v = e.target.getCenter()
  314. // // 自然缩放移动,刷新接口
  315. // const Lng = v.getLng();
  316. // const Lat = v.getLat();
  317. // this.$emit("moveMap", { Lng, Lat })
  318. // } else {
  319. // // 地图移动,判断是否缩放/移动地图,还是通过点位定位
  320. // if (!this.checkedDot) {
  321. // const v = e.target.getCenter()
  322. // // 自然缩放移动,刷新接口
  323. // const Lng = v.getLng();
  324. // const Lat = v.getLat();
  325. // this.$emit("moveMap", { Lng, Lat })
  326. // } else {
  327. // // 点位移动,做处理
  328. // this.$nextTick(() => {
  329. // this.checkedDot = false;
  330. // })
  331. // }
  332. // }
  333. // 地图移动,判断是否缩放/移动地图,还是通过点位定位
  334. if (!this.checkedDot) {
  335. const v = e.target.getCenter()
  336. // 自然缩放移动,刷新接口
  337. if (v) {
  338. const Lng = v.getLng();
  339. const Lat = v.getLat();
  340. this.$emit("moveMap", { Lng, Lat })
  341. }
  342. } else {
  343. // 点位移动,做处理
  344. this.$nextTick(() => {
  345. this.checkedDot = false;
  346. })
  347. }
  348. } catch (error) {
  349. //TODO handle the exception
  350. }
  351. },
  352. // 点击地图标注的点位
  353. clickMapSite({ type, target, lnglat, containerPoint }) {
  354. const Lng = lnglat.getLng();
  355. const Lat = lnglat.getLat();
  356. this.$emit('handleMapSite', { Lng, Lat })
  357. },
  358. // 天地图缩放事件
  359. handleZoomEvent(event) {
  360. if (!this.labelLsit || this.labelLsit.length === 0) return;
  361. this.labelLsit.forEach(el => {
  362. this.labelShowOrHide(el)
  363. })
  364. },
  365. // 标签的显示与隐藏
  366. labelShowOrHide(label) {
  367. if (!Tmap) return
  368. let currentZoom = Tmap.getZoom();
  369. if (currentZoom >= 16) {
  370. label.show()
  371. } else {
  372. label.hide()
  373. }
  374. },
  375. initTmap_() {
  376. try {
  377. Tmap = null;
  378. Tmap = new T.Map('mapDiv', {
  379. projection: 'EPSG:4326',
  380. });
  381. } catch (error) {
  382. console.log('Tmap error= ', error)
  383. //TODO handle the exception
  384. }
  385. },
  386. setViewport() {
  387. try {
  388. console.log('window.devicePixelRatio = ', window.devicePixelRatio)
  389. console.log('window.getResolution 1 = 1 ', Tmap, window.screen.width * window.devicePixelRatio)
  390. const w = window.screen.width * window.devicePixelRatio
  391. const meta = document.createElement('meta')
  392. meta.name = 'viewport'
  393. meta.content =
  394. `width=device-width,initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0, user-scalable=no`
  395. // meta.content = `initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no`
  396. // meta.media = `(device-height: 568px)`
  397. document.head.appendChild(meta)
  398. } catch (err) {
  399. console.log('---------- ', err)
  400. }
  401. },
  402. initTMap(newValue, oldValue, ownerInstance, instance) {
  403. this.options = newValue
  404. if (newValue.type === 'open' && newValue.apikey) {
  405. if (!window.T) {
  406. // this.setViewport()
  407. const script = document.createElement('script')
  408. // script.src = "https://tile0.tianditu.gov.cn/vts?t=vt&pk=ag1adgmgd&tk=92053ec7c4309bf20d822b28f150f33d&v=1.0"
  409. script.src = 'https://api.tianditu.gov.cn/api?v=4.0&tk=' + this.options.apikey
  410. script.onload = this.initChartsRender.bind(this)
  411. document.head.appendChild(script)
  412. } else {
  413. const {
  414. lng,
  415. lat
  416. } = this.options
  417. this.initTmap_()
  418. Tmap.centerAndZoom(new T.LngLat(lng, lat), 15);
  419. this.$ownerInstance.callMethod('nextPoint', {
  420. lng,
  421. lat
  422. })
  423. Tmap.addEventListener('click', (e) => {
  424. this.$ownerInstance.callMethod('nextPoint', e.lnglat)
  425. });
  426. }
  427. } else {
  428. // 选点,更新
  429. // const {
  430. // lng,
  431. // lat
  432. // } = newValue
  433. // this.upDataChartsRender(lng, lat)
  434. this.$emit("clickMap")
  435. }
  436. },
  437. initChartsRender() {
  438. this.$ownerInstance.callMethod('compliteonLoadTianDiTu')
  439. const {
  440. lng,
  441. lat
  442. } = this.options
  443. var that = this;
  444. this.initTmap_()
  445. Tmap.centerAndZoom(new T.LngLat(lng, lat), 15);
  446. this.$ownerInstance.callMethod('nextPoint', {
  447. lng,
  448. lat
  449. })
  450. Tmap.addEventListener('click', (e) => {
  451. this.$ownerInstance.callMethod('nextPoint', e.lnglat)
  452. });
  453. // Tmap.addEventListener("moveend", (e) => {
  454. // console.log('addEventListener = ' , e)
  455. // });
  456. this.addMapEvent()
  457. this.$emit("handleSearch")
  458. },
  459. // upDataChartsRender(lng, lat) {
  460. // if (!Tmap) return
  461. // this.setIcon(lng, lat, true)
  462. // Tmap.centerAndZoom(new T.LngLat(lng, lat), 15);
  463. // },
  464. // setIcon(lng, lat, isClear, iconU, info, max = false) {
  465. setIcon(row) {
  466. const { longitude, latitude, mapTypeIcon, locationName, maxIcon } = row
  467. // const w = uni.upx2px(54)
  468. // const h = uni.upx2px(54)
  469. const icon = new T.Icon({
  470. iconUrl: mapTypeIcon || this.options.png,
  471. iconSize: maxIcon ? new T.Point(60, 60) : new T.Point(45, 45),
  472. iconAnchor: new T.Point(15, 45)
  473. });
  474. const marker = new T.Marker(new T.LngLat(longitude, latitude), {
  475. icon
  476. });
  477. // 点位注册点击事件
  478. try {
  479. marker.removeEventListener("click", this.clickMapSite);
  480. } catch (error) {}
  481. marker.addEventListener("click", this.clickMapSite);
  482. // 缓存注册点击事件的点位
  483. this.markerList.push(marker)
  484. Tmap.addOverLay(marker);
  485. if (locationName) {
  486. try {
  487. var label = new T.Label({
  488. // text: this.setLable(locationName),
  489. text: locationName,
  490. position: marker.getLngLat(),
  491. offset: new T.Point(left, 30)
  492. });
  493. Tmap.addOverLay(label);
  494. label.setLngLat(marker.getLngLat());
  495. label.setBorderLine(0);
  496. // label.setBackgroundColor ('transparent');
  497. label.setFontSize(10);
  498. this.labelLsit.push(label)
  499. // 判断当前是否显示
  500. this.labelShowOrHide(label)
  501. } catch (error) {
  502. //TODO handle the exception
  503. console.log("info = error ", error)
  504. }
  505. }
  506. },
  507. // 移除点位,并注销点位绑定的点击事件
  508. clearIcon() {
  509. return new Promise((resolve, reject) => {
  510. try {
  511. (this.markerList || []).forEach(el => {
  512. try {
  513. el.removeEventListener("click", this.clickMapSite);
  514. } catch (error) {}
  515. });
  516. this.markerList = [];
  517. this.labelLsit = [];
  518. this.centreMarker = null;
  519. this.MyMarker = null;
  520. Tmap.clearOverLays();
  521. this.setMyIcon()
  522. } catch (error) {
  523. //TODO handle the exception
  524. } finally {
  525. resolve()
  526. }
  527. })
  528. },
  529. getLocation() {
  530. var lo = new T.Geolocation();
  531. console.log("天地图获取定位 = ", lo, lo.getStatus())
  532. try {
  533. lo.getCurrentPosition((res) => {
  534. console.log('获取定位', res)
  535. });
  536. } catch (error) {
  537. //TODO handle the exception
  538. console.log("天地图获取定位 = error ", error)
  539. }
  540. },
  541. SelectedDot(res, dot = false, level = 16) {
  542. this.checkedDot = dot
  543. const { longitude, latitude } = res;
  544. Tmap.panTo(new T.LngLat(longitude, latitude), level); // 移动到选中的点位
  545. setTimeout(function() {
  546. this.checkedDot = false
  547. }, 40);
  548. },
  549. setMaxIcon() {
  550. },
  551. setMyIcon() {
  552. const { longitude, latitude } = this.useLocation || {}
  553. if (!Tmap || !longitude || !latitude) return;
  554. // const w = uni.upx2px(54)
  555. // const h = uni.upx2px(54)
  556. const icon = new T.Icon({
  557. iconUrl: locationPath,
  558. iconSize: new T.Point(30, 30)
  559. });
  560. const marker = new T.Marker(new T.LngLat(longitude, latitude), {
  561. icon
  562. });
  563. Tmap.addOverLay(marker);
  564. try {
  565. marker.removeEventListener("click", () => {});
  566. } catch (error) {}
  567. marker.addEventListener("click", () => {});
  568. this.MyMarker = marker
  569. },
  570. setLable(locationName) {
  571. let el = '';
  572. for (let i = 0; i < locationName.length; i++) {
  573. if (!i || i % 10) {
  574. el += `${locationName[i]}`
  575. } else {
  576. el += `<br>${locationName[i]}`
  577. }
  578. };
  579. return `<p class='map-label'>${el}<p>`
  580. },
  581. // setTcon
  582. // centreDot
  583. // 设置中心点坐标
  584. setCentre() {
  585. if (type !== 'H6') return
  586. // siteListArr
  587. if (this.centreDot) {
  588. try {
  589. const { Lng, Lat } = this.centreDot || {};
  590. // const w = uni.upx2px(54)
  591. // const h = uni.upx2px(92)
  592. const icon = new T.Icon({
  593. iconUrl: dotPath,
  594. iconSize: new T.Point(27, 46)
  595. });
  596. const d_ = new T.Marker(new T.LngLat(Lng, Lat), {
  597. icon,
  598. zIndexOffset: 666
  599. });
  600. Tmap.addOverLay(d_);
  601. this.centreMarker = d_
  602. } catch (error) {
  603. //TODO handle the exception
  604. console.log('this.centreDot error ', error)
  605. }
  606. }
  607. }
  608. },
  609. }
  610. </script>
  611. <style lang="scss">
  612. .mapDiv {
  613. width: 100%;
  614. height: 100%;
  615. }
  616. .tool-btn {
  617. position: fixed;
  618. right: 30rpx;
  619. bottom: 45vh;
  620. z-index: 1000;
  621. }
  622. .position {
  623. width: 94rpx;
  624. // height: 99rpx;
  625. background-color: #fff;
  626. padding: 10rpx;
  627. border-radius: 22rpx;
  628. padding: 23rpx 20rpx 22rpx 20rpx;
  629. .position-icon {
  630. width: 54rpx;
  631. height: 54rpx;
  632. path {
  633. fill: #3291F8;
  634. }
  635. }
  636. .position-text{
  637. display: inline-block;
  638. width: 100%;
  639. text-align: center;
  640. font-size: 26rpx;
  641. color: #3291F8;
  642. line-height: 1.2;
  643. }
  644. &+.position{
  645. margin-top: 20rpx;
  646. }
  647. }
  648. </style>