<template>
<div id="map" class="page-flex">
<div id="container"></div>
</div>
</template>
mounted: function () {
this.$nextTick(() => {
var map = new BMap.Map("container"); //初始化map, 绑定id=allmap
// var point = new BMap.Point(121.445, 31.213); // 初始化point, 给定一个默认x,y值
var point = new BMap.Point(123.465009, 41.300287); // 初始化point, 给定一个默认x,y值
map.centerAndZoom(point, 9); // 将point点放入map中,展示在页面中心展示,10=缩放程度
map.enableScrollWheelZoom(true); // 开启滚动鼠标滑轮
// 获取缩放的比例
// map.addEventListener("zoomend",function(e){
// var zoomNum = map.getZoom()
// console.log(zoomNum)
// })
// 如有多个point去展示,可根据后端接口传入为主
let data = this.city
data.forEach((e, i) => {
// 创建point, 将x,y值传入
let pointNumber = new BMap.Point(e.x, e.y);
// let pointNumber = new BMap.Point(e.latitude, e.longitude);
// 将data中的name加入地图中
var label = new BMap.Label(e.name);
// var label = new BMap.Label(e.city);
label.setStyle({
display:'flex',
// alignItem:'center',
flexDirection:'column',
justifyContent: 'center',
color: "#fff", //字体颜色
width:'1.2rem',
height:'1.2rem',
fontSize: ".24rem", //字体大小
backgroundColor: "#FEC700", //文本标注背景颜色
borderRadius: "1rem",
border: "1px solid #fff",
textAlign: "center",
lineHeight:'.24rem',
});
// markerFun(pointNumber, label);
// let markers = new BMap.Marker(points);
var myIcon = new BMap.Icon(
"http://api.map.baidu.com/img/markers.png",
new BMap.Size(1, 1)
);
var initMarkers = new BMap.Marker(pointNumber, { icon: myIcon });
map.addOverlay(initMarkers); // 将标注添加到地图中
initMarkers.setLabel(label); // 将data中的name添加到地图中
});
map.addEventListener("zoomend", function (e) {
// 判断缩放比例
var zoomNum = map.getZoom();
//清除页面中所有覆盖物
function Clear(){
map.clearOverlays();//清除图层覆盖物
}
if (zoomNum == 10) {
// 先清除所有覆盖物
Clear()
let data = [
{ x: 121.48, y: 31.23, name: "黄浦区
118面屏" },
{ x: 121.33, y: 31.58, name: "徐汇区
118面屏" },
{ x: 121.75, y: 31.23, name: "静安区
118面屏" },
{ x: 121.5, y: 31.27, name: "虹口区
118面屏" },
{ x: 121.4, y: 31.05, name: "普陀区
118面屏" },
{ x: 121.28, y: 31.4, name: "宝山区
118面屏" },
{ x: 121.18, y: 31.12, name: "闵行区
118面屏" },
];
data.forEach((e, i) => {
// 创建point, 将x,y值传入
let pointNumber = new BMap.Point(e.x, e.y);
// 将data中的name加入地图中
var label = new BMap.Label(e.name);
label.setStyle({
display:'flex',
// alignItem:'center',
flexDirection:'column',
justifyContent: 'center',
color: "#fff", //字体颜色
width:'1rem',
height:'1rem',
fontSize: ".2rem", //字体大小
backgroundColor: "#FEC700", //文本标注背景颜色
borderRadius: "1rem",
border: "1px solid #fff",
textAlign: "center",
lineHeight:'.2rem',
});
// markerFun(pointNumber, label);
// let markers = new BMap.Marker(points);
var myIcon = new BMap.Icon(
"http://api.map.baidu.com/img/markers.png",
new BMap.Size(1, 1)
);
var markers10 = new BMap.Marker(pointNumber, {
icon: myIcon,
});
map.addOverlay(markers10); // 将标注添加到地图中
markers10.setLabel(label); // 将data中的name添加到地图中
});
}
if (zoomNum == 11) {
// 先清除所有覆盖物
Clear()
// console.log(1);
// this.zoomRatio = zoomNum;
// console.log(this.zoomRatio);
// map.removeOverlay(markers);
// map.openInfoWindow( points);//参数:窗口、点 根据点击的点出现对应的窗口
map.centerAndZoom(point, 11);
let ptdata = [
{ x: 121.5, y: 31.2456, name: "普陀一区
102面屏" },
{ x: 121.4, y: 31.26, name: "普陀二区
103面屏" },
{ x: 121.6, y: 31.2645, name: "普陀三区
120面屏" },
{ x: 121.43, y: 31.18, name: "徐汇一区
120面屏" },
{ x: 121.43, y: 31.29, name: "徐汇二区
120面屏" },
];
ptdata.forEach((e, i) => {
// 创建point, 将x,y值传入
let ptpointNumber = new BMap.Point(e.x, e.y);
// 将data中的name加入地图中
var ptlabel = new BMap.Label(e.name);
ptlabel.setStyle({
display:'flex',
// alignItem:'center',
flexDirection:'column',
justifyContent: 'center',
color: "#fff", //字体颜色
width:'1rem',
height:'1rem',
fontSize: ".2rem", //字体大小
backgroundColor: "#FEC700", //文本标注背景颜色
borderRadius: "1rem",
border: "1px solid #fff",
textAlign: "center",
lineHeight:'.2rem',
});
// ptmarkerFun(ptpointNumber, ptlabel);
var myIcon = new BMap.Icon(
"http://api.map.baidu.com/img/markers.png",
new BMap.Size(1, 1)
);
var markers11 = new BMap.Marker(ptpointNumber, {
icon: myIcon,
});
map.addOverlay(markers11); // 将标注添加到地图中
markers11.setLabel(ptlabel); // 将data中的name添加到地图中
});
}
if (zoomNum == 12) {
// 先清除所有覆盖物
Clear()
// console.log(2);
// this.zoomRatio = zoomNum;
// console.log(this.zoomRatio);
// map.removeOverlay(markers);
// map.openInfoWindow( points);//参数:窗口、点 根据点击的点出现对应的窗口
map.centerAndZoom(point, 12);
let ptdata = [
{ x: 121.45, y: 31.2056, name: "一区
102面屏" },
{ x: 121.5, y: 31.37, name: "二区
103面屏" },
{ x: 121.55, y: 31.2745, name: "三区
120面屏" },
{ x: 121.40, y: 31.28, name: "一区
120面屏" },
{ x: 121.40, y: 31.39, name: "二区
120面屏" },
];
ptdata.forEach((e, i) => {
// 创建point, 将x,y值传入
let ptpointNumber = new BMap.Point(e.x, e.y);
// 将data中的name加入地图中
var ptlabel = new BMap.Label(e.name);
ptlabel.setStyle({
display:'flex',
// alignItem:'center',
flexDirection:'column',
justifyContent: 'center',
color: "#fff", //字体颜色
width:'1rem',
height:'1rem',
fontSize: ".2rem", //字体大小
backgroundColor: "#FEC700", //文本标注背景颜色
borderRadius: "1rem",
border: "1px solid #fff",
textAlign: "center",
lineHeight:'.2rem',
});
// ptmarkerFun(ptpointNumber, ptlabel);
var myIcon = new BMap.Icon(
"http://api.map.baidu.com/img/markers.png",
new BMap.Size(1, 1)
);
var markers13 = new BMap.Marker(ptpointNumber, {
icon: myIcon,
});
map.addOverlay(markers13); // 将标注添加到地图中
markers13.setLabel(ptlabel); // 将data中的name添加到地图中
});
}
});
});
},
去除百度地图的logo
/* 去除百度地图的logo */
.BMap_cpyCtrl {
display: none;
}
.anchorBL {
display: none;
}
<template>
<div id="map" class="page-flex">
<div id="container"></div>
</div>
</template>
<script>
export default {
name: "allmap",
data() {
return {
city: [
{ x: 123.465009, y: 41.677287, name: "沈阳市
120面屏" },
{ x: 121.618622, y: 38.91459, name: "大连市
118面屏" },
{ x: 122.995632, y: 41.110626, name: "鞍山市
118面屏" },
{ x: 123.921109, y: 41.875956, name: "抚顺市
118面屏" },
{ x: 123.770519, y: 41.297909, name: "本溪市
200面屏" },
{ x: 124.383044, y: 40.124296, name: "丹东市
118面屏" },
{ x: 123.844279, y: 42.290585, name: "铁岭市
118面屏" },
],
};
},
props:['mapData'],
mounted() {
this.init();
},
methods: {
init() {
var marker,map = new AMap.Map("container", {
resizeEnable: true,
center: [123.465009,41.677287],
zoom: 8,
});
let data = this.city;
data.forEach((e, i) => {
// 实例化点标记
// function addMarker() {
marker = new AMap.Marker({
icon:"https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
position: [e.x,e.y],
offset: new AMap.Pixel(5, 5),
});
marker.setMap(map);
// }
// function updateIcon() {
// marker.setIcon(
// "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png"
// );
// }
// 自定义点标记内容
var markerContent = document.createElement("div");
markerContent.className = "marker-wrapper"
// // 点标记中的图标
// var markerImg = document.createElement("img");
// markerImg.className = "markerlnglat";
// markerImg.src ="https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png";
// markerContent.appendChild(markerImg);
// 点标记中的文本
var markerSpan = document.createElement("span");
markerSpan.className = "marker";
markerSpan.innerHTML = e.name ;
markerContent.appendChild(markerSpan);
marker.setContent(markerContent); //更新点标记内容
// marker.setPosition([e.x,e.y]); //更新点标记位置
});
// 清除 marker
function clearMarker() {
if (marker) {
marker.setMap(null);
marker = null;
}
}
},
},
// computed: {
// resultData(){
// return this.mapData.map(item=>{
// // this.$set(text)
// })
// }
// },
};
</script>
<style>
#map {
/* font-family: "Avenir", Helvetica, Arial, sans-serif; */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
#container {
/* height:12rem; */
flex: 1;
}
.marker-wrapper{
height: 50px;
width: 50px;
border-radius: 50%;
background: #FEC700;
font-size: 12px;
text-align: center;
line-height: 20px;
}
.marker{
color: #fff;
font-size: 12px;
}
</style>
删除某个marker
var singleMarker; //全局定义marker
map.remove(singleMarker); //删除自己定义的marker
删除地图上所有的marker
map.clearMap();
去掉高德的logo和版本号
/* 去掉高德的logo和版本号 */
.amap-logo{
display: none;
}
.amap-copyright {
opacity:0;
}
我是直接在index.html直接引用的,其他方法可自行百度
遇到的问题:
1、注意地图需要设置高度,不然显示不出来;
2、地图是根据dom节点,所以要在vue生命钩子函数mounted中写;
3、webpack配置高德api(但是webpack中没有配置却可以使用,有点意外)
externals: { AMap: "AMap" }, //或者BMap
module.exports = {
configureWebpack: {
externals: { AMap: "AMap" }
}
};
// 获取当前位置
getLocation() {
const _this = this;
_this.$toast("正在定位中...")
AMap.plugin('AMap.Geolocation', function () {
var geolocation = new AMap.Geolocation({
// 是否使用高精度定位,默认:true
enableHighAccuracy: true,
// 设置定位超时时间,默认:无穷大
timeout: 10000
});
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete);
AMap.event.addListener(geolocation, 'error', onError);
function onComplete (value) {
// value是具体的定位信息
console.log('定位成功信息:', value.addressComponent.province);
console.log('定位成功信息:', value.addressComponent.city);
console.log('定位成功信息:', value.addressComponent.district);
_this.address = value.addressComponent.city;
_this.locationProvince = value.addressComponent.province
_this.locationCity = value.addressComponent.city
_this.locationCountry = value.addressComponent.district
// 取消弹框 传递数据
let data = {
flag:false,
prov:_this.locationProvince,
city: _this.locationCity,
country:_this.locationCountry,
provID:'',
cityID: '',
countryID:''
}
_this.$emit("cancelPopup", data);
}
function onError (value) {
// 定位出错
console.log('定位失败错误:', value);
// 调用IP定位
// _this.getLngLatLocation();
_this.errFlag = true
_this.errorLocation = "定位失败,请手动选择地址"
}
});
},
// 通过IP获取当前位置
getLngLatLocation () {
AMap.plugin('AMap.CitySearch', function () {
var citySearch = new AMap.CitySearch();
citySearch.getLocalCity(function (status, result) {
if (status === 'complete' && result.info === 'OK') {
// 查询成功,result即为当前所在城市信息
console.log('通过ip获取当前城市:', result);
// 逆向地理编码
AMap.plugin('AMap.Geocoder', function () {
var geocoder = new AMap.Geocoder({
// city 指定进行编码查询的城市,支持传入城市名、adcode 和 citycode
city: result.adcode
});
var lnglat = result.rectangle.split(';')[0].split(',');
geocoder.getAddress(lnglat, function (status, data) {
if (status === 'complete' && data.info === 'OK') {
// result为对应的地理位置详细信息
console.log(data);
}
});
});
}
});
});
},
// 点击获取定位
getAddress(){
this.errFlag = false
this.getLocation();
}
<template>
<div id="map">
<div id="container"></div>
</div>
</template>
<script>
export default {
name: "allmap",
props: {
mapData: {
type: Array,
default() {
return [];
},
},
},
computed: {
// 用户定位的经纬度
userLocation(){
return this.$store.state.userLocation
},
mapCityList() {
this.mapCityData = []
// 取出地区的多少面屏的数据量
return this.mapData.reduce((obj, item) => {
let find = obj.find((i) => i.cityName === item.cityName);
let _d = {
...item,
screenNum: 1,
};
find ? find.screenNum++ : obj.push(_d);
return obj;
// }, []);
}, this.mapCityData);
},
mapAreaList() {
this.mapAreaData = []
// 取出地区的多少面屏的数据量
return this.mapData.reduce((obj, item) => {
let find = obj.find((i) => i.districtName === item.districtName);
let _d = {
...item,
screenNum: 1,
};
find ? find.screenNum++ : obj.push(_d);
return obj;
// }, []);
}, this.mapAreaData);
},
mapSiteNameList() {
this.mapSiteNameData = []
// 取出地区的多少面屏的数据量
return this.mapData.reduce((obj, item) => {
let find = obj.find((i) => i.siteName === item.siteName);
let _d = {
...item,
screenNum: 1,
};
find ? find.screenNum++ : obj.push(_d);
return obj;
// }, []);
}, this.mapSiteNameData);
},
},
data() {
return {
map:null,
markers:[],
mapCityData:[],
mapAreaData:[],
mapSiteNameData:[],
zoomNum:8,
// city: [
// { longitude: 123.465009, latitude: 41.677287, name: "沈阳市", num: "120" },
// { longitude: 121.618622, latitude: 38.91459, name: "大连市", num: "118" },
// { longitude: 122.995632, latitude: 41.110626, name: "鞍山市", num: "118" },
// { longitude: 123.921109, latitude: 41.875956, name: "抚顺市", num: "118" },
// { longitude: 123.770519, latitude: 41.297909, name: "本溪市", num: "200" },
// { longitude: 124.383044, latitude: 40.124296, name: "丹东市", num: "118" },
// { longitude: 123.844279, latitude: 42.290585, name: "铁岭市", num: "118" },
// ],
// city2: [
// { longitude: 123.465009, latitude: 41.677287, name: "沈阳市1", num: "120" },
// { longitude: 121.618622, latitude: 38.91459, name: "大连市1", num: "118" },
// { longitude: 122.995632, latitude: 41.110626, name: "鞍山市1", num: "118" },
// { longitude: 123.921109, latitude: 41.875956, name: "抚顺市1", num: "118" },
// { longitude: 123.770519, latitude: 41.297909, name: "本溪市1", num: "200" },
// { longitude: 124.383044, latitude: 40.124296, name: "丹东市1", num: "118" },
// { longitude: 123.844279, latitude: 42.290585, name: "铁岭市1", num: "118" },
// ],
// city3: [
// { longitude: 123.465009, latitude: 41.677287, name: "沈阳市2", num: "1200" },
// ],
};
},
mounted() {
const _this = this;
_this.initMap()
_this.markersList(_this.mapCityData, '0')
_this.mapZoom()
},
methods: {
initMap() {
const _this = this
console.log(_this.userLocation)
console.log("true", (Object.keys(_this.userLocation)).length)
console.log( _this.mapCityList)
console.log("true2", _this.mapCityList.length)
var centerLongitude;
var centerLatitude;
if (_this.mapCityList.length > 0) {
console.log(_this.mapCityList);
centerLongitude = _this.mapCityList[0].longitude;
centerLatitude = _this.mapCityList[0].latitude;
console.log("经纬度=",centerLongitude, centerLatitude)
} else if((Object.keys(_this.userLocation)).length !== 0 && _this.mapCityList.length == 0){
// 有定位时默认定位的
console.log("默认中心定位")
centerLongitude = _this.userLocation.longitude
centerLatitude = _this.userLocation.latitude
} else {
//否则默认沈阳市
centerLongitude = '113.264385';
centerLatitude = '23.129112';
console.log("经纬度111")
}
_this.map = new AMap.Map("container", {
resizeEnable: true,
center: [centerLongitude, centerLatitude],
// 沈阳市
// center: [123.465009,41.677287],
// 广州市
// center: [113.264385,23.129112],
zoom: 8,
});
},
markersList(data, type){
const _this = this
// 打点前 清除 所有的marker
function clearMarker() {
_this.map.clearMap();
}
clearMarker();
var marker;
// console.log(data);
data.forEach((item, i) => {
// 实例化点标记
marker = new AMap.Marker({
position: [item.longitude, item.latitude],
// offset: new AMap.Pixel(2, 2),
// icon:"https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
});
// 添加点标记到地图实例
marker.setMap(_this.map);
// 自定义点标记内容
var markerContent = document.createElement("div");
markerContent.className = "marker-wrapper";
// 点标记中的城市文本
var markerSpan = document.createElement("span");
markerSpan.className = "marker";
// markerSpan.innerHTML = type == 0 ? item.cityName : item.districtName;
console.log(type)
switch (type) {
case '0':
markerSpan.innerHTML = item.cityName
break;
case '1':
markerSpan.innerHTML = item.districtName
break;
case '2':
markerSpan.innerHTML = item.siteName
break;
default:
markerSpan.innerHTML = ''
}
markerContent.appendChild(markerSpan);
// 点标记中的屏幕数量文本
var markerSpan = document.createElement("span");
markerSpan.className = "marker";
markerSpan.innerHTML = item.screenNum + "面屏";
markerContent.appendChild(markerSpan);
// 更新点标记内容
marker.setContent(markerContent);
// marker.setPosition([e.x,e.y]); //更新点标记位置
});
},
mapZoom(){
const _this = this
// 获取缩放的比例 3-19级
_this.map.on("zoomend", function (e) {
// 判断缩放比例
let zoomNum = _this.map.getZoom();
_this.zoomNum = zoomNum
console.log("缩放的比例=",zoomNum);
// 清除 marker
function clearMarker() {
_this.map.clearMap();
}
clearMarker();
if (zoomNum < 9 && zoomNum > 3) {
// clearMarker();
_this.markersList(_this.mapCityList, '0');
}
if (zoomNum < 12 && zoomNum >= 9) {
// clearMarker();
_this.markersList(_this.mapAreaList, '1');
}
if (zoomNum <= 19 && zoomNum >= 12) {
// clearMarker();
_this.markersList(_this.mapSiteNameList, '2');
}
});
}
},
updated() {
this.markersList(this.mapCityList)
this.mapZoom()
console.log("mapData",this.mapData)
},
watch:{
// watch 检测数据的变化
mapCityList(){
// if(this.zoomNum < 9 && this.zoomNum > 3){
this.initMap()
this.markersList(this.mapCityList, '0')
this.mapZoom()
// }
},
mapAreaList(){
// if(this.zoomNum < 12 && this.zoomNum > 9){
// this.markersList(this.mapAreaList, '1')
this.mapZoom()
// }
// this.markersList(this.mapAreaList, '0')
// this.mapZoom()
},
mapSiteNameList(){
// if(this.zoomNum < 16 && this.zoomNum > 12){
// this.markersList(this.mapSiteNameList, '2')
this.mapZoom()
// }
// this.markersList(this.mapSiteNameList, '0')
// this.mapZoom()
},
zoomNum(){
this.mapZoom()
}
}
};
</script>
<style lang='scss'>
#map {
/* font-family: "Avenir", Helvetica, Arial, sans-serif; */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
#container {
height:100vh;
// margin-top: .88rem;
// flex: 1;
}
/* 去掉高德的logo和版本号 */
.amap-logo {
display: none;
}
.amap-copyright {
opacity: 0;
}
.marker-wrapper {
height: 1.1rem;
width: 1.1rem;
border: .02rem solid #fff;
border-radius: 50%;
background: $main-color;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.marker {
color: #fff;
font-size: 0.24rem;
width: 1rem;
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
}
</style>
项目中其实只有几处需要用到地图,不需要全局引入;
在index文件中引入js会明显拖慢首屏加载速度,虽然可以使用异步加载script的方式解决,但是始终觉得不够优雅。
解决方案
1.创建一个AMap.js
,路径'utils/AMap'
export default function MapLoader () { // <-- 原作者这里使用的是module.exports
return new Promise((resolve, reject) => {
if (window.AMap) {
resolve(window.AMap)
} else {
var script = document.createElement('script')
script.type = 'text/javascript'
script.async = true
script.src = 'http://webapi.amap.com/maps?v=1.3&callback=initAMap&key=yourkey'
script.onerror = reject
document.head.appendChild(script)
}
window.initAMap = () => {
resolve(window.AMap)
}
})
}
// test.vue
<template>
<div class="map">
<div id="container" class="h300 w300"></div>
</div>
</template>
<script>
import MapLoader from '@/utils/AMap'
export default {
name: 'map',
data () {
return {
map: null
}
},
mounted () {
let _this = this
MapLoader().then(AMap => {
console.log('地图加载成功')
_this.map = new AMap.Map('container', {
center: [113.264385, 23.129112],
zoom: 9
})
}, e => {
console.log('地图加载失败' ,e)
})
}
}
</script>
上面有些代码会冗余,没有整理好,仅用于个人项目需求效果,可能存在其他问题,后面慢慢补充。