一安装
npm install vue-baidu-map --save
二 main.js
import BaiduMap from "vue-baidu-map";
Vue.use(BaiduMap, {
ak: "**你的key**",
});
三、我用的是element,安装的话,前面有。
Map.vue代码:
<template>
<div class="app-container">
<el-autocomplete
v-model.trim="mapLocation.address"
:fetch-suggestions="querySearch"
placeholder="请输入详细地址"
style="width: 100%"
:trigger-on-focus="false"
@select="handleSelect"
/>
<div style="margin: 5px">
<baidu-map
class="bm-view"
:center="mapCenter"
:zoom="mapZoom"
@click="paintPolyline"
:scroll-wheel-zoom="true"
ak="baidu-ak"
@ready="handlerBMap"
>
<bm-marker :position="mapCenter"> </bm-marker>
</baidu-map>
</div>
</div>
</template>
<script>
import BaiduMap from "vue-baidu-map/components/map/Map.vue";
export default {
name: "Map",
components: {
BaiduMap,
},
props: {
value: String,
longitude: Number,
latitude: Number,
lnglat: String,
},
data() {
return {
mapZoom: 17,
mapCenter: { lng: 117.233441, lat: 31.826885 },
mapLocation: {
address: "",
coordinate: "",
},
flag: false,
};
},
methods: {
async handlerBMap({ BMap, map }) {
this.BMap = BMap;
this.map = map;
if (this.mapLocation.coordinate && this.mapLocation.coordinate.lng) {
this.mapCenter.lng = this.longitude;
this.mapCenter.lat = this.latitude;
this.mapZoom = 17;
map.addOverlay(new this.BMap.Marker(this.mapLocation.coordinate));
} else {
this.mapCenter.lng = this.longitude || 117.233441;
this.mapCenter.lat = this.latitude || 31.826885;
this.mapZoom = 17;
}
},
querySearch(queryString, cb) {
var that = this;
var myGeo = new this.BMap.Geocoder();
myGeo.getPoint(
queryString,
function(point) {
if (point) {
that.mapLocation.coordinate = point;
that.makerCenter(point);
} else {
that.mapLocation.coordinate = null;
}
},
this.locationCity
);
var options = {
onSearchComplete: function(results) {
if (local.getStatus() === 0) {
// 判断状态是否正确
var s = [];
for (var i = 0; i < results.getCurrentNumPois(); i++) {
var x = results.getPoi(i);
var item = { value: x.address + x.title, point: x.point };
s.push(item);
cb(s);
}
} else {
cb();
}
},
};
var local = new this.BMap.LocalSearch(this.map, options);
local.search(queryString);
},
paintPolyline(item) {
var { point } = item;
this.flag = true;
this.makerCenter(point);
},
handleSelect(item) {
var { point } = item;
this.flag = false;
this.mapLocation.coordinate = point;
//console.log(point);
this.makerCenter(point);
},
makerCenter(point) {
if (this.map) {
this.map.clearOverlays();
this.map.addOverlay(new this.BMap.Marker(point));
this.mapCenter.lng = point.lng;
this.mapCenter.lat = point.lat;
this.mapZoom = 17;
if (this.lnglat == "coord") {
if (this.flag) {
this.$emit("longlat", { lng: point.lng, lat: point.lat });
}
} else {
this.$emit("longlat", { lng: point.lng, lat: point.lat });
}
}
},
},
};
</script>
index.vue代码
<Map @longlat="longlat"></Map>
methods: {
longlat(item) {
this.addForm.longitude = item.lng;
this.addForm.latitude = item.lat;
},
}
``