tiandituMap.vue 16 KB

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