Bootstrap

Vue引入腾讯地图(搜索获取定位)

效果:

328f45f8a51d4907900cafd643f8a280.png

申请腾讯地图

1.首先进入腾讯位置服务登陆/注册,地址:https://lbs.qq.com/ 

2.进入控制台,点击左侧菜单应用管理—我的应用,点击右上方创建应用,填写内容如下

26879be73d88475887830e4d4801d4da.png

WebServiceAPI里根据自己的情况填写

 保存后显示刚刚的应用即可使用腾讯地图

开始使用腾讯地图

以Vue项目为例,在index.html文件中添加

<head>
    <!-- 引入腾讯地图api -->
    <script  src="https://map.qq.com/api/gljs?v=1.exp&key=腾讯地图key"></script>
  </head>

新建map.vue 腾讯地图组件

<template>
  <!-- <el-dialog
  :append-to-body="true"
    title="选择地址"
    :visible.sync="isShowDialog"
    width="1000px"
    top="50px"> -->
  <div>
    <!-- <div class="search">
      <el-input placeholder="请输入搜索地址信息" v-model="keyword" clearable>
        <el-button slot="append" icon="el-icon-search" @click="searchAddress"></el-button>
      </el-input>
    </div> -->
    <el-table
      v-if="isShowDialog"
      highlight-current-row
      :data="nearPointList"
      height="300"
      style="width: 100%"
      class="table"
    >
      <el-table-column prop="address" label="附近推荐地点">
        <template slot-scope="scope">
          {{ scope.row.address }}{{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="selectAddress(scope.row, 2)"
            type="text"
            >确认选择</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div id="mapContainer" style="width: 100%; height: 350px"></div>

    <div class="address">
      <!-- <span>当前选点:</span>
      <b>{{nowAddress ? (nowAddress.addressComponents.province + nowAddress.addressComponents.city + nowAddress.addressComponents.district + nowAddress.addressComponents.streetNumber) : '尚未选点'}}</b> -->
      <!-- <el-button v-if="nowAddress" @click="selectAddress(nowAddress, 1)" type="text">【确认选择】</el-button> -->
    </div>
  </div>

  <!-- 
  </el-dialog> -->
</template>
<script>
export default {
  data() {
    return {
      keyword: "", // 搜索关键词
      nearPointList: [], // 附近地址
      isShowDialog: false, // 是否显示弹窗
      markersArray: [],
      geocoder: null,
      nowAddress: null, // 选择的地点
      geocoderLocation: null,
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    // 搜索地址
    // searchAddress() {
    //   if (!this.keyword) {
    //     return this.$message.error("请输入搜索地址信息");
    //   }
    //   this.setLocationByAddress(this.keyword);
    // },

    // 初始化地图
    initMap() {
      let that = this;
      let latLon = new qq.maps.LatLng(39.916527, 116.397128);
      var map = new qq.maps.Map(document.getElementById("mapContainer"), {
        zoom: 13,
        center: latLon,
        mapTypeId: qq.maps.MapTypeId.ROADMAP,
      });
      var listener = qq.maps.event.addListener(map, "click", function (event) {
        that.setLocationByLatLng(event.latLng.getLat(), event.latLng.getLng());
      });
      // 经纬度解析类回调函数
      this.geocoder = new qq.maps.Geocoder({
        complete: function (result) {
          that.nowAddress = result.detail;
          that.nearPointList = result.detail.nearPois;
          map.setCenter(result.detail.location);
          // 标记点
          let marker = new qq.maps.Marker({
            map: map,
            position: result.detail.location,
          });
          that.markersArray.push(marker);
          if (that.markersArray.length > 1) {
            for (let i = 0; i < that.markersArray.length - 1; i++) {
              that.markersArray[i].setMap(null); // 清除标记
            }
          }
        },
      });
      // 地址解析回调函数
      that.geocoderLocation = new qq.maps.Geocoder({
        complete: function (result) {
          // 查找附近的点
          let latLng = new qq.maps.LatLng(
            result.detail.location.lat,
            result.detail.location.lng
          );
          that.geocoder.getAddress(latLng);
        },
      });
    },

    // 选择地址事件
    selectAddress(item, type) {
      let info = this.nowAddress.addressComponents;
      if (type === 1) {
        let addressInfo = item.addressComponents;
        this.$emit(
          "on-select",
          addressInfo.province +
            addressInfo.city +
            addressInfo.district +
            addressInfo.streetNumber,
          item.location.lat,
          item.location.lng,
          info.province,
          info.city,
          info.district
        );
        this.isShowDialog = false;
      }
      if (type === 2) {
        this.$emit(
          "on-select",
          item.address,
          item.latLng.lat,
          item.latLng.lng,
          info.province,
          info.city,
          info.district
        );
        this.isShowDialog = false;
      }
    },

    // 显示地图
    // show() {
    //   setTimeout(() => {
    //     // this.keyword = '';
    //     this.initMap();
    //   })
    // },

    // 根据地址信息进行定位
    setLocationByAddress(address) {
      setTimeout(() => {
        this.geocoderLocation.getLocation(address);
      });
    },

    // 根据经纬度进行定位
    setLocationByLatLng(lat, lng) {
      setTimeout(() => {
        this.isShowDialog = true;
        let latLng = new qq.maps.LatLng(lat, lng);
        this.geocoder.getAddress(latLng);
      });
    },
  },
};
</script>

<style scoped lang="scss">
.search {
  margin-bottom: 15px;
  margin-top: -20px;
}
.address {
  margin-top: 15px;
  margin-bottom: 10px;
  .el-button {
    padding: 0;
  }
}
.table {
  .el-button {
    padding: 0;
  }
}
</style>

页面引用

<el-form>
    <el-form-item
          label="详细地址"
          label-width="100px"
          prop="address1"
          clearable
        >
          
          <!-- 地图容器 -->
          <!-- <el-input
                    @change="handleSearch"
                    v-model="keyWord"
                    clearable
                    placeholder="请输入地址来直接查找相关位置"
                    style="width: 500px"
                  ></el-input>
          <div id="container"></div> -->
          <div style="width:90%;"> 
            <div class="xqk">
              <span>{{ info.address }}</span>
          </div>
            <el-input placeholder="请选择地址"  v-model="keyWord" @change="openMap()">
              <el-button slot="append" icon="el-icon-location" @click="openMap()"></el-button>
            </el-input>
            <TMap ref="ms" @on-select="selectAddress" />
          </div>
        </el-form-item>
</el-form>

页面js

// 打开地图弹窗
		openMap() {
      jsonp('https://apis.map.qq.com/ws/geocoder/v1/?address=', {
            output: 'jsonp',
            address: this.keyWord,
            key: '申请腾讯地图key'
        }).then(res => {
          console.log(res)
            if (res.status == 0) {
                // 通过地址得到经纬度
                // locations.value = `${res.result.location.lat},${res.result.location.lng}`
                // let center = new qq.maps.LatLng(res.result.location.lat, res.result.location.lng)
                // map.panTo(center)  // 重新设置地图中心点
                // initMap(res.result.location.lat, res.result.location.lng)
                
                this.$refs.ms.setLocationByLatLng(res.result.location.lat, res.result.location.lng);
            } else {
            this.$messages(res.message)
            }
        }).catch(err => {
            // search_btn.value = false
            console.log('地图错误:', err);
        })
			// 根据省市区设置初始值
			// this.$refs.ms.setLocationByAddress(this.mainForm.address);
			// 根据经纬度设置初始值

			// this.$refs.ms.setLocationByLatLng(this.mainForm.lat, this.mainForm.lng);
		},
		
		// 地址选择后的回调函数
		selectAddress(address, lat, lng, province, city, area) {
      this.info.lat = lat;
      this.info.lng = lng;
      this.info.province = province;
      this.info.city = city;
      this.info.area = area;
      this.info.address = address;
      this.keyWord = address;
			// this.mainForm.address = address;
			// this.mainForm.lat = lat;
			// this.mainForm.lng = lng;
		},
    

 

 

;