基于jeecgboot前端框架制作。
.env文件中加入变量定义:
VUE_APP_MAP_KEY= 你的key
项目中config文件夹中的index.js中增加一个变量,引用这个key
//腾讯地图key
window._CONFIG['qqMapKey'] = process.env.VUE_APP_MAP_KEY
index.html中增加腾讯地图的js文件引用
<script src="https://map.qq.com/api/gljs?v=1.exp&key=<%= VUE_APP_MAP_KEY %>"></script>
地图组件:
<template>
<j-modal
:title="title"
:width="width"
:visible="visible"
switchFullscreen
@ok="handleOk"
@cancel="handleCancel"
cancelText="关闭">
<div id="container"></div>
</j-modal>
</template>
<script>
export default {
name: "TencentMap",
props: {
coordinate: {
type: Object,
default: () => {
return {
lat: '',
lng: ''
}
}
}
},
data() {
return {
title: '设置地点',
width: 1000,
visible: false,
markerLayer: {},
markerId: 'marker',
location: this.coordinate
}
},
methods: {
getMyLocation() {
const KEY = window._CONFIG['qqMapKey']
let url = 'https://apis.map.qq.com/ws/location/v1/ip'
this.$jsonp(url, {
key: KEY,
output: 'jsonp'
}).then(json => {
this.location.lat = json.result.location.lat;
this.location.lng = json.result.location.lng;
this.initMap()
}).catch(error => {
this.$message.error('定位失败')
})
},
initMap() {
let center = new TMap.LatLng(this.location.lat, this.location.lng)
let map = new TMap.Map(document.getElementById('container'), {
center: center,
zoom: 17.2, //设置地图缩放级别
pitch: 0, //设置俯仰角
rotation: 0 //设置地图旋转角度
});
this.markerLayer = new TMap.MultiMarker({
id: 'marker-layer',
map: map,
})
map.on('click', (evt) => {
this.location.lat = evt.latLng.lat
this.location.lng = evt.latLng.lng
this.markerLayer.remove(this.markerId) //移除旧的标记
this.markerLayer.add({
id: this.markerId,
position: new TMap.LatLng(this.location.lat, this.location.lng)
})
})
if (this.location.lat) {
this.markerLayer.add({
id: this.markerId,
position: new TMap.LatLng(this.location.lat, this.location.lng)
})
}
},
handleCancel() {
this.visible = false
},
handleOk() {
this.$emit('onSel', this.location)
this.visible = false
},
open(location) {
if (location && JSON.stringify(location) != "{}") {
this.location = location
}
this.visible = true
this.$nextTick(() => {
if (!this.location.lat) {
this.getMyLocation()
} else {
this.initMap()
}
})
}
}
}
</script>
<style scoped>
</style>
使用:
<tencent-map ref="map" @onSel="selLocation"></tencent-map>
import TencentMap from "@comp/map/TencentMap";
components: {
TencentMap
},
this.$refs.map.open() //打开窗口,未传入坐标,将使用ip进行定位,并在地图上标记,ip定位并不准确,不过距离实际的位置不会太远,都在一个城市内
this.$refs.map.open({lat:35.21406841039809 ,lng:113.2474249152092}) //打开窗口,传入坐标,将在这个坐标上标记
selLocation(location){
console.log(location)
}