vue里使用腾讯地图

主要需求是:
1.通过搜索地址获取坐标经纬度,
2.通过点击地图上的位置获取地址同时获取坐标经纬度
使用了地址解析和反地址解析

npm安装腾讯地图
腾讯官方并没有在npm上发布腾讯地图插件,所以找到一个别人写的,可以直接调用腾讯地图javascript方法
链接:https://www.npmjs.com/package/qqmap

npm install qqmap --save

在组件中引入

import maps from "qqmap"
地图 DOM 元素
<div class="map">
       <el-input v-model="addressKeyword" placeholder="请输入地址来直接查找相关位置" clearable style="margin-bottom:20px">
            <el-button slot="append" icon="el-icon-search" @click="getAddressKeyword"></el-button>
        </el-input>
        <div id="container" style="width:100%; height:300px"></div>
  </div>
 

  

data:{
   //腾讯地图
      map: null,
      getAddress: null,
      getAddCode: null,
   addressKeyword: ""
}

由于在使用的把地图DOM放在了可显示隐藏的盒子里,导致了地图不显示的问题,(showModal是一个控制显示隐藏的变量;newValue是watch监听的新值)

故:

  watch: {
  showModal: function(newValue) { if (newValue) { this.init(); } } },

  初始化地图

 methods: {
    //初始化地图
    init() {
      var that = this;
      maps.init("W3YBZ-NW734-APUUL-XQTC4-76L2T-NCF70", () => {
        var myLatlng = new qq.maps.LatLng(22.547931568083015, 114.1306221485138);
        var myOptions = {
          zoom: 16,
          center: myLatlng,
          mapTypeId: qq.maps.MapTypeId.ROADMAP
        };
        that.map = new qq.maps.Map(
          document.getElementById("container"),
          myOptions
        );
        //获取点击后的地址
        qq.maps.event.addListener(that.map, "click", function(event) {
          // 获取点击后的地图坐标
          that.shopInfo.lng = event.latLng.getLng();
          that.shopInfo.lat = event.latLng.getLat();
          that.getAddressCode();
        });

        //调用地址显示地图位置并设置地址
        that.getAddress = new qq.maps.Geocoder({
          complete: function(result) {
            that.map.setCenter(result.detail.location);
            console.log(result.detail.location)
            that.shopInfo.lng = result.detail.location.lng;
            that.shopInfo.lat = result.detail.location.lat;
            var marker = new qq.maps.Marker({
              map: that.map,
              position: result.detail.location
            });
          }
        });
        //通过坐标来显示地图地址
        that.getAddCode = new qq.maps.Geocoder({
          complete: function(result) {
            that.addressKeyword = result.detail.address;
          }
        });
      });
    },

  

   //通过地址获得位置
    getAddressKeyword() {
      //通过getLocation();方法获取位置信息值
      this.getAddress.getLocation(this.addressKeyword);调用自带的接口
    },
    // 通过坐标获得地址
    getAddressCode() {
      var lat = parseFloat(this.shopInfo.lat);
      var lng = parseFloat(this.shopInfo.lng);
      var latLng = new qq.maps.LatLng(lat, lng);
      //调用获取位置方法
      this.getAddCode.getAddress(latLng);
    },
  

  

猜你喜欢

转载自www.cnblogs.com/Glant/p/12092866.html
今日推荐