百度地图JavaScript API GL常用方法封装
引入百度js库
<script type="text/javascript" src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=自己的百度应用ak"></script>
封装方法
<template>
<div class="map">
<div id="container" class="container"></div>
</div>
</template>
<script>
export default {
data() {
return {
map:null,
}
},
props: {
position: {
type: Object,
default: () => {
return { lng: 116.40334547586404, lat: 39.92386800168819 };
}
},
firingLngLat:{
type:Boolean,
default:false
}
},
mounted(){
this.init()
},
methods:{
init(){
this.map = new BMapGL.Map('container');
this.map.enableScrollWheelZoom();
var point = new BMapGL.Point(this.position.lng,this.position.lat);
this.map.centerAndZoom(point, 10);
if(this.firingLngLat){
this.getLngLat()
}
},
getMap(items){
let data = items
this.charMap()
if(data.length){
items.forEach((item,idnex) => {
var point = new BMapGL.Point(item.longitude,item.latitude);
this.map.centerAndZoom(point, 15);
let img = require("@/assets/images/yard.png")
var myIcon = new BMapGL.Icon(img, new BMapGL.Size(56, 56), {
imageOffset: new BMapGL.Size(0, 0 )
});
var marker = new BMapGL.Marker(point, {icon: myIcon});
this.map.addOverlay(marker);
var optsName = {
position: new BMapGL.Point(item.longitude ,item.latitude),
offset: new BMapGL.Size(-40, -50)
};
var label = new BMapGL.Label(item.name , optsName);
label.setStyle({
color: 'blue',
borderColor: '#ccc',
fontSize: '16px',
height: '30px',
lineHeight: '30px',
fontFamily: '微软雅黑'
});
this.map.addOverlay(label);
marker.addEventListener("click", ()=>{
this.$emit('click',item)
})
});
}
},
charMap(){
var allOverlay = this.map.getOverlays();
for(var i = 0;i<allOverlay.length;i++) {
if(allOverlay[i].toString()){
this.map.removeOverlay(allOverlay[i]);
}
}
},
getLngLat(){
this.charMap()
this.map.addEventListener('click', (e)=> {
let mapll = {
lng:e.latlng.lng,
lat:e.latlng.lat
}
this.$emit("change",mapll)
let data =[{
name:"标记点位置",
longitude:e.latlng.lng,
latitude:e.latlng.lat
}]
this.getMap(data)
})
},
}
}
</script>
<style lang="stylus" scoped>
.map
width 100%
height 100%
border: 1px solid #cccccc99
.container
width 100%
height 100%
</style>
使用方式
<my-map :position="position" @click="myMapClick" @change="getPostion" :firingLngLat="true" ref="maps" ></my-map>
import myMap from "@/components/map/maps";
components: { myMap},
position:{
lng:0,
lat:0,
},
myMapClick(item){},
getPostion(item){},
this.$refs.maps.getMap([{longitude:经度,latitude:维度,name:标记名}]),