vue中使用腾讯API地图,实现搜索关键词获取经纬度和地址并显示地图

vue中使用腾讯API地图,实现搜索关键词获取经纬度和地址并显示地图

  1. 调用腾讯地图api前需要先去注册并申请key
  2. 在vue项目中的/public文件夹中的index.html的head中写入
  3. 安装lodash:npm install --save lodash
  4. 安装jsonp: npm install vue-jsonp --save
  5. main.js引入jsonp
import Vue from 'vue'
import { VueJsonp } from 'vue-jsonp'
Vue.use(VueJsonp)
Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

在public中的index.html文件中引入script标签加上链接

<script src="https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>

具体代码功能如下:

// template中
<template>
  <div id="app">
    <div class="box">
      <div class="search-box">
        <input type="text" v-model="searchValue" class="search" @input="searchHandler">
        <ul class="" v-if="kwData.length != 0">
          <li v-for="(kw, i) in kwData" :key="i" @click="clickLiHandler(kw)">{{kw.title}}</li>
        </ul>
      </div>
      <h3>地址:{{address}}</h3>
      <div class="location">
        <h3>经度:{{lng}}</h3>
        <h3>纬度:{{lat}}</h3>
      </div>
      <br />
      <div id='mapContainer'></div>
    </div>
  </div>
</template>

// script
<script>
// import { debounce } from 'throttle-debounce'
// 安装lodash:npm install lodash --save     安装jsonp: npm install vue-jsonp --save
import lodash from 'lodash'
let that

export default ({
  data() {
    return {
      addValue: '',
      longitude: '',
      latitude: '',
      searchValue: '',
      kwData: '',
      clickLi: true,
      lng: '',
      lat: '',
      address: '',

      markerUrl: require("./assets/logo.png"),  // 点标记图片路径
      map: '',
      zoom: 4,  // 地图一开始的缩放级别
      center: new window.TMap.LatLng(39.984120, 116.307484),  // 地图一开始的中心点
      markerLayer: '',
      geometries: []
    }
  },
  created() {
    that = this
  },
  mounted() {
    this.init1()
  },
  methods: {
    init1() {
      var drawContainer = document.getElementById('mapContainer');
      // var center = new window.TMap.LatLng(39.984104, 116.307503);//设置中心点坐标   lat: 23.228237   lng: 113.273747
      var center = new window.TMap.LatLng(23.228237, 113.273747);//设置中心点坐标   lat: 23.228237   lng: 113.273747
      this.map = new window.TMap.Map(drawContainer, {
        zoom: 9,
        pitch: 40,
        center: center,
        draggable: true,
        scrollable: true,
        mapStyleId: "style 1"
      });
      console.log('drawContainer', drawContainer)
      console.log(111, this.map)
      // 创建点聚合实例
      var markerCluster = new window.TMap.MarkerCluster({
        id: 'cluster',
        map: this.map,
        enableDefaultStyle: true, // 启用默认样式
        minimumClusterSize: 1, // 形成聚合簇的最小个数
        geometries: this.geometries,
        zoomOnClick: true, // 点击簇时放大至簇内点分离
        gridSize: 60, // 聚合算法的可聚合距离
        averageCenter: false, // 每个聚和簇的中心是否应该是聚类中所有标记的平均值
        maxZoom: 10 // 采用聚合策略的最大缩放级别
      })
      markerCluster
    },

    // 添加点标记
    addPoint(point) { // 一个point需要有id和坐标
        this.markerLayer.add([
            {
                'id': point['id'],
                'styleId': 'mystyle',
                "position": new window.TMap.LatLng(point['latitude'], point['longitude']),
                "properties":{} // 自定义属性,可以没有
            }
        ])
    },

    addrToGetCoordinate(event) {
      console.log('event', event)
      console.log(event.target.value)
      let addr = event.target.value
      this.$jsonp('https://apis.map.qq.com/ws/geocoder/v1/', {
        // key: 'ZBABZ-S5LKO-AQAWR-SNHUD-V3AQS-MSBMB',
        key: '6V3BZ-BZL6F-SAAJ6-JUS4K-ZCBNZ-6ZFGH',
        output: 'jsonp',
        address: addr
      })
    .then((res) => {
        console.log(res)
        if (res.status === 0) {
          // 处理得到的经纬度
          this.longitude = res.result.location.lng
          this.latitude = res.result.location.lat
          console.log('经度', this.longitude)
          console.log('纬度', this.latitude)

          // 用获取到的经纬度,修改地图的中心点
          // this.changeCenter(res.result.location.lat.toFixed(6), res.result.location.lng.toFixed(6))
        }
      })
      .catch((e) => {
          console.log(e)
        })
    },
    getKwd(event) {
      let kw = event.target.value
      console.log(111, kw)
      this.$jsonp('https://apis.map.qq.com/ws/place/v1/suggestion', {
        // key: 'ZBABZ-S5LKO-AQAWR-SNHUD-V3AQS-MSBMB',
        key: '6V3BZ-BZL6F-SAAJ6-JUS4K-ZCBNZ-6ZFGH',
        output: 'jsonp',
        keyword: kw,
        region: '广州市'
      })
        .then((res) => {
          console.log(res)
          if (res.status === 0) {
            console.log(res)
            this.kwData = res.data
            // 用获取到的经纬度,修改地图的中心点
            // this.changeCenter(res.result.location.lat.toFixed(6), res.result.location.lng.toFixed(6))
          } else {
            this.kwData = []
          }
        })
        .catch((e) => {
          console.log(e)
        })
    },
    searchHandler: lodash.debounce((event) => {
      console.log(222, this)
      console.log('event', event)
      that.getKwd(event)
    }, 500),
    clickLiHandler(kwObj) {  // 点击搜索关键词项
      // this.clickLi = false
      this.searchValue = kwObj.title
      this.lng = kwObj.location.lng
      this.lat = kwObj.location.lat
      this.address = kwObj.address
      this.geometries = [
        { // 点数组
          position: new window.TMap.LatLng(this.lat, this.lng)
        }]
      this.init1()
      console.log(this.lat, this.lng)
      this.kwData = []
    }
  }
})
</script>


<style lang="less">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;

  .search {
    margin-top: 20px;
  }

  .box {
    margin: 0 auto;
    width: 1080px;
    margin-top: 80px;

    input {
      outline: none;
      width: 300px;
      height: 30px;
      border: 1px solid #ccc;
      padding: 10px;
      background-color: white;
      box-sizing: border-box;

    }

    .search-box {
      position: relative;

      ul {
          // border: 1px solid #ccc;
          // box-shadow: 1px, 1px, 1px, 1px, #ccc;
          box-shadow: 0px 5px 15px rgba(165, 165, 165, 0.438);
          width: 300px;
          position: absolute;
          left: 389px;
          bottom: -293px;
          box-sizing: border-box;
          padding: 10px;
          font-size: 12px;
          z-index: 100;
          background-color: white;

          li {
            list-style: none;
            padding: 5px;
            text-align: left;
            
            &:hover {
              background-color: #7ad9ff;
              cursor: pointer;
            }
          }
        }
    }

    .location {
      display: flex;
      text-align: center;
      justify-content: center;

      h2 {
        width: 200px;

        &::nth-child(1) {
          margin-right: 20px;
        }
      }
    }

  }

  .map {
    width: 700px;
    height: 700px;
  }

  #mapContainer {
    width: 600px;
    height: 600px;
    margin: 0 auto;
  }

}

#nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
</style>

效果图
在这里插入图片描述
在这里插入图片描述

查考:https://blog.csdn.net/l13620804253/article/details/117259244

<think>好的,我现在需要在Vue项目中集成腾讯地图的功能。用户的问题是如何在Vue使用腾讯地图API或组件。我需要根据提供的引用内容来整理步骤,同时确保回答结构清晰,符合用户的要求。 首先,我应该回顾提供的引用内容。引用[1]提到在index.html中引入腾讯地图的脚本,封装成组件。引用[2]展示了使用异步加载初始化地图的示例。引用[3]提到WebService API使用需要Key,引用[4]则演示了如何调用逆地址解析接口。 接下来,我需要分步骤说明如何在Vue使用腾讯地图。可能包括以下几个步骤:申请Key、引入SDK、组件封装、初始化地图、调用WebService API,以及可能的优化方法如异步加载或签名验证。 需要注意的是,用户可能希望在Vue组件中正确加载地图,避免全局污染,所以动态加载组件封装是关键。异步加载可以提升性能,这在引用[2]中提到了使用lazyTMapApiLoaderInstance。同时,WebService API使用需要发送请求,可能涉及JSONP,如引用[4]中的示例。 需要确保每个步骤都清晰,代码示例正确,且引用对应的引用标记。比如,引入脚本的部分对应引用[1],异步加载对应引用[2],申请Key对应引用[3],调用API对应引用[4]。 另外,用户可能关心如何封装组件,避免重复加载脚本,所以需要提到将初始化逻辑封装到单独的工具文件中,如TMapInit.js,如引用[2]所示。 最后,生成相关问题需要考虑用户可能遇到的后续问题,比如优化加载、处理错误、签名验证等,这些都是合理的相关问题。</think>### 在 Vue使用腾讯地图 API 的步骤 #### 1. **申请开发者密钥(Key)** - 前往腾讯地图[开放平台](https://lbs.qq.com/)注册账号,创建应用获取 `key`[^3]。 - `key` 是调用 API 的必备参数,需在请求中传递。 #### 2. **引入地图 SDK** - **全局引入**(适用于简单场景): 在 `index.html` 中直接添加脚本标签: ```html <script src="https://map.qq.com/api/js?v=2.exp&key=YOUR_KEY"></script> ``` 注意替换 `YOUR_KEY`,此方法可能导致全局变量污染[^1]。 - **动态异步加载**(推荐): 封装独立的工具文件(如 `TMapInit.js`),实现按需加载: ```javascript // TMapInit.js export const lazyTMapApiLoaderInstance = new Promise((resolve) => { if (window.TMap) resolve(true); else { const script = document.createElement('script'); script.src = `https://map.qq.com/api/js?v=2.exp&key=YOUR_KEY`; script.onload = resolve; document.head.appendChild(script); } }); ``` 使用时通过 `lazyTMapApiLoaderInstance.then()` 确保脚本加载完成[^2]。 #### 3. **封装地图组件** - 创建 Vue 组件(如 `MyMap.vue`): ```html <template> <div id="myMap" :style="{ width: '100%', height: '500px' }"></div> </template> <script> import { lazyTMapApiLoaderInstance } from './util/TMapInit'; export default { mounted() { lazyTMapApiLoaderInstance.then(() => { new TMap.Map('myMap', { center: new TMap.LatLng(39.909, 116.397), // 初始中心坐标 zoom: 11 // 缩放级别 }); }); } }; </script> ``` 通过 `id="myMap"` 的 `div` 作为地图容器。 #### 4. **调用 WebService API** - 以逆地址解析(坐标转地址)为例: ```javascript // api.js export const getAddressByLat = (params) => { return request.jsonp('https://apis.map.qq.com/ws/geocoder/v1/', { key: 'YOUR_KEY', output: 'jsonp', ...params }); }; ``` 在 Vue 组件中调用: ```javascript import { getAddressByLat } from '@/api'; export default { methods: { async fetchAddress(lat, lng) { const res = await getAddressByLat({ location: `${lat},${lng}` }); console.log(res.address); } } }; ``` 需处理 JSONP 跨域问题[^4]。 #### 5. **签名验证(可选)** - 若需提升安全性,可在请求中增加 `sig` 参数: ```javascript import md5 from 'crypto-js/md5'; const sig = md5(`/ws/geocoder/v1?key=YOUR_KEY&location=${lat},${lng}${SECRET_KEY}`).toString(); ``` 将 `sig` 加入请求参数。 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值