vue-amap installation and usage steps

vue-amap installation and usage steps

I have previously shared the usage of asynchronously loading the Amap API. Now I will record the usage of vue-amap.

vue-amap is an open source map component based on Vue 2.0 and Amap developed by Ele.me. The data status is one-way bound to the map status, and developers do not need to worry about the specific operations of the map.

Official documentation: https://elemefe.github.io/vue-amap/

Here are the steps:

1. npm installation

npm install vue-amap --save

If using CDN, you can currently obtain the latest version of resources through unpkg.com/vue-amap.

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

2. Use Case

Instance requirement description: Search and select an address. After selecting it, the map will locate the address and obtain the longitude and latitude and automatically fill them in the input box below.

Note: The framework used in the example is ElementUI, and its form components are relatively easy to use.

Implementation steps:

(1) After installation, set the following in main.js:

import VueAMap from "vue-amap";
Vue.use(VueAMap);
// Initialize vue-amap
VueAMap.initAMapApiLoader({
  key: "your key", //Write the key of the Amap you applied for here
  plugin: ["AMap.Autocomplete", "AMap.Geocoder", "AMap.Geolocation"],
  v: "1.4.15",
  uiVersion: "1.1"
});

(2) Define the map search component base/mapSearch/baseMapSearch.vue

<template>
  <div>
    <div class="search-box">
      <el-input
        v-model="searchKey"
        type="search"
        id="search"
        placeholder="Please enter the detailed address"
      ></el-input>
      <!--<button @click="searchByHand">Search</button>-->
      <div class="tip-box" id="searchTip"></div>
    </div>
    <!--
      amap-manager: map management object vid: ID of the map container node
      zooms: The zoom level range of the map display. On PC, the default range is [3,18] and the value range is [3-18]. On mobile devices, the default range is [3-19] and the value range is [3-19].
      center: coordinate value of the center point of the map plugin: plugin used by the map events: events -->
    <div class="amap-box">
      <el-amap
        :amap-manager="amapManager"
        :vid="'amap-vue'"
        :zoom="zoom"
        :plugin="plugin"
        :center="center"
        :events="events"
      >
        <!-- Tags -->
        <el-amap-marker
          v-for="(marker, index) in markers"
          :position="marker"
          :key="index"
        ></el-amap-marker>
      </el-amap>
    </div>
  </div>
</template>
<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 : "National",
        citylimit: true
      },
      center: [121.329402, 31.228667],
      zoom: 17,
      lng: 0,
      lat: 0,
      loaded: false,
      events: {
        init() {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initSearch();
          });
        },
        // Click to get the address data click(e) {
          self.markers = [];
          let { lng, lat } = e.lnglat;
          self.lng = lng;
          self.lat = lat;
          self.center = [lng, lat];
          self.markers.push([lng, lat]);
          // This is done through Amap 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();
              }
            }
          });
        }
      },
      // Some tool plug-ins plugin: [
        {
          // Position pName: "Geolocation",
          events: {
            init(o) {
              // o is the Amap positioning plug-in instance o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  if (self.isEdit) {
                    // Set longitude self.lng = self.longitude;
                    // Set the dimension self.lat = self.latitude;
                    // Set the coordinates self.center = [self.longitude, self.latitude];
                    self.markers.push([self.longitude, self.latitude]);
                  } else {
                    // Set longitude self.lng = result.position.lng;
                    // Set the dimension self.lat = result.position.lat;
                    // Set the coordinates self.center = [self.lng, self.lat];
                    self.markers.push([self.lng, self.lat]);
                  }
                  // load
                  self.loaded = true;
                  //After the page is rendered 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: {
    // After selecting an address, automatically locate near the current address 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: "search",
          placeSearchOptions: {
            map: map,
            pageSize: 10
          },
          suggestContainer: "searchTip",
          searchResultsContainer: "searchTip"
        });
        vm.poiPicker = poiPicker;
        // Listen for poi selected information 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", lng, lat, 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-picker-sugg,
.amap_lib_placeSearch {
  border: 1px solid #eee;
  border-radius: 4px;
}
.amap-box {
  height: 200px;
}
</style>

The style here uses stylus, and you can convert other styles by yourself.

(3) Use the map search component in the component. Here we take the pop-up window as an example.

<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="Select address" 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="Longitude">
              <el-input
                v-model.number="form.addLon"
                :maxlength="15"
                placeholder="Please enter longitude"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="right-label-form-item">
            <el-form-item prop="addLat" label="Latitude">
              <el-input
                v-model.number="form.addLat"
                :maxlength="15"
                placeholder="Please enter latitude"
              ></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: "Add address",
            form: {
                address: "",
                addLon: "",
                addLat: ""
            },
            rules:
                address:
                  {
                    required: true,
                    message: "Please enter the address",
                    trigger: ["blur", "change"]
                  }
                ],
                addLat: [
                  {
                    required: true,
                    message: "Please enter the latitude",
                    trigger: ["blur", "change"]
                  }
                ],
                addLon: [
                  {
                    required: true,
                    message: "Please enter longitude",
                    trigger: ["blur", "change"]
                  }
                ],
            }
        };
    },
    created() {
      if (this.isEdit) {
        this.initForm();
      }
    },
    methods: {
        // Initialize the form initForm() {
          this.title = "Modify address";
          if (this.detail) {
            this.form = { ...this.detail };
          }
        },
        // Map search location updateLocation(lng, lat, address) {
          this.form.addLon = lng;
          this.form.addLat = lat;
          this.form.address = address;
        },
        handleClose() {
          this.$emit("update:visible", false);
        }
    }
};
</script>

(4) At this time, if ESlint is used in the project, an error will be reported that AMap and AMapUI are not defined. We need to define the globals property in the .eslintrc.js file:

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

This is written, the effect is as shown below:

This is the end of this article about the installation and use of vue-amap. For more relevant vue-amap installation and usage content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • The most complete vue vue-amap uses the Amap plug-in to draw polygon range sample code
  • vue uses the Amap component process analysis

<<:  Docker Consul Overview and Cluster Environment Construction Steps (Graphical Explanation)

>>:  Thumbnail hover effect implemented with CSS3

Recommend

Radio buttons and multiple-choice buttons are styled using images

I've seen people asking before, how to add sty...

Linux MySQL root password forgotten solution

When using the MySQL database, if you have not lo...

Summary of 3 minor errors encountered during MySQL 8.0 installation

Preface In the past, the company used the 5.7 ser...

How to dynamically modify container port mapping in Docker

Preface: Docker port mapping is often done by map...

MySQL database architecture details

Table of contents 1. MySQL Architecture 2. Networ...

Instructions for nested use of MySQL ifnull

Nested use of MySQL ifnull I searched online to s...

WeChat applet implements a simple dice game

This article shares the specific code of the WeCh...

HTML unordered list bullet points using images CSS writing

Create an HTML page with an unordered list of at l...

Example code of CSS layout at both ends (using parent's negative margin)

Recently, during the development process, I encou...

CSS3 frosted glass effect

If the frosted glass effect is done well, it can ...

Docker practice: Python application containerization

1. Introduction Containers use a sandbox mechanis...

Detailed explanation of the basic use of react-navigation6.x routing library

Table of contents react-native project initializa...

A detailed discussion of components in Vue

Table of contents 1. Component Registration 2. Us...

MySQL slow query optimization: the advantages of limit from theory and practice

Many times, we expect the query result to be at m...