Vue项目中使用高德地图

Vue的项目中经常会使用到地图的相关功能这里我们就搭建一个脚手架,引入高德地图
index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title>belineamap</title>
    <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script> 
  </head>
  <body>
    <noscript>
      <strong>We're sorry but belineamap doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

在首页的页面中引入高德地图.
由于此次写的demo采用的Vue-Cli3.0的脚手架,webpack的配置需要在项目根目录单独建立一个vue.config.js

module.exports = {
  devServer: {
    port: 8011 // 端口号配置
  },
  configureWebpack: {
    externals: {
      'AMap': 'AMap' // 高德地图配置
    }
  }
}

这时我们重启项目,并在页面中给地图一个加载位置,初始化地图后就可以看到地图了

<template>
  <div class="home">
    <h1>这里是首页</h1>
    <div id="amap" class="mapbox"></div>
  </div>
</template>

<script>
export default {
  name: 'home',
  mounted () {
    map = new AMap.Map('amap', {
      center: [104.05523, 30.561469],
      resizeEnable: true,
      zoom: 15
    })
  },
}
</script>
<style lang="css" scoped>
.mapbox {
  margin: 0 auto;
  width: 400px;
  height: 400px;
}
</style>

虽然页面正确加载了地图,并且按照我们的配置,把中心点进行了修改,但是我们发现console中依然会报一个错

image.png

此时只需要在index.html的页面定义一个变量map即可消除报错

<body>
  <noscript>
    <strong>We're sorry but belineamap doesn't work properly without JavaScript enabled. Please enable it to
      continue.</strong>
  </noscript>
  <div id="app"></div>
  <!-- built files will be auto injected -->
  <script>
    // 用于消除map未定义错误
    var map
  </script>
</body>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容