赞
踩
高德官网教程地址:https://lbs.amap.com/api/javascript-api/guide/abc/prepare
官网其实很详细啦,但这是比官网还详细的保姆级教程!
入门准备:
成功注册账号后,申请key:
1.
2.
3.
在项目中,assets文件中新建一个js文件,用于引入高德api,代码:
export default function MapLoader () { return new Promise((resolve, reject) => { if (window.AMap) { resolve(window.AMap) } else { // 动态创造DOM,引入api let script = document.createElement('script') script.type = 'text/javascript' script.async = true script.src = 'http://webapi.amap.com/maps?v=1.3&callback=initAMap&key=注册的key值' script.onerror = reject document.body.appendChild(script) } window.initAMap = () => { resolve(window.AMap) } }) }
接下来在webpack.base.conf.js文件里添加:
与entry同级
externals: {
'AMap': 'AMap'
},
在components中新建Amap.vue,代码如下:
<template> <div id="container" style="position: relative;width: 100%; height:500px;"></div> </template> <script> import MapLoader from '../assets/amap' export default { name: 'Amap', data () { return { map: '', } }, mounted() { this.initAMap() }, methods: { initAMap () { let that = this MapLoader().then(AMap => { that.map = new AMap.Map('container', { zoom: 11, // 级别 center: [116.397428, 39.90923], // 中心点坐标 viewMode:'3D' // 使用3D视图 }) // 异步加载插件 // AMap.ToolBar: 滑动工具条, AMap.Scale: 比例尺 // 一次加载多个 AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], function () { that.map.addControl(new AMap.ToolBar()) that.map.addControl(new AMap.Scale()) }) // AMap.Geolocation: 定位 AMap.plugin('AMap.Geolocation', function () { let 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 }) that.map.addControl(geolocation) // 获取当前定位的信息 geolocation.getCurrentPosition((status,result) => { console.log(result.addressComponent) }) // AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息 // AMap.event.addListener(geolocation, 'error', onError); //返回定位出错信息 }) }) } } } </script> <style scoped> /*隐藏高德地图logo,版本号*/ /deep/ .amap-logo{ visibility: hidden; } /deep/ .amap-copyright { visibility: hidden; } </style>
如果注释还有不明白的地方,可以看官网教程哦~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。