初次使用高德地圖+vue-amap實現標記點+label功能
阿新 • • 發佈:2022-05-25
效果圖:
步驟:
1. npm安裝
npm install vue-amap --save
2. 安裝後在main.js中設定以下內容
import VueAMap from 'vue-amap'; Vue.use(VueAMap); VueAMap.initAMapApiLoader({ key: '你申請的key', plugin: ["AMap.Driving", "AMap.ToolBar"], v: '2.0' });
3 .應用
<template> <div class="amap-wrapper"> <el-amap class="amap-box" :amap-manager="amapManager" :events="events" vid="amapContainer"> </el-amap> </div> </template> <script> import { AMapManager, lazyAMapApiLoaderInstance } from'vue-amap' const amapManager = new AMapManager() export default { name: 'MapShow', data() { return { amapManager, events: {}, markerList: [ {marker: [113.697791,34.746216], name: '蘭桂小區'}, {marker: [113.698758,34.745175], name: '海上香頌'}, {marker: [113.695714,34.74422], name: '朝陽御景'}, {marker: [113.69469,34.745463], name: '長城康橋花園'}, ], iconPoint: require('../assets/ico.png') }; }, mounted() { lazyAMapApiLoaderInstance.load().then(() => { this.map = new window.AMap.Map('amapContainer', { center: [113.69469, 34.745463], //地圖顯示的中心位置 zoom: 14, //地圖縮放比例 }) this.map.addControl(new window.AMap.ToolBar({ // 簡易縮放模式,預設為 false liteStyle: true })); //地圖示記點方法 this.createMark() }) }, methods: { createMark() { const icon = new window.AMap.Icon({ size: new window.AMap.Size(24, 24), image: this.iconPoint, imageSize: new window.AMap.Size(24, 24) }) var labelOffset = new window.AMap.Pixel(0, -5); this.markerList.forEach((item) => { const labelContent = "<div class='labelContent'>"+item.name+"</div>" const marker = new window.AMap.Marker({ position: item.marker, icon: icon, anchor: 'center', //設定錨點 offset: new window.AMap.Pixel(0,0), //設定偏移量 label: { direction: 'top', content: labelContent, offset: labelOffset, } }) // this.map.add(marker) marker.setMap(this.map) }) }, eventsFun() { const self = this return { // 地圖載入完成時執行的方法 complete() { self.createMark() } } } }, }; </script> <style lang="less" scoped> .amap-wrapper { width: 100%; height: 500px; } </style>