注册地图key
使用地图前,需要到对应官网申请key
1.首先,注册开发者账号,成为高德开放平台开发者
2. 登陆之后,在进入「应用管理」 页面「创建新应用」
3. 为应用添加 Key,「服务平台」一项请选择「 Web 端 ( JSAPI )」
项目中引用
申请完key之后,这里已后台系统为例,使用地图。
1.在index.html,一般在public文件夹下或根目录
image.png
引用相关文件,这里使用了地图工具,有兴趣可以官网可以了解下AMap.Geocode
<link rel="stylesheet" href="https://cache.amap.com/lbs/static/main1119.css"/>
<script src="https://cache.amap.com/lbs/static/es5.min.js"></script>
<script src="https://webapi.amap.com/maps?v=1.4.8&key=你申请的key&plugin=AMap.MouseTool&plugin=AMap.Geocoder"></script>
<script src="//webapi.amap.com/ui/1.0/main.js?v=1.0.11"></script>
2.引用完之后,项目基本可以使用了,这里使用组件的方式引入
image.png
utils.js,这里将地图对象的创建和一些需要的功能的方法统一起来,后续方便调用
const _clickMarker = Symbol('_clickMarker');
const _addPolygon = Symbol('_addPolygon');
const _addOtherPolygon = Symbol('_addOtherPolygon');
const _deleteNode = Symbol('_deleteNode');
let polylines = [];
let polyEditor;
let polygon;
let markerPoint = [];
class Amap {
constructor(map, amap) {
if (!map || !amap) {
throw new Error('map or amap is required');
}
this.map = map;
this.amap = amap;
this.path = [];
}
addTeamPoint (points) { // 通过坐标以红点显示
const {
map,
amap
} = this;
var markerContent = "<div style='width:10px;height:10px;background:red;border-radius:50%'></div>";
points.forEach(item => {
const notMarker = new amap.Marker({
position: item,
content: markerContent,
});
map.add(notMarker);
notMarker.setLabel({
offset: new amap.Pixel(-60, -20), // 修改label相对于maker的位置
content: 123123141231
});
map.setFitView(notMarker);
});
}
addPoint (lnglat, labelShow) {
const {
map,
amap
} = this;
map.remove(markerPoint);
markerPoint = [];
const position = new amap.LngLat(lnglat.lng, lnglat.lat);
const marker = new amap.Marker({
position,
// 以 icon 的 [center bottom] 为原点
offset: new amap.Pixel(-13, -30)
});
if (labelShow === 1) {
marker.setLabel({
offset: new amap.Pixel(-60, -20), // 修改label相对于maker的位置
content: 123123141231
});
}
// 将 markers 添加到地图
map.add(marker);
markerPoint.push(marker);
map.setFitView(marker);
}
startPoint (callback) {
polygon.on('click', (e) => {
this.addPoint(e.lnglat);
callback(e.lnglat);
});
}
setData ({
path,
point,
}) {
const {
amap
} = this;
if (point) {
this[_addPolygon](path);
this.addPoint(new amap.LngLat(point[0], point[1]));
} else {
this[_addOtherPolygon](path);
}
}
// 画圆
circleDrawing ({
point,
deliverRange,
labelShow
}) {
const {
map,
amap
} = this;
const circle = new amap.Circle({
center: [point[0], point[1]], // 圆心位置
radius: deliverRange, // 半径
fillColor: '#1791fc40',
strokeColor: '#FF33FF'
});
this.addPoint(new amap.LngLat(point[0], point[1]), labelShow);
circle.setMap(map);
}
selectionPoint (callback) {
this.map.on('click', (e) => {
this.addPoint(e.lnglat);
callback(e.lnglat);
});
}
setPoint (point) { // 设置地图标点
const {
amap
} = this;
this.addPoint(new amap.LngLat(point[0], point[1]));
}
// 画线
addPolyline (path) {
const {
map,
amap
} = this;
map.remove(polylines);
polylines = [];
const polyline = new amap.Polyline({
path,
isOutline: true,
outlineColor: '#ffeeff',
borderWeight: 3,
strokeColor: '#3366FF',
strokeOpacity: 1,
strokeWeight: 6,
strokeStyle: 'solid',
strokeDasharray: [10, 5],
lineJoin: 'round',
lineCap: 'round',
zIndex: 50
});
polyline.setMap(map);
polylines.push(polyline);
// 缩放地图到合适的视野级别
map.setFitView([polyline]);
}
// 清除地图上所有的覆盖物
clearMap () {
this.map.clearMap();
}
// 开始编辑
polyEditorStart () {
if (polyEditor) {
polyEditor.open();
}
}
// 关闭编辑
polyEditorClose (callback) {
if (polyEditor) {
polyEditor.close();
callback(this.path);
}
}
// 检查点是否在多边形内
isPointInRing (point, path) {
const {
amap
} = this;
if (polyEditor) {
polyEditor.close();
}
const isPointInRing = amap.GeometryUtil.isPointInRing(point, path);
return isPointInRing;
}
autocomplete () { // 输入相关关键字,联想相关地点
const {
map,
amap
} = this;
console.log(amap);
amap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], () => {
const autoOptions = {
city: '广州', // 城市,默认全国
input: 'pickerInput' // 使用联想输入的input的id
};
const autocomplete = new amap.Autocomplete(autoOptions);
amap.event.addListener(autocomplete, 'select', (e) => {
map.setCenter(e.poi.location);
});
});
}
geolocation () { // 获取当前位置
const {
map,
amap
} = this;
map.plugin('AMap.Geolocation', () => {
const geolocation = new amap.Geolocation({
enableHighAccuracy: true, // 是否使用高精度定位,默认:true
timeout: 10000, // 超过10秒后停止定位,默认:无穷大
maximumAge: 0, // 定位结果缓存0毫秒,默认:0
convert: true, // 自动偏移坐标,偏移后的坐标为高德坐标,默认:true
showButton: true, // 显示定位按钮,默认:true
buttonPosition: 'LB', // 定位按钮停靠位置,默认:'LB',左下角
buttonOffset: new amap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
showMarker: true, // 定位成功后在定位到的位置显示点标记,默认:true
showCircle: true, // 定位成功后用圆圈表示定位精度范围,默认:true
panToLocation: true, // 定位成功后将定位到的位置作为地图中心点,默认:true
zoomToAccuracy: true // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
});
map.addControl(geolocation);
geolocation.getCurrentPosition();
amap.event.addListener(geolocation, 'complete', (e) => {
console.log(e);
}); // 返回定位信息
});
}
[_clickMarker] (path, finishCallback) {
if (path.length > 2) {
this.clearMap();
this[_addPolygon](path, finishCallback);
}
}
[_deleteNode] (index, callback) {
callback(index, this);
}
[_addPolygon] (path, finishCallback) { // 编辑构建多边形,可以通过点击的方式点与点连线构成多边形
const {
map,
amap
} = this;
polygon = new amap.Polygon({
path,
isOutline: true,
borderWeight: 3,
strokeColor: '#FF33FF',
strokeWeight: 6,
strokeOpacity: 0.2,
fillOpacity: 0.4,
// 线样式还支持 'dashed'
fillColor: '#1791fc',
zIndex: 50
});
polygon.setMap(map);
if (finishCallback) {
finishCallback(path);
}
map.plugin(['AMap.PolyEditor'], () => {
polyEditor = new amap.PolyEditor(map, polygon);
polyEditor.on('end', (event) => {
this.path = event.target.getPath();
});
});
}
[_addOtherPolygon] (path) { //绘制多边形图案
const {
map,
amap
} = this;
const otherPolygon = new amap.Polygon({
path,
isOutline: true,
borderWeight: 3,
strokeColor: '#FF33FF',
strokeWeight: 6,
strokeOpacity: 0.2,
fillOpacity: 0.4,
fillColor: '#1791fc',
zIndex: 50
});
otherPolygon.setMap(map);
}
getLocalBylnlt (data) { // 返回经纬度和地址转换的对象
const {
map,
amap
} = this;
const geocoder = new amap.Geocoder({
city: '010'
});
return geocoder;
}
}
export default Amap;
创建组件
<template>
<div
:id="mapId"
class="map-content"
:style="{'height':height+'px'}"
>
<div id="pickerBox">
<input
id="pickerInput"
ref="seach"
placeholder="输入键字选取地点"
>
<div id="poiInfo" />
</div>
</div>
</template>
<script>
import MapUtils from './utils';
export default {
props: {
mapId: {
type: String,
required: true
},
type: {
type: String,
default: ''
},
height: {
type: Number,
default: 500
}
},
data () {
return {
map: null,
AMap: window.AMap,
utils: null,
path: [],
clickListener: null
};
},
mounted () {
const { mapId, AMap } = this;
const map = new AMap.Map(mapId, {
resizeEnable: true,
// center: this.localMarker,
zoom: 20,
mapStyle: 'amap://styles/whitesmoke'
});
this.map = map;
const utils = new MapUtils(map, AMap);
this.utils = utils;
if (!this.type) {
utils.placeSearch();
}
// 加载BasicControl,loadUI的路径参数为模块名中 'ui/' 之后的部分
window.AMapUI.loadUI(['control/BasicControl'], function (BasicControl) {
// 缩放控件
map.addControl(new BasicControl.Zoom({
position: 'rb', // right bottom,右下角
showZoomNum: true // 显示zoom值
}));
});
const _this = this;
AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], () => {
const autoOptions = {
city: '广州', // 城市,默认全国
input: 'pickerInput' // 使用联想输入的input的id
};
const autocomplete = new AMap.Autocomplete(autoOptions);
AMap.event.addListener(autocomplete, 'select', (e) => {
const { lng, lat } = e.poi.location;
utils.setPoint([lng, lat]);
_this.getLocalBylnlt([lng, lat] , false);
});
});
},
methods: {
// 地图选点 开启选点
startPoint (callback) {
const { utils } = this;
this.$refs.seach.value = '';
utils.selectionPoint(callback);
},
// 显示已有的标记
setPoint (callback) {
const { utils } = this;
utils.setPoint(callback);
},
getLocalBylnlt (data, boolOpen) {
const { utils } = this;
let geocoder = null;
if (!geocoder) {
geocoder = utils.getLocalBylnlt();
}
if (boolOpen) {
geocoder.getAddress(data, (status, result) => {
if (result.info === "OK") {
this.$emit("getLocalhost", { address: result.regeocode.formattedAddress, local: data });
}
})
} else {
this.$emit("getLocalhost", { address: "", local: data });
}
},
}
};
</script>
<style>
.custom-content-marker {
position: relative;
width: 25px;
height: 34px;
}
.custom-content-marker img {
width: 100%;
height: 100%;
}
#pickerBox {
position: absolute;
z-index: 9999;
top: 2%;
right: -5%;
width: 300px;
}
#pickerInput {
width: 200px;
padding: 5px 5px;
}
#poiInfo {
background: #fff;
}
.amap_lib_placeSearch .poibox.highlight {
background-color: #cae1ff;
}
.amap_lib_placeSearch .poi-more {
display: none !important;
}
.amap-sug-result {
z-index: 9999;
}
</style>
引用
image.png
// 引用该组件文件所对应的方法
// 开始选点
selectionPoint () {
this.$nextTick(() => {
this.$refs.maps.startPoint((point) => {
if (point) {
this.latitude = point.lat;
this.longitude = point.lng;
}
});
})
},
getLocal () {
this.localMapVis = true;
this.selectionPoint();
const longitude = 113.280353;
const latitude = 23.125223;
this.$nextTick(() => {
this.$refs.maps.setPoint([longitude, latitude]);
})
},
getMapInfo () {
const { longitude, latitude } = this;
this.$refs.maps.getLocalBylnlt([longitude, latitude], true);
},
getLocalhost (res) {
console.log(res);
this.latitude = res.local[1];
this.longitude = res.local[0];
}
功能方法描述
1.该组件可以在地图标记点
2.该组件可以通过选择联想输入的地址,设置标点
3.该组件可以通过标点获得当前地址详细信息和经纬度
image.png
其他方法示例
image.png
相关方法
画圆 、显示附近点