search
HomeWeb Front-endVue.jsLet's talk about how to use the Amap API in vue3

Let's talk about how to use the Amap API in vue3

Mar 09, 2023 pm 07:22 PM
front endvue.jsdata visualization

When 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!

Let's talk about how to use the Amap API in vue3

Pre-work

We need to understand before developmentvue3 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'

Lets talk about how to use the Amap API in vue3vue2 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 using vue3, 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

模块的引入

  • 首先导入的方式,和官网一样,后面我会贴完整代码, 这里我们使用 plugins 加载插件, 其他配置如 Loca, 直接进行配置, 这里需要注意版本问题, 写成  ‘2.0’ 是不行的,初始化函数在 onmounted 生命周期中执行。
  • AMap存储 这里我做了很多存储,大家知道 .value  的语法是 vue3 获取 ref 的语法,我下面使用到的 都是ref,后面完整代码可以查看, 这里挂载的时候直接存一下,因为很多工具方法都会只用到他,这里后期业务逻辑我会抽离到 pinia中去,所以不需要在初始化函数中写全部的业务逻辑。
  • 模版样式不生效问题, 我们在使用的时候, 就像我之前写的文章,点位新增的时候,我们会插入 content 字符串模版,替换点样式,这里有两种方案修改样式,一种是 插入 DOM ,不使用字符串,然后在 DOM 上通过 style 直接修改样式,另一种就是使用模版的时候直接给 class 类名,但是这种样式如果我们给 vuestyle 加了 scoped 就不会生效,这里大家可以自己灵活选择用哪种,我这里暂时先使用模版的方式,去掉了 scoped
  • 图例, 图例这里除了导入的时候,需要配置一下,使用上来说变化不大,样式的修改还是复用了我之前的逻辑。
import AMapLoader from '@amap/amap-jsapi-loader'

const initMap = () => {
  AMapLoader.load({
    key: 'b59c490f61a694b9d7576dd864f74d6e', // 申请好的Web端开发者Key,首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.MouseTool'], // 需要使用的的插件列表,如比例尺'AMap.Scale'等
    Loca:{
      version:'2.0.0'
    }
  })
    .then((res) => {      
      AMap.value = res
      // 上来就显示的中心点  北京 116.397, 39.918
      var lnglat = new res.LngLat(105, 38)
      map.value = new res.Map('container', {
        //设置地图容器id
        viewMode: '3D', //是否为3D地图模式
        zoom: 5, //初始化地图级别
        center: lnglat, //初始化地图中心点位置
      })
      map.value.clearMap() // 清除地图覆盖物
      // 地图是否可拖拽和缩放
      map.value.setStatus({
        dragEnable: true, // 是否可拖拽
        zoomEnable: true, // 是否可缩放
      })

      initWindow()
      // 添加一些分布不均的点到地图上,地图上添加三个点标记,作为参照
      coordData.forEach(function (marker) {
        setMarker(marker)
      })

      let renderLine = setLine(coordData)
      // 设置线
      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]) // 绘制线
      //创建右键菜单
      menuInstance.value = new ContextMenu(map.value)
      let loca = new Loca.Container({
          map:map.value,
      });
      window._loca = loca;

      // 图例, 图例可以实例化多个,使用定位来设置位置
      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: '省级管道', color: headColors[1] },
              { label: '县级管道', 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()
})

右键菜单

右键菜单, 右键菜单这里官方给我们的示例是使用一个 函数 进行实例化,里面使用了 this, 所以这个我单独拿出来,首先我们看一下官方的 demo

Lets talk about how to use the Amap API in vue3

  • 这里使用了一个函数,但这个函数还不是类,但是他却在里面使用了this,实话来讲,这种写法确实不是很优秀,可扩展性很差,不够健壮,但没办法,谁让我们用了人家的东西呢是吧, 在 vue3 中这么用就不可以了,首先 vue3 里面使用 this 就不是官方建议的, 另外这里面还修改了函数原型上的方法,其实我得代码里面一共有两种右键菜单,如下:

Lets talk about how to use the Amap API in vue3

Lets talk about how to use the Amap API in vue3
一种是在指定点位上打开,另一种是在非点位的空白处打开,指定点位处打开的其实叫信息窗体,只不过是通过右键的方式触发,那个没有上面这个右键菜单麻烦。

  • 首先来说 this 问题, 这里的 this 实际上就是把我们的实例化对象挂载到上面而已,vue3 中没办法像 vue2 那样使用 this, 但也提供给我们了 api 来获取当前组件的实例化对象, 然后我没用使用函数, 使用了一个类,类构造这个方法, 模版也不适用字符串模版,因为这里字符串模版的事件绑定写死了,我们使用 DOM 来动态绑定事件,代码如下:
const { ctx } = getCurrentInstance()
const _this = ctx
//自定义菜单类
class ContextMenu {
  constructor(map) {
    var me = _this
    //地图中添加鼠标工具MouseTool插件
    _this.mouseTool = new AMap.value.MouseTool(map)
    _this.contextMenuPositon = null
    const fragment = document.createElement(&#39;div&#39;) // 使用 DOM 方式, 方便添加事件
    fragment.className = &#39;info context_menu&#39;
    const p = document.createElement(&#39;p&#39;)
    p.addEventListener(&#39;click&#39;, this.delMarkerMenu)
    p.textContent = &#39;移除上次选中信息&#39;
    fragment.appendChild(p)
    //通过content自定义右键菜单内容
    _this.contextMenu = new AMap.value.ContextMenu({
      isCustom: true,
      content: fragment,
    })
    //地图绑定鼠标右击事件——弹出右键菜单
    map.on(&#39;rightclick&#39;, function (e) {
      me.contextMenu.open(map, e.lnglat)
      me.contextMenuPositon = e.lnglat //右键菜单位置
    })
  }
  delMarkerMenu() {
    // 右键菜单上次选中点的信息
    clearPoint()
    _this.mouseTool.close()
    _this.contextMenu.close()
  }
}

完整代码




  • 这里的业务逻辑还不完善, 输入部分的交互逻辑没有完成, 这个文件直接引入自己的项目,安装一下上面说过的依赖, 就可以使用,不过这里数据源需要自己根据自己的数据来构造就可以了,我引入的事 data 中的一组假数据,在这里给大家两组看一下
export const coordData = [
  {
    name: &#39;黑龙江&#39;,
    position: [127, 47],
    pointData: {
      out: 100,
      provide: 10,
    },
    line: [
      {
        current: [
          [127, 47],
          [126, 43],
        ],
        type: 1,
      },
    ],
  },
  {
    name: &#39;吉林&#39;,
    position: [126, 43],
    pointData: {
      out: 120,
      provide: 11,
    },
    line: [
      {
        current: [
          [126, 43],
          [113, 41],
        ],
        type: 1,
      },
    ],
  },
 ]
  • 后面我会把业务逻辑抽离到 pinia 中, 并且完善ts类型, 大家对哪一部分有疑问或者更好的解决方案可以留言一起学习~

(学习视频分享:vuejs入门教程编程基础视频

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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?May 13, 2025 pm 04:05 PM

Vue.js' VirtualDOM is both a mirror of the real DOM, and not exactly. 1. Create and update: Vue.js creates a VirtualDOM tree based on component definitions, and updates VirtualDOM first when the state changes. 2. Differences and patching: Comparison of old and new VirtualDOMs through diff operations, and apply only the minimum changes to the real DOM. 3. Efficiency: VirtualDOM allows batch updates, reduces direct DOM operations, and optimizes the rendering process. VirtualDOM is a strategic tool for Vue.js to optimize UI updates.

Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool