vue项目引入原生高德地图报错'AMap' is not defined的解决方法

21,618 阅读1分钟

由于工作上的需要,今天下午捣鼓了下高德地图。

如果定制化开发需求不太高的话,可以用vue-amap,这个我就不多说了,详细就看官网 elemefe.github.io/vue-amap/#/…

因为我们公司需要一些其他的定制化开发需求,然后就只用原生的高德。

其实原生的引入也不复杂,但是有几个坑要填一下。

1. index.html

注意,引入的高德js一定要放在头部而不是尾部,否则就会报 “AMap is not defined”。这个坑我踩了好久!网上找了其他文章也都都没有提到这一点。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>demo</title>
    <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=YOURKEY"></script>
  </head>

2. webpack.base.conf.js

在module.exports = {}里加入

externals: {
  'AMap': 'AMap'
},

3. 引用高德的那个页面

<template>
  <div class="hello">
    <div style="height:500px" id="container" tabindex="0"></div>
  </div>
</template>

<script>
import AMap from 'AMap'
</script>