博主这里用了vue-admin-template作为前台模板做测试...

这里使用的是外引高德css和js的方式,因为是spa单页面应用,所以只有一个index.html,在其中添加上相关应用即可:

引入(那个key换成自己在高德申请的):

<link rel="stylesheet" href="https://cache.amap.com/lbs/static/main.css" />
    <script
      type="text/javascript"
      src="https://webapi.amap.com/maps?v=1.4.15&key=0000000key0000000&plugin=AMap.ToolBar,AMap.Marker,AMap.Driving,AMap.DistrictSearch,AMap.Autocomplete,AMap.PlaceSearch"
    ></script>

index.html 完整页面代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
    />
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
    <link rel="stylesheet" href="https://cache.amap.com/lbs/static/main.css" />
    <script
      type="text/javascript"
      src="https://webapi.amap.com/maps?v=1.4.15&key=9022bbbcf0eecf156c3e3a8592f73330&plugin=AMap.ToolBar,AMap.Marker,AMap.Driving,AMap.DistrictSearch,AMap.Autocomplete,AMap.PlaceSearch"
    ></script>
    <title><%= webpackConfig.name %></title>
  </head>
  <body>
    <noscript>
      <strong
        >We're sorry but <%= webpackConfig.name %> 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>

创建相关页面,并路由至此,地图页面代码:

<template>
  <div class="app-container">
    <div id="title">高德地图组件展示</div>
    <div id="mapsearch"></div>
    <div id="mapcontainer"></div>
    <div id="footer"></div>
  </div>
</template>
<script>
import location from "@/assets/image/location.png";
export default {
  data() {
    return {
      mapMain: null,
      lngMain: 0,
      latMain: 0,
      markerMain: null
    };
  },
  created() {},
  mounted() {
    this.initMapMain();
  },
  methods: {
    initMapMain() {
      //地图组件绑定div进行初始化并赋值给vue的对象
      this.mapMain = new AMap.Map("mapcontainer", {
        center: [this.lngMain, this.latMain], //设置显示的地图中心坐标
        zoom: 8 //设置地图缩放等级
      });
      //生成自定义的图标
      let icon = new AMap.Icon({
        image: location,
        size: new AMap.Size(25, 35),
        imageSize: new AMap.Size(25, 35)
      });
      //初始化覆盖物对象并赋值给vue对象
      this.markerMain = new AMap.Marker({
        icon: icon, //使用自定义的图标
        position: [this.lngMain, this.latMain] //覆盖物位置坐标
      });
      this.mapMain.add(this.markerMain); //添加覆盖物到地图,与下方法同效
      // this.markerMain.set(this.mapMain) //添加覆盖物到地图,与上方法同效
      this.mapMain.setFitView(); //地图缩放等级和位置等自适应,可以放置折线对象等作为形参也可以为空
    }
  }
};
</script>
<style scoped>
#mapcontainer {
  height: 300px;
  width: 500px;
  font-size: 13px;
}
</style>

使用的自定义图标:

成功加载后:

 地图展示因为坐标是0,0,加上自动缩放,所以显示的好像一片空白。其实没问题的,调节缩放后:

 地图组件的基本引用就是这样了,详细的功能都备注在了页面代码中,需要注意的是地图绑定的div一定要有宽高样式否则不能正常加载!

Logo

前往低代码交流专区

更多推荐