高德地图(前端入门学习)
參考文檔
官方教程
基礎(chǔ)知識(shí)
lng:經(jīng)度
lat:緯度
在百度地圖中,習(xí)慣經(jīng)度在前,緯度在后
地球上同一個(gè)地理位置的經(jīng)緯度,在不同的坐標(biāo)系中,會(huì)有少于偏移,國(guó)內(nèi)目前常見(jiàn)的坐標(biāo)系主要分為三種:
地球坐標(biāo)系——WGS84:常見(jiàn)于 GPS 設(shè)備,Google 地圖等國(guó)際標(biāo)準(zhǔn)的坐標(biāo)體系。
火星坐標(biāo)系——GCJ-02:中國(guó)國(guó)內(nèi)使用的被強(qiáng)制加密后的坐標(biāo)體系,高德坐標(biāo)就屬于該種坐標(biāo)體系。
百度坐標(biāo)系——BD-09:百度地圖所使用的坐標(biāo)體系,是在火星坐標(biāo)系的基礎(chǔ)上又進(jìn)行了一次加密處理。
準(zhǔn)備
1、注冊(cè)開(kāi)發(fā)者賬號(hào)
2、創(chuàng)建新應(yīng)用
3、為應(yīng)用添加 Key,「服務(wù)平臺(tái)」一項(xiàng)請(qǐng)選擇「 Web 端 ( JSAPI ) 」
vue項(xiàng)目使用(方案一:引用原生api)(全局注冊(cè))(不推薦)
首先,申請(qǐng) Key
其次,引入地圖 js,在public/index.html里面添加下面代碼
然后,創(chuàng)建vue.config.js文件,寫(xiě)入
module.exports = {configureWebpack: {externals: {'AMap': 'AMap','AMapUI': 'AMapUI'}} };最后,組件引入,mounted時(shí)初始化地圖(注意要設(shè)置容器的寬高)
<template><div class="wrap"><!-- 1、創(chuàng)建地圖容器 --><div id="container"style="width:100%;height:600px"></div></div> </template><script> // 2、引用地圖類 import AMap from "AMap" // import AMapUI from 'AMapUI' export default {data () {return {map: null,}},// 3、mounted時(shí)初始化地圖mounted () {this.init();},methods: {init () {this.map = new AMap.Map("container", {zoom: 11, //級(jí)別resizeEnable: true});},} }; </script>vue項(xiàng)目使用(方案二:引用原生api)(單頁(yè)面按需加載)
1、創(chuàng)建utils/AMap.js文件,寫(xiě)入初始化函數(shù)loadAMap,用于動(dòng)態(tài)加載地圖api。
/* eslint-disable */ export default function loadAMap(ak) {return new Promise(function(resolve, reject) {if (typeof AMap !== 'undefined') {resolve(AMap)return true}window.onAMapCallback = function() {resolve(AMap)} // let script = document.createElement('script') // script.type = 'text/javascript' // script.src = 'https://webapi.amap.com/maps?v=2.0&key=' + ak + '&callback=onAMapCallback' // script.onerror = reject // document.head.appendChild(script)let AMapURL = 'https://webapi.amap.com/maps?v=2.0&key=' + ak + '&callback=onAMapCallback'let scriptNode = document.createElement('script')scriptNode.setAttribute('type', 'text/javascript')scriptNode.setAttribute('src', AMapURL)scriptNode.onerror = rejectdocument.body.appendChild(scriptNode)}) }2、頁(yè)面使用
a、創(chuàng)建地圖容器Div
b、引用import loadAMap from "@/utils/AMap.js"
c、在mounted使用loadAMap函數(shù)創(chuàng)建地圖實(shí)例
vue項(xiàng)目使用(方案三:引用原生api)(按 NPM 方式使用 Loader)(推薦)
JSAPI 腳本加載詳解
安裝:
npm i @amap/amap-jsapi-loader --save使用:
import AMapLoader from '@amap/amap-jsapi-loader';let that = this AMapLoader.load({"key": "您申請(qǐng)的key值", // 申請(qǐng)好的Web端開(kāi)發(fā)者Key,首次調(diào)用 load 時(shí)必填"version": "1.4.15", // 指定要加載的 JSAPI 的版本,缺省時(shí)默認(rèn)為 1.4.15"plugins": [], // 需要使用的的插件列表,如比例尺'AMap.Scale'等"AMapUI": { // 是否加載 AMapUI,缺省不加載"version": '1.1', // AMapUI 缺省 1.1"plugins":[], // 需要加載的 AMapUI ui插件},"Loca":{ // 是否加載 Loca, 缺省不加載"version": '1.3.2' // Loca 版本,缺省 1.3.2}, }).then((AMap)=>{that.map = new AMap.Map('container'); }).catch(e => {console.log(e); })vue項(xiàng)目使用(方案四:vue-amap組件)
官方文檔
npm地址
參考案例
點(diǎn)線面地圖選點(diǎn)組件封裝案例(vue引用原生api)
<template><a-modal title="坐標(biāo)拾取":width="1000":visible="visible":maskClosable="false"@ok="handleConfirm"@cancel="handleCancel":bodyStyle="{padding:'12px'}"><div style="position: relative;"><a-select size="small"placeholder="請(qǐng)選擇地點(diǎn)類型"v-model="locationType"@change="changeType"style="position: absolute;top: 0;right: 0;z-index:2;width:160px;"><a-select-option :value="0">點(diǎn)</a-select-option><a-select-option :value="1">線</a-select-option><a-select-option :value="2">面</a-select-option></a-select><div id="pickUpMap"style="height:500px"></div></div></a-modal> </template> <script>import AMap from 'AMap' // import AMapUI from 'AMapUI' import { IconFont } from '@/core/my_icon' export default {components: { IconFont },data () {return {submitLoading: false,visible: false,// 覆蓋物集合overlays: [],coordinate: [],locationType: 0,oldType: 0,map: null,mouseTool: null,oldMarker: null,oldPolyline: null,oldPolygon: null}},computed: {show: {get: function () {return this.visible},set: function () { }}},watch: {visible (newVal, oldVal) {// if (newVal) {// setTimeout(() => {// this.init()// }, 400)// }}},methods: {showMap (coordinate, locationType) {this.visible = truethis.locationType = locationType || 0this.oldType = locationType || 0this.coordinate = coordinate ? coordinate.split(',') : []setTimeout(() => {this.init()}, 100)},// 地圖初始化init () {const that = thisthat.map = new AMap.Map('pickUpMap', {zoom: 11,resizeEnable: true})// 添加工具類this.addTool()// 如果有覆蓋物,觸發(fā)繪制函數(shù)if (this.coordinate.length) {this.initDraw()}},initDraw () {const arr = this.coordinate.map(item => ({lng: parseFloat(item.split(' ')[0]),lat: parseFloat(item.split(' ')[1])}))// console.log(this.oldType, arr)if (this.oldType == 0) {this.oldMarker = new AMap.Marker({position: new AMap.LngLat(arr[0].lng, arr[0].lat)})// console.log('marker', this.oldMarker)this.map.add(this.oldMarker)this.map.setFitView()} else if (this.oldType == 1) {var path1 = arr.map(item => {return new AMap.LngLat(item.lng, item.lat)})// console.log('path1', path1)this.oldPolyline = new AMap.Polyline({path: path1,strokeColor: '#80d8ff'})this.map.add(this.oldPolyline)this.map.setFitView()} else if (this.oldType == 2) {var path2 = arr.map(item => {return new AMap.LngLat(item.lng, item.lat)})// console.log('path2', path2)this.oldPolygon = new AMap.Polygon({path: path2,fillColor: '#00b0ff',strokeColor: '#80d8ff'})this.map.add(this.oldPolygon)this.map.setFitView()}},addTool () {const that = this// 縮放控制條-地圖工具條(ToolBar)AMap.plugin(['AMap.ToolBar'], () => {const toolbar = new AMap.ToolBar()that.map.addControl(toolbar)})// 縮略圖-鷹眼(OverView)AMap.plugin(['AMap.OverView'], () => {const overView = new AMap.OverView({visible: true // 初始化顯示鷹眼})that.map.addControl(overView)overView.open() // 展開(kāi)鷹眼})// 比例尺(Scale)AMap.plugin(['AMap.Scale'], () => {const scale = new AMap.Scale()that.map.addControl(scale)scale.show()})// 添加鼠標(biāo)工具(MouseTool)AMap.plugin(['AMap.MouseTool'], () => {const MouseTool = new AMap.MouseTool(that.map)that.mouseTool = MouseTool})// 添加繪制事件that.draw(that.locationType)// 監(jiān)聽(tīng)繪圖事件,獲取覆蓋物對(duì)象信息that.mouseTool.on('draw', function (e) {// console.log(e.obj)// 先清空再添加覆蓋物信息that.clearAll()that.overlays.push(e.obj)})},clearAll () {const that = thisthat.map.remove(that.overlays)// 清空當(dāng)前繪畫(huà)物that.overlays = []// 如果是修改,有且僅需要操作一次 清空原來(lái)的繪制覆蓋物if (that.coordinate.length) {that.coordinate = []if (that.oldType == 0) {that.map.remove(that.oldMarker)} else if (that.oldType == 1) {that.map.remove(that.oldPolyline)} else if (that.oldType == 2) {that.map.remove(that.oldPolygon)}}},changeType (val) {this.draw(val)},// 繪圖draw (type) {switch (type) {case 0: {this.mouseTool.marker({// 同Marker的Option設(shè)置})break}case 1: {this.mouseTool.polyline({strokeColor: '#80d8ff'// 同Polyline的Option設(shè)置})break}case 2: {this.mouseTool.polygon({fillColor: '#00b0ff',strokeColor: '#80d8ff'// 同Polygon的Option設(shè)置})break}}},handleCancel () {this.visible = falsethis.overlays = []this.coordinate = []this.locationType = 0this.oldType = 0this.map = nullthis.mouseTool = nullthis.oldMarker = nullthis.oldPolyline = nullthis.oldPolygon = null},handleConfirm () {const { overlays, locationType } = thisconst coordinate = this.toPosition(overlays[0])this.$emit('confirm', { coordinate, locationType })this.handleCancel()},toPosition (overlay) {let str = ''if (overlay['CLASS_NAME'] == 'AMap.Marker') {// //console.log('Marker', overlay.getPosition())const marker = overlay.getPosition()str = marker['R'] + ' ' + marker['Q']return str} else if (overlay['CLASS_NAME'] == 'AMap.Polyline') {// //console.log('Polyline', overlay.getPath())const arr = overlay.getPath().map(item => {return item['R'] + ' ' + item['Q']})str = arr.join(',')return str} else if (overlay['CLASS_NAME'] == 'AMap.Polygon') {// //console.log('Polygon', overlay.getPath())const arr = overlay.getPath().map(item => {return item['R'] + ' ' + item['Q']})arr.push(arr[0])str = arr.join(',')return str}}} } </script> <style lang="less" scoped> </style>組件使用
<CoordinateMap ref="CoordinateMap"@confirm="pickUpConfirm" />coordinate: '', locationType: null// 坐標(biāo)拾取 openCoordinateMap () {const { coordinate, locationType } = thisthis.$refs.CoordinateMap.showMap(coordinate, locationType) }, // 組件回調(diào) pickUpConfirm (obj) {// console.log('pickUpConfirm', obj)this.coordinate = obj.coordinatethis.locationType = obj.locationType },總結(jié)
以上是生活随笔為你收集整理的高德地图(前端入门学习)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Linux 虚拟机忘记密码解决办法
- 下一篇: 文后参考文献著录规则 自动生成器 HTM