高德地图组件使用总结

最近项目中使用到了高德地图组件,还用到了打点功能,这里总结一下:

效果如下:

高德地图组件使用总结_第1张图片
登录进高德开放平台后可以查看相关api文档

<template>
  <div id="mapcontainer"></div>
</template>

<script setup lang="ts">
import { onMounted,  } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import emitter from "@/util/bus.js";
      interface pointer{
        lng: number
        lat: number
        name: string
      }
      let markeList = []
const init = () => {
  AMapLoader.load({
    key: "" , // 自己的key
    version: "2.0",
    plugins: ['AMap.DistrictSearch'],
  })
    .then((AMap) => {
     let map = new AMap.Map("mapcontainer", {
        mapStyle: "amap://styles/darkblue",
        center: [120.575642, 27.881179],
        zoom: 9,
      });
    let adCode = 330300;
    let depth = 2;
    let disProvince;
      function initPro(code, dep) {
        dep = typeof dep == 'undefined' ? 2 : dep;
        adCode = code;
        depth = dep;

        disProvince && disProvince.setMap(null);

        disProvince = new AMap.DistrictLayer.Province({
            zIndex: 12,
            adcode: [code],
            depth: dep,
            styles: {
                'fill': function (properties) {
                    var adcode = properties.adcode;
                    return getColorByAdcode(adcode);
                },
                'province-stroke': 'cornflowerblue',
                'city-stroke': 'white', // 中国地级市边界
                'county-stroke': 'rgba(255,255,255,0.5)' // 中国区县边界
            }
        });

        disProvince.setMap(map);
    }
    let colors = {};
    let getColorByAdcode = function (adcode) {
        if (!colors[adcode]) {
            var gb = Math.random() * 155 + 50;
            colors[adcode] = 'rgb(' + gb + ',' + gb + ',255)';
        }

        return colors[adcode];
    };
     initPro(adCode, depth)
      emitter.on("point", (res: pointer[]) => {
        if (res.length) {
          if(markeList.length){
            map.remove(markeList)
            markeList.length = 0
          }

          res.forEach((item, index) => {
            markeList.push(
              new AMap.Marker({
                position: new AMap.LngLat(item.lng, item.lat),
                title: item.name,
                icon: '/img/dot2.png'
              })
            )
          })
          map.add(markeList)
        }
      });
    })
    .catch((e) => {
      console.log(e);
    });
};

onMounted(() => {
  init();
});
</script>

<style lang="less" scoped>
#mapcontainer {
  height: 100%;
}
</style>

你可能感兴趣的:(javascript,前端,vue.js)