vue項目中使用高的地圖vue-map,帶標註、點擊選址和搜索功能

第一步:安裝依賴

npm install vue-amap --save

第二步:在main.js中

import AMap from "vue-amap";
Vue.use(AMap);
AMap.initAMapApiLoader({
  key: "開發者申請的key", 
  plugin: ["AMap.Scale", "AMap.OverView", "AMap.ToolBar", "AMap.MapType"],
  uiVersion: "1.0.11", // ui庫版本,不配置不加載,
  v: "1.4.4"
});

第三步:在demo.vue中使用

                <el-amap 
                  ref="map" 
                  vid="amapDemo" 
                  :amap-manager="amapManager" 
                  :center="center" 
                  :zoom="zoom" 
                  :plugin="plugin" 
                  :events="events" 
                  class="amap-demo">
                  <el-amap-marker vid="amapDemo" :position="center"></el-amap-marker>
                </el-amap>
import AMap from "vue-amap";
let amapManager = new AMap.AMapManager();
data(){
    return{
      amapManager,
      zoom: 12,
      center: [121, 31],
      events: {
        init: o => {
          console.log(o.getCenter());
          // console.log(this.$refs.map.$$getInstance());
          o.getCity(result => {
            console.log(result);
          });
        },
        moveend: () => {},
        zoomchange: () => {},
        click: e => {
          console.log(e);
          this.center = [e.lnglat.lng, e.lnglat.lat];//點擊選擇新地址爲中心點
          const msg = {
            key: "您申請的key值",
            location: this.center.join()
          };
          this.$$.ajax({
            url: "https://restapi.amap.com/v3/geocode/regeo",
            data: msg,
            success: data => {
              console.log(data);
              let d = data.regeocode;
              if (d) {
                this.address = d.formatted_address;//點擊選擇新地址並獲取地址的名稱
              }
            }
          });
        }
      },
      plugin: [
        "ToolBar",
        {
          pName: "MapType",
          defaultType: 0,
          events: {
            init(o) {
              console.log(o);
            }
          }
        }
      ],
    }
}

⚠️注意:

附:amap搜索建議:

    const msg = {
        key: "你申請的key值",
        keywords: this.address
      };    
    this.$http
        .get("https://restapi.amap.com/v3/assistant/inputtips", {
          params: msg,
          withCredentials: false //一定要加這個,不然會報跨域的錯(如果你封裝的$http沒有設置withCredentials:true就不用加這行)
        })
        .then(res => {
          console.log(res.data);
          let data = res.data;
          this.tips = data.tips;
        })
        .catch(error => {
          this.$message.error(error);
        });

附:vue-amap官網

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章