天天看點

vue實作騰訊地圖元件

在index.html頁面引入以下代碼

<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=GOZBZ-MWHKV-GDSPP-UPRNN-YUWEE-EHB5U"></script>
  <script type="text/javascript" src="http://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>
  <script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
           

自定義TXMap地圖元件

<template>
  <a-modal :title="title" :visible="showModel" :width="width" @cancel="onClose" @ok="ok">
    <p></p>
    <div :key="mapKey" :id="'container_' + mapKey" :style="'width:' + (width - 80) + 'px;height:500px;'"></div>
    <p>經度:{{longitude}} 緯度:{{latitude}} 位址:{{address}}</p>
    <a-button type="primary" @click="buttonPosition" icon="environment" :loading="loading">定位</a-button>
    <a-input-search style="width: 300px" placeholder="位址搜尋" v-model="searchAdress" enter-button @search="onSearch" />
    <a-list style="height: 200px;overflow: scroll">
      <a-list-item @click="selectAddr(addr)" :key="idx" v-for="(addr, idx) in narAddress"><h3>{{addr.name}} <a-tag>{{addr.category}}</a-tag></h3>
        <br><h7>位址:{{addr.address}}</h7></a-list-item>
    </a-list>
  </a-modal>
</template>

<script>
export default {
  props: {
    show: {
      default: false
    },
    width: {
      default: 680
    },
    title: {
      default: ''
    }
  },
  name: 'TXMap',
  computed: {
    showModel: {
      get: function () {
        this.setMap()
        return this.show
      },
      set: function () {
      }
    }
  },
  data () {
    return {
      mapKey: new Date().getTime(),
      /** loading **/
      loading: false,
      /** 位址 **/
      searchAdress: '百花山路',
      detailcontent: '這是我目前的位置',
      address: '',

      longitude: 106.72622323036194, // 經度
      latitude: 26.86139511254856, // 緯度
      city: '',
      /** 定位 **/
      geolocation: null,

      myLatlng: null,
      map: null,
      geo: null,

      markerSelect: null,
      labelMarkerSelect: null,
      narAddress: [],
      zoom: 13
    }
  },
  watch: {
  },
  methods: {

    /** **/
    onClose () {
      this.$emit('close')
    },
    initMap (location = null) {
      // let _this = this
      if (!location) {
        this.getPosition()
        // setTimeout(function () {
        //   _this.setMap()
        // }, 3000)
      } else {
        this.longitude = location.lng
        this.latitude = location.lat
        this.setMap()
        // setTimeout(function () {
        //   _this.setMap()
        // }, 3000)
      }
    },

    /** ***/
    ok () {
      let location = {
        lat: this.latitude,
        lng: this.longitude
      }
      this.$emit('position', location)
      this.$emit('close')
    },

    /** 進行位址搜尋 **/
    onSearch () {
      let _this = this
      // returnCitySN["cip"]+','+returnCitySN["cname"] returnCitySN['cname'] 在index.html 引入了<script src="http://pv.sohu.com/cityjson?ie=utf-8">
      // eslint-disable-next-line no-undef
      let search = returnCitySN['cname'].split('省')[0] + '省,' + returnCitySN['cname'].split('省')[1]
      if (_this.searchAdress) {
        search += ',' + _this.searchAdress
      }
      console.log(search)
      _this.geo.getLocation(search)// 位址
      _this.geo.setComplete(function (res) {
        console.log(res)
        _this.latitude = res.detail.location.lat
        _this.longitude = res.detail.location.lng
        _this.detailcontent = res.detail.address
        _this.address = res.detail.address
        _this.setMap()
        _this.detailcontent = '這是我目前的位置'

        // eslint-disable-next-line no-undef
        let center = new qq.maps.LatLng(_this.latitude, _this.longitude)
        // eslint-disable-next-line no-undef
        var geocoder = new qq.maps.Geocoder({
          complete (res) {
            console.log(res)
            _this.narAddress = res.detail.nearPois
          }
        })
        geocoder.getAddress(center)
      })
    },

    /** 按鈕 **/
    buttonPosition () {
      this.loading = true
      this.getPosition()
    },

    // 第一部分
    /** 定位獲得目前位置資訊 **/
    getMyLocation () {
      // eslint-disable-next-line no-undef
      this.geolocation = new qq.maps.Geolocation('GOZBZ-MWHKV-GDSPP-UPRNN-YUWEE-EHB5U', 'shopMap')
      this.getPosition()
    },
    /** 執行定位 **/
    getPosition () {
      // this.geolocation.getIpLocation(this.showPosition, this.showErr)
      this.geolocation.getLocation(this.showPosition, this.showErr)// 或者用getLocation精确度比較高
    },
    showPosition (position) {
      let _this = this
      console.log('定位成功:', position)
      this.latitude = position.lat // 經度
      this.longitude = position.lng // 緯度
      this.city = position.city
      // eslint-disable-next-line no-undef
      let center = new qq.maps.LatLng(this.latitude, this.longitude)
      // eslint-disable-next-line no-undef
      var geocoderPos = new qq.maps.Geocoder({
        complete (res) {
          console.log('定位成功', res)
          _this.narAddress = res.detail.nearPois
        }
      })
      geocoderPos.getAddress(center)
      this.setMap()
      // 消除loading
      this.loading = false
      this.address = position.province + position.city
    },
    showErr () {
      console.log('定位失敗:')
      this.getPosition()// 定位失敗再請求定位,測試使用
    },
    // 第二部分
    /** 位置資訊在地圖上展示 **/
    setMap () {
      let _this = this
      // 步驟:定義map變量 調用 qq.maps.Map() 構造函數   擷取地圖顯示容器
      // 設定地圖中心點
      // eslint-disable-next-line no-undef
      let center = new qq.maps.LatLng(this.latitude, this.longitude)
      // 定義工廠模式函數
      var myOptions = {
        zoom: _this.zoom, // 設定地圖縮放級别
        center: center, // 設定中心點樣式
        // eslint-disable-next-line no-undef
        mapTypeId: qq.maps.MapTypeId.ROADMAP // 設定地圖樣式詳情參見MapType
      }
      // //擷取dom元素添加地圖資訊
      // eslint-disable-next-line no-undef
      let map = new qq.maps.Map(document.getElementById('container_' + _this.mapKey), myOptions)
      // 第三部分
      /** 給定位的位置添加圖檔标注 **/
      // eslint-disable-next-line no-undef,no-unused-vars
      var marker = new qq.maps.Marker({
        position: center,
        map: map
      })
      // 給定位的位置添加文本标注
      // eslint-disable-next-line no-undef,no-unused-vars,no-redeclare
      var marker = new qq.maps.Label({
        position: center,
        map: map,
        content: this.detailcontent
      })
      /** 資訊标記 **/
      // eslint-disable-next-line no-undef
      var infoWin = new qq.maps.InfoWindow({
        map: map
      })
      /** 點選後生成的地表名稱 **/
      let address = '此地'
      // eslint-disable-next-line no-undef
      var geocoder = new qq.maps.Geocoder({
        complete (res) {
          console.log(res)
          address = res.detail.nearPois[0].name // 這裡是你點選之處根據經緯度傳回的地點名稱
          _this.narAddress = res.detail.nearPois
        }
      })
      // 第四部分
      /** 給地圖添加點選事件,并擷取滑鼠點選的經緯度 **/
      // eslint-disable-next-line no-undef,no-unused-vars
      qq.maps.event.addListener(map, 'click', function (event) {
        console.log(event)
        this.longitude = event.latLng.getLng()
        this.latitude = event.latLng.getLat()

        geocoder.getAddress(event.latLng)
        setTimeout(() => {
          infoWin.open()
          infoWin.setContent(`<div style="text-align:center;white-space:nowrap;">${address}</div>`)
          infoWin.setPosition(event.latLng)
        }, 200)
      })
    },
    /** 選中位址 **/
    selectAddr (addr) {
      let _this = this
      this.longitude = addr.latLng.lng
      this.latitude = addr.latLng.lat
      _this.address = addr.address
      _this.zoom = 17
      _this.detailcontent = addr.name
      this.setMap()
    }
  },
  mounted () {
    this.setMap()
  },
  created () {
    // eslint-disable-next-line no-undef
    this.geolocation = new qq.maps.Geolocation('GOZBZ-MWHKV-GDSPP-UPRNN-YUWEE-EHB5U', 'shopMap')
    // eslint-disable-next-line no-undef
    this.geo = new qq.maps.Geocoder()
  }
}
</script>

<style scoped>

</style>