1. 程式人生 > 程式設計 >vue-amap安裝和用法步驟

vue-amap安裝和用法步驟

之前分享了非同步載入高德地圖api的用法,現在記錄一下-amap的用法。

vue-amap是餓了麼開源的一套基於 Vue 2.0 和高德地圖的地圖元件。 資料狀態與地圖狀態單向繫結,開發者無需關心地圖的具體操作。

官方文件:https://elemefe..io/vue-amap/

步驟如下:

1.npm 安裝

npm install vue-amap --save

如果是CDN方式,目前可通過unpkg.com/vue-amap獲取最新版本的資源。

<script src="https://unpkg.com/vue-amap/dist/index."></script>

2.使用例項

例項需求描述:搜尋並選擇地址,選中後地圖定位到該地址,並獲取經緯度自動填入下方的輸入框中。

vue-amap安裝和用法步驟

注:例項中使用的框架是ElementUI,其表單元件使用比較方便。

實現步驟:

(1)安裝後在main.js中設定以下內容:

import VueAMap from "vue-amap";
Vue.use(VueAMap);
// 初始化vue-amap
VueAMap.initAMapApiLoader({
  key: "your key",// 這裡寫你申請的高德地圖的key
  plugin: ["AMap.Autocomplete","AMap.Geocoder","AMap.Geolocation"],yJKRW
v: "1.4.15",uiVersion: "1.1" });

(2)定義地圖搜尋元件 base/mapSearch/baseMapSearch.vue

<template>
  <div>
    <div class="search-box">
      <el-input
        v-model="searchKey"
        type="search"
        id="search"
        placeholder="請輸入詳細地址"
      ></el-input>
      <!--<button @click="searchByHand">搜尋</button>-->
      <div class="tip-box" id="searchTip"></div>
    </div>
    <!--
      amap-manager: 地圖管理物件
      vid:地圖容器節點的ID
      zooms: 地圖顯示的縮放級別範圍,在PC上,預設範圍[3,18],取值範圍[3-18];在移動裝置上,預設範圍[3-19],取值範圍[3-19]
      center: 地圖中心點座標值
      plugin:地圖使用的外掛
      events: 事件
    -->
    <div class="amap-box">
      <el-amap
        :amap-manager="amapManager"
        :vid="'amap-vue'"
        :zoom="zoom"
        :plugin="plugin"
        :center="center"
        :events="events"
      >
        <!-- 標記 -->
        <el-amap-marker
          v-for="(marker,index) in markers"
          :position="marker"
          :key="index"
        ></el-amap-marker>
      </el-amap>
    </div>
  </div>
</t
emplate> <script> import { AMapManager,lazyAMapApiLoaderInstance } from "vue-amap"; let amapManager = new AMapManager(); export default { props: ["city","value","longitude","latitude","isEdit"],data() { let self = this; return { 客棧 address: null,searchKey: "",amapManager,markers: [],searchOption: { city: this.city ? this.city : "全國",citylimit: true },center: [121.329402,31.228667],zoom: 17,lng: 0,lat: 0,loaded: false,events: { init() { lazyAMapApiLoaderInstance.load().then(() => { self.initSearch(); }); },// 點選獲取地址的資料 click(e) { self.markers = []; let { lng,lat } = e.lnglat; self.lng = lng; self.lat = lat; self.center = [lng,lat]; self.markers.push([lng,lat]); // 這裡通過高德 SDK 完成。 let geocoder = new AMap.Geocoder({ radius: 1000,extensions: "all" }); geocoder.getAddress([lng,lat],function(status,result) { if (status === "complete" && result.info === "OK") { if (result && result.regeocode) { self.address = result.regeocode.formattedAddress; self.searchKey = result.regeocode.formattedAddress; self.$emit("updateLocation",lng,lat,self.searchKey); self.$nextTick(); } } }); } },// 一些工具外掛 plugin: [ { // 定位 pName: "Geolocation",events: { init(o) { // o是高德地圖定位外掛例項 o.getCurrentPosition((status,result) => { if (result && result.position) { if (self.isEdit) { // 設定經度 self.lng = self.longitude; // 設定維度 self.lat = self.latitude; // 設定座標 self.center = [self.longitude,self.latitude]; self.markers.push([self.longitude,self.latitude]); } else { // 設定經度 self.lng = result.position.lng; // 設定維度 self.lat = result.position.lat; // 設定座標 self.center = [self.lng,self.lat]; self.markers.push([self.lng,self.lat]); } // load self.loaded = true; // 頁面渲染好後 self.$nextTick(); } }); } } } ] }; },created() { if (this.value) { this.searchKey = this.value; this.address = this.value; } if (this.longitude && this.latitude) { this.lng = this.longitude; this.lat = this.latitude; this.center = [this.longitude,this.latitude]; this.markers.push([this.longitude,this.latitude]); } },methods: { // 選擇地址後自動定位到當前地址附近 updateAddress(value,longitude,latitude) { this.searchKey = value; this.address = value; this.lng = longitude; this.lat = latitude; this.center = [longitude,latitude]; this.markers.push([longitude,latitude]); },initSearch() { let vm = this; let map = this.amapManager.getMap(); AMapUI.loadUI(["misc/PoiPicker"],function(PoiPicker) { let poiPicker = new PoiPicker({ input: "syJKRWearch",placeSearchOptions: { map: map,pageSize: 10 },suggestContainer: "searchTip",searchResultsContainer: "searchTip" }); vm.poiPicker = poiPicker; // 監聽poi選中資訊 poiPicker.on("poiPicked",function(poiResult) { let source = poiResult.source; let poi = poiResult.item; if (source !== "search") { poiPicker.searchByKeyword(poi.name); } else { poiPicker.clearSearchResults(); vm.markers = []; let lng = poi.location.lng; let lat = poi.location.lat; let address = poi.name; // poi.cityname + poi.adname + poi.name vm.center = [lng,lat]; vm.markers.push([lng,lat]); vm.lng = lng; vm.lat = lat; vm.address = address; vm.searchKey = address; vm.$emit("updateLocation",vm.searchKey); } }); }); },searchByHand() { if (this.searchKey !== "" && this.poiPicker) { this.poiPicker.searchByKeyword(this.searchKey); } } } }; </script> <style lang="stylus"> .search-box { margin-top: 6px; width: 100%; } .search-box input { padding: 0 15px; width: 100%; height: 32px; line-height: 32px; color: #606266; border: 1px solid #dcdfe6; border-radius: 4px; } .search-box input:focus { border-color: #409eff; outline: 0; } .search-box input::-webkit-input-placeholder { color: #c0c4cc; } .tip-box { width: 100%; max-height:280px; position: absolute; top: 72px; z-index: 10000; overflow-y: auto; background-color: #fff; } </style> <style> .amap-ui-poi-pick程式設計客棧er-sugg,.amap_lib_placeSearch { border: 1px solid #eee; border-radius: 4px; } .amap-box { height: 200px; } </style>

這裡樣式使用了stylus,可自行轉換其他樣式。

(3)在元件中使用地圖搜尋元件,這裡以彈窗為例

<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :before-close="handleClose"
    width="600px"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="form-info">
      <el-form
        :model="form"
        ref="form"
        :rules="rules"
        size="small"
        label-width="110px"
      >
        <el-form-item label="選擇地址" prop="address">
          <base-map-search
            ref="mapSearch"
            :city="form.city"
            :value="form.address"
            :longitude="form.addLon"
            :latitude="form.addLat"
            :isEdit="isEdit"
            @updateLocation="updateLocation"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="addLon" label="經度">
              <el-input
                v-model.number="form.addLon"
                :maxlength="15"
                placeholder="請輸入經度"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="right-label-form-item">
            <el-form-item prop="addLat" label="緯度">
              <el-input
                v-model.number="form.addLat"
                :maxlength="15"
                placeholder="請輸入緯度"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </el-dialog>
</template>
<script>
import BaseMapSearch from "../base/mapSearch/baseMapSearch";
export default {
    props: ["visible","isEdit","detail"],components: {
      BaseMapSearch
    },data() {
        return {
            title: "新增地址",form: {
                address: "",addLon: "",addLat: ""
            },rules: {
                address: [
                  {
                    required: true,message: "請輸入地址",trigger: ["blur","change"]
                  }
                ],addLat: [
                  {
                    required: true,message: "請輸入緯度",addLon: [
                  {
                    required: true,message: "請輸入經度",}
        };
    },created() {
      if (this.isEdit) {
        this.initForm();
      }
    },methods: {
        // 初始化表單
        initForm() {
          this.title = "修改地址";
          if (this.detail) {
            this.form = { ...this.detail };
          }
        },// 地圖搜尋選址
        updateLocation(lng,address) {
          this.form.addLon = lng;
          this.form.addLat = lat;
          this.form.address = address;
        },handleClose() {
          this.$emit("update:visible",false);
        }
    }
};
</script>

(4)這時,如果專案中使用了ESlint,會報AMap、AMapUI未定義的錯誤,我們需要在.eslintrc.js檔案中定義globals屬性:

module.exports = {
    // ...
    globals: {
      AMap: false,AMapUI: false
    }
};

這樣就寫好了,效果如圖:

vue-amap安裝和用法步驟

到此這篇關於vue-amap安裝和使用的文章就介紹到這了,更多相關vue-amap安裝和使用內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!