vue3使用高德地图JSAPI2.0(超详细)

2,890 阅读1分钟

最近使用 vue3 + vite + ts 开发的PC项目中有使用到地图的需求,这里说明下如何简答的引入高德地图的插件

官网(点击跳转) 有自带说明如何使用vue3调用高德地图的 JS API

按 npm 方式安装使用 Loader

npm i @amap/amap-jsapi-loader --save

注意这里需要使用到 官方给的key(点击跳转) 然后登录或者注册平台获取对应的密匙(点击跳转) 注意如果需要 2.0 安全密钥必须要有 注意如果需要 2.0 安全密钥必须要有

这里推荐使用按需引入的方式获取高德地的@amap/amap-jsapi-loader 【因为地图模块比较大在自己使用的地方按需引入即可】 index.vue

<script setup lang="ts">
import { load } from '@amap/amap-jsapi-loader'
import { ref, onMounted, reactive } from 'vue'

const mapRef = ref() // 对应地图渲染的 ref 元素 <div ref="mapRef" />
const mapApiKey = reactive({
	securityJsCode: '「你申请的安全密钥」', // 注意如果需要 2.0 mapApiKey.securityJsCode 必填
	key: '' // 申请好的Web端开发者Key,首次调用 load 时必填
})
const map = ref()

const initMapView = async () => {
  try {
    window._AMapSecurityConfig = {
	  securityJsCode: mapApiKey.securityJsCode
	}
	map.value = await load({
	  key: mapApiKey.key,
	  version: '2.0',  // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
	  plugins: ['AMap.Scale'] //需要使用的的插件列表,如比例尺'AMap.Scale',支持添加多个如:['...','...']
	})
	new map.value.Map(mapRef.value, {
        viewMode: '3D', // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        center: [106.603408, 29.531952],
        resizeEnable: true
      })
  } catch (error) {
	console.log(error)	
  }
}

onMounted(() => {
  initMapView()
})
</script> 

<template>
	<div ref="mapRef" style="width: 500px; height: 500px" />
</template>

这样就初始化了一个最基本的地图,后续如果想要使用更多的功能点击跳转查看官方示例

后续如果需要对应示例留言下

<script setup lang="ts">
// 如果加如新的官方插件,需要在plugins: ['AMap.Scale']对应添加
	map.value = await load({
	  key: mapApiKey.key,
	  version: '2.0',
	  plugins: [
          'AMap.Scale',
          'AMap.PlaceSearch',
          'AMap.Autocomplete',
          'AMap.LngLat',
          'AMap.Geocoder',
          'AMap.PolylineEditor'
      ]
	})
</script>