Using AMap Component in Vue3

Using AMap Component in Vue3

​ In this article, I’ll introduce how to combine amap component with Vue3 and render amap component with covid data provided with API to create a Chinese covid map.

Precondition Preparation

​ First, You need sign up an account at amap official website https://lbs.amap.com. Then enter the console and apply for the developers’ permission.

​ After getting the developers’ permission, you can create a JSAPI key, which will used later.

Environment Configuration

​ Ideally, we can use the amap component amap-vue specialized for Vue. However, amap-vue is designed for Vue2 but not for Vue3. When we use amap-vue component in Vue3, we can’t use the AMap method to create and render a map component.

​ I have tried various methods mentioned in technological forum but get no correct solution. Luckily, I finally found a solution by my own. Let me have it introduced.

Get maps.js

​ The amap official demo use HTML-JavaScript to render a website, and it use CDN to import the amap dependency:

1
<script language="javascript" src="https://webapi.amap.com/maps?v=2.0&key=您申请的key值"></script>

​ Replace 您申请的key值 with the JSAPI key you have just applied. Then access https://webapi.amap.com/maps?v=2.0&key=您申请的key值, we can get a file named maps.js. This is just the JavaScript file used to render the amap component. Download the file and we will use it later.

Declare Import

​ Import the file into the Vue project’s public folder. Then announce the statement below at each Vue file requiring amap component:

1
declare let AMap: any;

​ This statement is used to declare the AMap method does exist. When it can’t find amap dependency in current file, it will found the dependency in other file, and finally find the amap dependency in maps.js. So when we use AMap method, the syntax check won’t show error.

​ Some function need additional declare for the secret key. Detailed information can be found at https://lbs.amap.com/api/jsapi-v2/guide/abc/prepare.