Let's talk about how to use the Amap API in vue3
Mar 09, 2023 pm 07:22 PMWhen we used Amap, the official recommended many cases to us, demo
, but these cases all used native methods to access and did not provide vue
or Many people have written about react
’s demo
and vue2
’s access to the Internet. Let’s take a look at this article vue3
How to use the commonly used Gaode mapapi
, I hope it will be helpful to everyone!
Pre-work
We need to understand before development
vue3
Medium access to high Several steps for German map
- First install the package and introduce
npm i @amap/amap-jsapi-loader --save
import AMapLoader from '@amap/amap-jsapi-loader'
Use the official introduction method There is a difference between adding
vue2
and vue3
, here we use vue3
, But the method of vue3
here is still optional, not combined. When I wrote it myself, I used combined type and integrated ts
. I will publish the complete later. When creating the .vue
file, the ts on the label will be removed, because the type is not yet complete, and the changes will be posted after it is completed later. Why use shallowRef
The official also gave an explanation. [Related recommendations: vuejs video tutorial, web front-end development]
Sample module
Here I will directly I took the business logic of the map business requirements that I wrote earlier and introduced it directly into an html file without using a framework. You can click on the link below to view:
Use of Amap jsApi
Point and line configuration of Gaode map jsApi
Right-click setting of Gaode map jsApi
New point position of Gaode map jsApi Add
Amap jsApi legend
When usingvue3
, the instantiation method,this
problem, and insertion When using string templates, the way of event response needs to be changed, which is still very troublesome
模塊的引入
- 首先導(dǎo)入的方式,和官網(wǎng)一樣,后面我會(huì)貼完整代碼, 這里我們使用
plugins
加載插件, 其他配置如Loca
, 直接進(jìn)行配置, 這里需要注意版本問題, 寫成 ‘2.0’ 是不行的,初始化函數(shù)在onmounted
生命周期中執(zhí)行。 - AMap存儲(chǔ) 這里我做了很多存儲(chǔ),大家知道
.value
的語法是vue3
獲取ref
的語法,我下面使用到的 都是ref
,后面完整代碼可以查看, 這里掛載的時(shí)候直接存一下,因?yàn)楹芏喙ぞ叻椒ǘ紩?huì)只用到他,這里后期業(yè)務(wù)邏輯我會(huì)抽離到pinia
中去,所以不需要在初始化函數(shù)中寫全部的業(yè)務(wù)邏輯。 - 模版樣式不生效問題, 我們?cè)谑褂玫臅r(shí)候, 就像我之前寫的文章,點(diǎn)位新增的時(shí)候,我們會(huì)插入
content
字符串模版,替換點(diǎn)樣式,這里有兩種方案修改樣式,一種是 插入DOM
,不使用字符串,然后在DOM
上通過style
直接修改樣式,另一種就是使用模版的時(shí)候直接給class
類名,但是這種樣式如果我們給vue
的style
加了scoped
就不會(huì)生效,這里大家可以自己靈活選擇用哪種,我這里暫時(shí)先使用模版的方式,去掉了scoped
。 - 圖例, 圖例這里除了導(dǎo)入的時(shí)候,需要配置一下,使用上來說變化不大,樣式的修改還是復(fù)用了我之前的邏輯。
import AMapLoader from '@amap/amap-jsapi-loader' const initMap = () => { AMapLoader.load({ key: 'b59c490f61a694b9d7576dd864f74d6e', // 申請(qǐng)好的Web端開發(fā)者Key,首次調(diào)用 load 時(shí)必填 version: '2.0', // 指定要加載的 JSAPI 的版本,缺省時(shí)默認(rèn)為 1.4.15 plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.MouseTool'], // 需要使用的的插件列表,如比例尺'AMap.Scale'等 Loca:{ version:'2.0.0' } }) .then((res) => { AMap.value = res // 上來就顯示的中心點(diǎn) 北京 116.397, 39.918 var lnglat = new res.LngLat(105, 38) map.value = new res.Map('container', { //設(shè)置地圖容器id viewMode: '3D', //是否為3D地圖模式 zoom: 5, //初始化地圖級(jí)別 center: lnglat, //初始化地圖中心點(diǎn)位置 }) map.value.clearMap() // 清除地圖覆蓋物 // 地圖是否可拖拽和縮放 map.value.setStatus({ dragEnable: true, // 是否可拖拽 zoomEnable: true, // 是否可縮放 }) initWindow() // 添加一些分布不均的點(diǎn)到地圖上,地圖上添加三個(gè)點(diǎn)標(biāo)記,作為參照 coordData.forEach(function (marker) { setMarker(marker) }) let renderLine = setLine(coordData) // 設(shè)置線 let polyline = renderLine.reduce((prev, item, index) => { let weight = item.type === 1 ? 5 : 3 let color = item.type === 1 ? headColors[0] : headColors[1] prev.push(setLines(item.current, color, weight)) return prev }, []) map.value.add([...polyline]) // 繪制線 //創(chuàng)建右鍵菜單 menuInstance.value = new ContextMenu(map.value) let loca = new Loca.Container({ map:map.value, }); window._loca = loca; // 圖例, 圖例可以實(shí)例化多個(gè),使用定位來設(shè)置位置 let lengend = new Loca.Legend({ loca: loca, title: { label: '管道類型', fontColor: 'rgba(255,255,255,1)', fontSize: '16px' }, style: { backgroundColor: 'rgba(255,255,255,0.2)', left: '20px', bottom: '40px', fontSize: '12px' }, dataMap: [ { label: '省級(jí)管道', color: headColors[1] }, { label: '縣級(jí)管道', color: headColors[0] }, ], }); //修改圖例排列方式 document.getElementsByClassName("amap-loca loca-controls")[0].setAttribute('id', 'testid') var lis = document.querySelectorAll("#testid li"); for (var i = 0; i < lis.length; i++) { console.log(lis[i]); lis[i].setAttribute("class", 'test' ); } }) .catch((e) => { console.log('error', e) }) } onMounted(() => { initMap() })
右鍵菜單
右鍵菜單, 右鍵菜單這里官方給我們的示例是使用一個(gè) 函數(shù) 進(jìn)行實(shí)例化,里面使用了
this
, 所以這個(gè)我單獨(dú)拿出來,首先我們看一下官方的 demo
- 這里使用了一個(gè)函數(shù),但這個(gè)函數(shù)還不是類,但是他卻在里面使用了
this
,實(shí)話來講,這種寫法確實(shí)不是很優(yōu)秀,可擴(kuò)展性很差,不夠健壯,但沒辦法,誰讓我們用了人家的東西呢是吧, 在vue3
中這么用就不可以了,首先vue3
里面使用this
就不是官方建議的, 另外這里面還修改了函數(shù)原型上的方法,其實(shí)我得代碼里面一共有兩種右鍵菜單,如下:
一種是在指定點(diǎn)位上打開,另一種是在非點(diǎn)位的空白處打開,指定點(diǎn)位處打開的其實(shí)叫信息窗體,只不過是通過右鍵的方式觸發(fā),那個(gè)沒有上面這個(gè)右鍵菜單麻煩。
- 首先來說
this
問題, 這里的this
實(shí)際上就是把我們的實(shí)例化對(duì)象掛載到上面而已,vue3
中沒辦法像vue2
那樣使用this
, 但也提供給我們了api
來獲取當(dāng)前組件的實(shí)例化對(duì)象, 然后我沒用使用函數(shù), 使用了一個(gè)類,類構(gòu)造這個(gè)方法, 模版也不適用字符串模版,因?yàn)檫@里字符串模版的事件綁定寫死了,我們使用DOM
來動(dòng)態(tài)綁定事件,代碼如下:
const { ctx } = getCurrentInstance() const _this = ctx //自定義菜單類 class ContextMenu { constructor(map) { var me = _this //地圖中添加鼠標(biāo)工具M(jìn)ouseTool插件 _this.mouseTool = new AMap.value.MouseTool(map) _this.contextMenuPositon = null const fragment = document.createElement('div') // 使用 DOM 方式, 方便添加事件 fragment.className = 'info context_menu' const p = document.createElement('p') p.addEventListener('click', this.delMarkerMenu) p.textContent = '移除上次選中信息' fragment.appendChild(p) //通過content自定義右鍵菜單內(nèi)容 _this.contextMenu = new AMap.value.ContextMenu({ isCustom: true, content: fragment, }) //地圖綁定鼠標(biāo)右擊事件——彈出右鍵菜單 map.on('rightclick', function (e) { me.contextMenu.open(map, e.lnglat) me.contextMenuPositon = e.lnglat //右鍵菜單位置 }) } delMarkerMenu() { // 右鍵菜單上次選中點(diǎn)的信息 clearPoint() _this.mouseTool.close() _this.contextMenu.close() } }
完整代碼
添加選點(diǎn)請(qǐng)輸入坐標(biāo)
- 這里的業(yè)務(wù)邏輯還不完善, 輸入部分的交互邏輯沒有完成, 這個(gè)文件直接引入自己的項(xiàng)目,安裝一下上面說過的依賴, 就可以使用,不過這里數(shù)據(jù)源需要自己根據(jù)自己的數(shù)據(jù)來構(gòu)造就可以了,我引入的事
data
中的一組假數(shù)據(jù),在這里給大家兩組看一下
export const coordData = [ { name: '黑龍江', position: [127, 47], pointData: { out: 100, provide: 10, }, line: [ { current: [ [127, 47], [126, 43], ], type: 1, }, ], }, { name: '吉林', position: [126, 43], pointData: { out: 120, provide: 11, }, line: [ { current: [ [126, 43], [113, 41], ], type: 1, }, ], }, ]
- 后面我會(huì)把業(yè)務(wù)邏輯抽離到
pinia
中, 并且完善ts
類型, 大家對(duì)哪一部分有疑問或者更好的解決方案可以留言一起學(xué)習(xí)~
(學(xué)習(xí)視頻分享:vuejs入門教程、編程基礎(chǔ)視頻)
The above is the detailed content of Let's talk about how to use the Amap API in vue3. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Graphviz is an open source toolkit that can be used to draw charts and graphs. It uses the DOT language to specify the chart structure. After installing Graphviz, you can use the DOT language to create charts, such as drawing knowledge graphs. After you generate your graph, you can use Graphviz's powerful features to visualize your data and improve its understandability.

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

There are three main technologies for visualizing data structures in PHP: Graphviz: an open source tool that can create graphical representations such as charts, directed acyclic graphs, and decision trees. D3.js: JavaScript library for creating interactive, data-driven visualizations, generating HTML and data from PHP, and then visualizing it on the client side using D3.js. ASCIIFlow: A library for creating textual representation of data flow diagrams, suitable for visualization of processes and algorithms.

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Combination of Golang and front-end technology: To explore how Golang plays a role in the front-end field, specific code examples are needed. With the rapid development of the Internet and mobile applications, front-end technology has become increasingly important. In this field, Golang, as a powerful back-end programming language, can also play an important role. This article will explore how Golang is combined with front-end technology and demonstrate its potential in the front-end field through specific code examples. The role of Golang in the front-end field is as an efficient, concise and easy-to-learn

Vue.js is not difficult to learn, especially for developers with a JavaScript foundation. 1) Its progressive design and responsive system simplify the development process. 2) Component-based development makes code management more efficient. 3) The usage examples show basic and advanced usage. 4) Common errors can be debugged through VueDevtools. 5) Performance optimization and best practices, such as using v-if/v-show and key attributes, can improve application efficiency.
