参考链接
https://blog.csdn.net/weixin_30552635/article/details/95095724
介绍
在vue项目中使用腾讯地图,我这里使用了gl版本,它呈现的效果更好,与老的2d版本相比它们的API大致相同。
使用方法,ctrl c + ctrl v。
使用效果
组件代码
<!-- 腾讯地图pcweb -xwjs -->
<template><div><div class="search-con"><el-input size="mini" v-model="CURR_ADR"></el-input><el-button @click="search" style="margin-left:20px" type="primary" size="mini">查询</el-button></div><div :id="elId" class="tmap"></div></div>
</template>
<script>
export default {props: {elId: {type: String,require: true,},},data() {return {CURR_MAP: [null, null], //当前坐标CURR_ADR: null, //当前地址KEY: "NJKBZ-FS2CS-6C6O4-6WWYM-4NQ63-MJBNO",APP_NAME: "像铸",map: null, //地图对象Maker: null, //标记(单个)}},mounted() {this.initMap()},beforeDestroy() {// this.map.off("click")},methods: {createScript() {return new Promise((resolveOut) => {const scripts = document.getElementsByTagName("script")const addScripts = Array.from(scripts)// 防止重复创建scriptconst findxzmap = addScripts.find((el) => el.id == "xzmap")const findxzgeo = addScripts.find((el) => el.id == "xzgeo")const findjq = addScripts.find((el) => el.id == "jquery")const promistList = []if (!findjq) {const p1 = new Promise((resolve) => {const sc = document.createElement("script")sc.src = `https://code.jquery.com/jquery-2.2.4.js`sc.setAttribute("id", "jquery")sc.type = "text/javascript"document.body.appendChild(sc)sc.onload = () => {resolve()}})promistList.push(p1)}// tmapglif (!findxzmap) {const p2 = new Promise((resolve) => {const sc = document.createElement("script")sc.src = `https://map.qq.com/api/gljs?v=1.exp&key=${this.KEY}`sc.setAttribute("id", "xzmap")sc.type = "text/javascript"document.body.appendChild(sc)sc.onload = () => {resolve()}})promistList.push(p2)}// 精准定位apiif (!findxzgeo) {const p3 = new Promise((resolve) => {const scgeo = document.createElement("script")scgeo.src ="https://mapapi.qq.com/web/mapComponents/geoLocation/v/geolocation.min.js"scgeo.setAttribute("id", "xzgeo")scgeo.type = "text/javascript"document.body.appendChild(scgeo)scgeo.onload = () => {resolve()}})promistList.push(p3)}Promise.all(promistList).then(() => {const { TMap, qq } = windowresolveOut({ TMap, qq })})})},async initMap() {const { TMap, qq } = await this.createScript()this.TMap = TMapthis.qq = qqconst geolocation = new this.qq.maps.Geolocation(this.KEY, this.APP_NAME)geolocation.getLocation((val) => {const { lat, lng } = valthis.CURR_MAP = [lat, lng]this.init()})},AddMark() {const center = new this.TMap.LatLng(this.CURR_MAP[0], this.CURR_MAP[1])if (this.Maker) {this.Maker.setMap(null)}this.Maker = new this.TMap.MultiMarker({id: "a-marker",map: this.map,geometries: [{position: center,},],})},RefMap() {const center = new this.TMap.LatLng(this.CURR_MAP[0], this.CURR_MAP[1])this.map.panTo(center)},search() {if (!this.CURR_ADR) {this.$message.warning('查询数据不能为空')return}this.getAddr('search')},getAddr(type) {const url = "http://apis.map.qq.com/ws/geocoder/v1/"const data = {address: type === 'search' ? this.CURR_ADR : undefined,location: type === 'search' ? undefined : this.CURR_MAP[0] + "," + this.CURR_MAP[1],get_poi: type === 'search' ? undefined : 0,key: this.KEY,output: 'jsonp'}$.ajax({type: "get",dataType: "jsonp",data: data,jsonp: "callback",jsonpCallback: "QQmap",url: url,success: (res) => {// console.log(res)if (res && res.status == 0 && res.result.location) {// 正向搜索let adddr = ''if (res.request_id) {adddr = `${res.result.address_component.province}${res.result.address_component.city}${res.result.formatted_addresses.recommend}`this.CURR_ADR = adddr} this.CURR_MAP = [res.result.location.lat, res.result.location.lng]this.$emit('mapSearch', { addr: adddr, latLng: this.CURR_MAP})//刷新坐标轴this.RefMap()//刷新makerthis.AddMark()} else {this.$message.warning('没有搜索到')}},error: () => {this.$message.error('服务错误,请刷新浏览器后重试')},})},init() {//定义map变量this.map = new this.TMap.Map(document.getElementById(this.elId), {center: new this.TMap.LatLng(this.CURR_MAP[0], this.CURR_MAP[1]),zoom: 10,})this.getAddr()//添加监听事件this.map.on("click", (e) => {this.CURR_MAP = [e.latLng.getLat().toFixed(5),e.latLng.getLng().toFixed(5),]this.getAddr()})},},
}</script>
<style lang="scss" scoped>
.search-con {display: flex;align-items: center;
}
.tmap {margin: 20px 0;border: 1px solid #ddd;
}
</style>
父组件调用
<qqMap elId="addr" @mapSearch="mapSearch"/>