Recently, I have been engaged in the development of wechat official account project on mobile terminal. This is the first time for me to use VUE to develop mobile terminal project. I have accumulated little mobile terminal development experience in the early stage. Through the exercise of the project, to deepen the understanding and using of vue related knowledge, at the same time, involved in the project WeChat API (WeChat share WeChat pay), baidu map API (how to instantiate the map, add custom mulch to map, add custom annotation to the map, the map to zoom in, drag and drop, etc.) related to use, Broaden their horizons of knowledge; Now I will develop the process of accumulation of relevant experience to share with you, hope to learn and progress with you….

  • Vux: Use of Vue mobile UI component library;

  • Vue-lazyload: an easy to use plug-in for vue image lazy loading;

  • Vuex: Introduction to vUE status management tool.

  • Async /await: An asynchronous artifact to wrap the interface request file fetch. Js

  • Iterative judgment skills in VUE projects;

  • Introduction of images commonly used in VUE projects;

  • Application of wechat API in VUE project:

    1. Vue2 can share pit points and experience with wechat;

    2. Vue2 realized wechat payment pit point and experience;

  • Application of Baidu Map API in VUE project:

    1. How to use Baidu Map API in VUe2.0 project

    2. Vue2 how to add housing overlay to the map;

    3. How to add custom positioning control to the map and change the control icon;

    4. How to add custom current location annotation to map

    5. Several commonly used API (map zoom, drag, get the current location) and other functions;

Use of VUX-VUE mobile UI component library;

About VUX: For details, see the official documentation.

As a mobile terminal project of wechat public account, we compared several vuejs mobile terminal UI libraries and learned that VUX is a mobile terminal UI component library developed based on WeUI and Vue(2.x), which mainly serves wechat pages. Although it is personal maintenance, the experience needs some improvement. However, the use of several components in the project greatly improved the development efficiency.

The usage method is as follows:

  • Install – vux:
npm install vux --save
Copy the code
Matters needing attention:

Vux2 must cooperate vux – loader use, please in the build/webpack base. Conf. Refer to the following code configured in js: Vux2 must cooperate vux – loader use, please in the build/webpack base. Conf. Refer to the following code configured in js:

const vuxLoader = require('vux-loader')
const webpackConfig = originalConfig // The original module.exports code was assigned to the webpackConfig variable

module.exports = vuxLoader.merge(webpackConfig, {
  plugins: ['vux-ui']})Copy the code
  • Take swiper as an example

If the component you want to use is only for use in the current page, we can just introduce it in the current page. If it is used in many pages, it can be referenced globally in main.js. Use components as follows:

 <template>
    <swiper auto loop :interval="interval" :duration="duration" id="swiper-banner"
            class="swiper-banner"
            :height="height">  
        <swiper-item 
                class="swiper-demo-img"
                v-for="(item, index) in bannerList"
                :key="index">
                    <img :src="item.img">
        </swiper-item>
    </swiper>
 </template>

 <script>
   import { Swiper, SwiperItem } from "vux";

   export default {
        name: "swiper",
        data() {
            interval:4000.// Rotation retention time
            duration:300// Toggle the animation time
            height:"10.19 rem." "./ / height
            bannerList:[
                {img: 'https://static.vux.li/demo/1.jpg'.title: 'Here's a fua for you'},
                {img: 'https://static.vux.li/demo/5.jpg'.title: 'flower'}}}]</script>
Copy the code

Property auto, which defaults to false and indicates whether auto multicast is enabled. Property loop, which defaults to false, indicating whether to loop;

Vue-lazyload: an easy-to-use plug-in for lazy loading of Vue images

Official website: Vue-Lazyload

Vue-lazyload is mainly used for image lazy loading. Contains the following features:

  • Compact and lightweight, powerful and easy to use
  • Can be used to load any image type
  • Vue 1.0 and Vue 2.0 are supported

Understand image lazy loading:

When there are too many pictures in a webpage, due to network reasons, all the pictures will not be displayed immediately when you visit the webpage, resulting in network delay loading, which affects user experience. But we can implement vue-lazyLoad plug-in in the picture loading process, first display the default loading picture, until the picture is fully displayed, the default picture disappeared, so that will greatly improve the user experience.

The usage method is as follows:

1. Install through NPM

npm install vue-lazyload -s
Copy the code

2. Reference in main.js

import Vue from 'vue' import App from './App.vue' import VueLazyload from 'vue-lazyload' Vue.use(VueLazyload, {preLoad: 1.3, // Ratio of preLoad height error: '.. /assets/img/no-pic. PNG ', // Error icon loading failed: '.. /assets/ imgloading. PNG ', // Loading icon attempt: 1 // number of loading attempts})Copy the code

3. Use in components

<img v-lazy="item.picUrl" alt="">

Copy the code

4. After the effect is implemented, the function can be extended according to the API.

You can set corresponding parameters by referring to the official API.

5, vue – the lazyLoad file, please refer to: vue2 – plugs – demo project in SRC/components/the lazyLoad/index. The vue and SRC/main. Js parts;;

Vuex: Introduction to vUE status management tool.

Vuex is introduced:

For details, please refer to the official website. Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way. When should I use Vuex? If you need to build a medium to large single-page application, you’re probably thinking about how to better manage state outside of components, and Vuex would be a natural choice. Usage:

  • Install vuex:
npm install vuex --save
Copy the code
  • Referenced in mins.js:
import Vuex from "vuex";
Vue.use(Vuex);
Copy the code

Understand the five basic objects of VUex:

  • State: storage status. That’s variables;

  • Getters: Derived state. Get, as in set and get, takes two optional arguments: state and getters, which get variables in state and other getters, respectively. External call: store.getters. PersonInfo (). It’s like computed in Vue;

  • Mutations: Submit a status change. This is the only way to change state in VUEX, but asynchronous operations are not supported. The first parameter defaults to state. External call: store.com MIT (‘SET_AGE’, 18). Similar to methods in VUE.

  • Actions: Similar to mutations. However, Actions supports asynchronous operations. The first parameter defaults to an object with the same parameter properties as store. External call: store.dispatch(‘nameAsyn’).

  • Modules: a submodule of store, whose content is equivalent to an instance of store. The call is similar to the previous one, but with the name of the current submodule, such as Store.a.getters.xxx ().

Vue-cli Indicates the vuex mode

In general, vuE-CLI is used for the actual development. In VUe-CLI, the development and invocation are slightly different.

├ ─ ─index.html├ ─ ─main.js├ ─ ─components└ ─ ─store├ ─ ─index.js# We assemble the module and export itstoreThe place where ├ ─ ─state.js# With the levelstate├ ─ ─getters.js# With the levelgetter├ ─ ─mutation-types.js# root levelmutationsName (officially recommendedmutionsMethod names in uppercase) ├─mutations.js# root levelmutation├ ─ ─actions.js# root levelaction└ ─ ─modules├ ─ ─index.js# Module Set Exercises ─m1.js# Module 1 ├─m2.js# module 2Copy the code

State. Js sample:

const state = {
    name: 'weish',
    age: 22
};

export default state;
Copy the code

Getters.js example (we usually use getters to get the state of state, not state directly) :

export const name = (state) => { return state.name; } export const age = (state) => { return state.age } export const other = (state) => { return `My name is ${state.name},  I am ${state.age}.`; }Copy the code

The mutation type.js example (we will include all mutations function names in this file) :

export const SET_NAME = 'SET_NAME';
export const SET_AGE = 'SET_AGE';
Copy the code

Mutations. Js sample:

import * as types from './mutation-type.js'; export default { [types.SET_NAME](state, name) { state.name = name; }, [types.SET_AGE](state, age) { state.age = age; }};Copy the code

Examples of actions.js (asynchronous operation, multiple commit) :

import * as types from './mutation-type.js'; export default { nameAsyn({commit}, {age, name}) { commit(types.SET_NAME, name); commit(types.SET_AGE, age); }};Copy the code

Modules /m1.js example, same with m2. (If the application is not very complex, it is generally not divided into modules) :

export default {
    state: {},
    getters: {},
    mutations: {},
    actions: {}};Copy the code

Modules /indes. Js to centrally manage modules files as follows:

import m1 from './m1';
import m2 from './m2';

export default {
  m1,
  m2
}

Copy the code

Index.js example (assemble vuex) :

// If the state management operation is very frequent in the project, the state management objects can be subdivided, and finally collected and centralized management; import vue from 'vue' import vuex from 'vuex' import state from './state' import * as getters from './getters' import mutations from './mutations' import actions from './actions' import modules from './modules' vue.use(vuex) export default new vuex.Store({ state, getters, mutations, actions, modules })Copy the code

Finally, mount the Store instance to vue in main.js

import store from './store';

new Vue({
  el: '#app',
  store,
  render: h => h(App)
});
Copy the code

When used in vUE components, we usually use mapGetters, mapActions, and mapMutations, and then we can call these variables or functions in the same way that Vue calls methods and computed, as shown in the following example:

import {mapGetters, mapMutations, mapActions} from 'vuex'; /* Write only the script part of the component */ export default {computed: {... mapGetters([ name, age ]) }, methods: { ... MapMutations ({setName: 'SET_NAME', // map this.setname () to this.setName() for this.store.mit ('SET_NAME') setAge: 'SET_AGE'}),... MapActions ([nameAsyn // map this.nameasyn () to this.$store.dispatch('increment')])}};Copy the code

The use of mapGetters, mapMutations, and mapActions is analogous to referring defined state management data (variables, functions) to computed and methods in vUE objects. How to use, for example: Get variables in computed:

this.name;
this.age;
Copy the code

Get variables in methods:

Enclosing elegantly-named setName (this name); // Map to 'this.store.com MIT ('setName', this.name)' this.setage (); this.nameAsyn();Copy the code

Conclusion:

1, if the project, the use of state management operation is very frequent, can undertake segmentation will state management objects, such as to distinguish between different objects folder (state, getters, mutations, the actions, modules), after the last collection centralized management;

2. If a few variables of state management are used in the project, a file can be used for centralized management;

For the vuEX project, please refer to the SRC/Store and SRC /store2 sections in vuE2-PLUGS – Demo.

Async /await: An asynchronous artifact to wrap the interface request file fetch. Js

In the project development with the separation of the front end and the back end, if the front end personnel want to obtain the back end data through the interface, we will generally independently encapsulate their own interface asynchronous request methods, so that they can be easily referenced in the whole project.

Async /await is used in the project to handle asynchronous requests, encapsulating methods (utils/fetch.js) as follows:

export default async (url = '', data = {}, type = 'POST', Method = 'fetch') => {type = type.toupperCase () // Get request requires url and parameter restitching if (type === 'get ') {let dataStr =" Object.keys(data).forEach(key => { dataStr += key + '=' + data[key] + '&' }) if (dataStr ! == '') { dataStr = dataStr.substr(0, dataStr.lastIndexOf('&')) url = url + '? If (window.fetch &&method === 'fetch') {let requestConfig = {if (window.fetch &&method === 'fetch') {if (window.fetch &&method === 'fetch') { credentials: 'include', method: type, headers: { 'Accept': 'application/json; charset=UTF-8', 'Content-Type': 'application/json; Charset =UTF-8'}, mode: 'cors', cache: 'force-cache'} // 'POST' request, add related request parameters to 'body'. if (type === 'POST') { Object.defineProperty(requestConfig, 'body', { value: Json.stringify (data)})} // await fetch with synchronous data (JSON form); try { const response = await fetch(url, requestConfig) const responseJson = await response.json() return responseJson } catch (error) { throw new Error(error) } } else {// If the fetch syntax is not supported by the browser, use ES6 promise() to encapsulate the asynchronous interface request; return new Promise((resolve, reject) => { let requestObj if (window.XMLHttpRequest) { requestObj = new XMLHttpRequest() } else { let ActiveXObject = window.ActiveXObject requestObj = new ActiveXObject() } let sendData = '' if (type === 'POST') { sendData = JSON.stringify(data) } requestObj.open(type, url, true) requestObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded') requestObj.send(sendData) requestObj.onreadystatechange = () => { if (requestObj.readyState === 4) { if (requestObj.status === 200) { let obj = requestObj.response if (typeof obj ! == 'object') { console.log(obj) obj = JSON.parse(obj) } resolve(obj) } else { reject(requestObj) } } } }) } }Copy the code

For example, the API used for login is centrally managed in login/ API /index.js, as follows:

import fetch from "@/utils/fetch"; /** * login */ export const login = (reqData) => FETCH ("/v2/cotton/user/app_login", reqData);Copy the code

After the API unified management is completed, we need to call in the page to obtain data, the method is as follows:

import { getyancode, login } from "./api"; Methods: {async login() {// Commit; if (this.checkMobile() && this.checkMsgCode()) { this.loading.show = true; let reqData = { phone: mutils.replaceAllSpace(this.telphone), code: mutils.replaceAllSpace(this.yancode) }; Try {// try{}catch(){} const res = await login(reqData); If (res.status.code == "200") {console.log(' interface request succeeded ~'); } else {console.log(' interface request failed ~'); } }catch(err){ console.log(err) } } } }Copy the code

Through the asynchronous interface request, we can get the relevant data and start the subsequent operation. Analysis of the encapsulation method of asynchronous interface request: async/await is used to send asynchronous request and get data from the server. The code is very simple, and async/await has been standardized. The use of async as a keyword in front of a function to indicate that the function is asynchronous, which means that the execution of the function does not block the execution of subsequent code. Such as:

async function timeout() { return 'hello world' } timeout(); Console. log(' I'll do it first, though I'll do it later ');Copy the code

Async returns a Promise object. If we want to get a promise, we should use then methods, such as:

async function timeout() { return 'hello world' } timeout().then(result => { console.log(result); }) console.log(' I'll do it first, though later ');Copy the code

Execution Result:

I'll do it later, but I'll do it firsthello world
Copy the code

Async and await are used together. Await means to wait. Note that await keyword can only be placed inside async function. Now let’s write a function that returns a Promise object that multiplies the number by 2 after 2s.

Function doubleAfter2seconds(num) {return new Promise(resolve, resolve) reject) => { setTimeout(() => { resolve(2 * num) }, 2000); })}Copy the code

Now write an async function so that you can use the await keyword. After await is an expression that returns a Promise object, so it can be followed by a call to the doubleAfter2seconds function.

async function testResult() {
    let result = await doubleAfter2seconds(30);
    console.log(result);
}
Copy the code

Now call the testResult function

testResult(a); The result is 60Copy the code

Of course we need to do exception handling when we use async/await interface request. It uses a try/catch to catch an exception, executes an await in the try, and uses a catch if there is an exception.

For the fetch. Js file, please refer to the utils/fetch. Js and SRC /login sections in vue2-PLUGS – Demo project;

Iterative judgment techniques in VUE projects

Let’s say we have a list, and we want to show the one that we’re currently selecting, how do we do that? The basic idea is to use $index to determine if it is the current iteration, and then add or subtract class or style to implement different styles.

<template> <ul> <! - method 1 class - > < li v - for = "item in the list:" class = "{' active ': $index = = = activeId}" > {{item}} < / li > <! < span style=" backgroundColor: $index === activeId? 'red' : 'white'}">{{item}}</li> </ul> </template> <script> data () { return { list: ['a', 'b', 'c'], activeId: 0 } } </script>Copy the code

A common way to introduce images in VUE projects

  1. Use the image in the IMG tag
data () {
    return {
        img: require('path/to/your/source')
    }
}
Copy the code

Then in template:

<img :src="img" />
Copy the code
  1. Use images as background images
data () { return { img: require('path/to/your/source') } } <div :style="{backgroundImage: 'url(' + img + ')'}"></div> background-image: url('path/to/your/source');Copy the code

Application of wechat API in VUE project:

  • Vue2 can share pit points and experience with wechat;

Official website: wechat public platform technical documentation/wechat JS-SDK documentation

Of course, the development of wechat public account should be carried out. In the early stage, users should register and bind relevant accounts to get the relevant permissions given by wechat official website, and then the subsequent development process and API call can be carried out. For the main steps, please refer to the technical documents of wechat public account. I’m just here to show you how to call the API after the registration process is complete.

As I am engaged in the front-end project development of wechat public account Vue2.0, there are some customized sharing functions and designs in the project according to the product needs. Because the sharing of wechat is relatively common, it has its own sharing mechanism and just presents a certain page normally. To customize sharing, we need to call wechat sharing API and customize configuration.

Share to wechat friends and QQ friends, the effect is shown in the picture:

Share to wechat moments, the effect is as shown in the picture:

The development steps are as follows:

1. Introduce jweixin-1.2.0.js in index. HTML;

< script type = "text/javascript" SRC = "http://res.wx.qq.com/open/js/jweixin-1.2.0.js" > < / script >Copy the code

2. Relevant wechat API configuration file utils/wx.js, as follows:

import fetch from "./fetch"; /** * baseUrl: server address * shareOosImg: share default icon * wechatId: Successful wechatId * * / import {baseUrl, shareOosImg wechatId} from "@ / utils/env"; /** * Get wechat signature, */ export const getCompactHouseList = (reqData) => FETCH ("/v2/cotton/user/get_wechat_authorize", reqData); */ export const getCompactHouseList = (reqData) => FETCH ("/v2/cotton/user/get_wechat_authorize", reqData); export function setWxConfig(link, title, desc, pic) { let url = window.location.href.split("#")[0]; WechatId: wechatId: wechatId: wechatId: wechatId: wechatId: wechatId getCompactHouseList({ "wechatId": wechatId, "url": url }).then((res) => { if (res.status.code == 200) { let wxConfigObj = res.result.parment; let myLink = link ? link : ""; let myTitle = title ? Title: "Xiaoai Technology "; let Mydesc = desc ? Desc: "What a surprise! Lots of discounts!" ; let mypic = pic ? pic : shareOosImg; wxConfig(wxConfigObj, myLink, myTitle, Mydesc, mypic); } }).catch((err) => { console.log(err); }); }; Function wxConfig(wxConfigObj, link, title, desc, PIC) {// Initialize the configuration. Wx. config({debug: false, // Enable the debug mode, the return value of all API calls will be alert in the client, to view the passed parameters, can be opened in the PC, parameter information will be printed in the log, only on the PC. Timestamp: wxconfigobj. timestamp, // Mandatory, generated signature's timestamp nonceStr: Wxconfigobj. noncestr, // Mandatory, random string to generate signature signature: wxconfigobj. signature, // Mandatory, signature jsApiList: ["checkJsApi","onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ","chooseWXPay", "chooseImage"] List of JS interfaces to use}); Wx.ready (() => {// Share to friends wx.onmenushareTimeline ({title: title, // Share the title link: ImgUrl: PIC, // share icon Success: function () {// alert(" share your friends successfully "); }}); Wx. onMenuShareAppMessage({title: title, // share the title desc: desc, // Share the description link: ImgUrl: PIC, // Share icon type: "", // Share type,music, video, or link. The default is link dataUrl: Function () {function () {function () {function () {function () {function () {function () { }}); // Share to QQ wx.onMenuShareQQ({title: title, // Share title desc: desc, // Share description link: link, // share link imgUrl: PIC, // Share icon success: Function () {// Callback performed after user confirms sharing}, cancel: function () {// Callback performed after user cancels sharing}}); Wx.checkjsapi ({jsApiList: ['chooseImage'], // checkJsApi({jsApiList: ['chooseImage'], // checkJsApi({jsApiList: ['chooseImage'], // checkJsApi {"checkResult":{"chooseImage":true},"errMsg":"checkJsApi: OK "}}}); }); wx.error(() => { }); }; Export function chooseWXPay(data, This) {// pay wx.chooseWXPay({timestamp: Data. timeStamp, // Payment signature timeStamp, note that all used timeStamp fields in wechat JSSDK are lowercase. NonceStr: data.nonceStr, // Payment signature random string, not longer than 32 bits package: Data. package, // The prepay_id parameter value returned by the unified payment interface. The submission format is as follows: prepay_id=\*\* *) signType: SignType, // Signature mode, default is 'SHA1', to use the new version of payment need to pass 'MD5' paySign: data.paySign, // payment signature success: function (res) { This.$router.push({ path: "/myReserve", query: { "reserve": "reservation" } }); }}); }; Export function chooseImage(callback) {wx. ChooseImage ({count: 6, // default 9 sizeType: ['original', 'compressed'], // select sourceType: ['album', 'camera'], // select sourceType: ['album', 'camera'] function (res) { callback(res); }}); }Copy the code

3. Use the following reference in main.js:

import Vue from "vue";
import * as wx"@ /utils/wx";
Vue.use(wx);
Copy the code

3. Reference sharing methods in the page

** Note: ** If this page, we want to share out content, is designed by product content, need to call the share method in the method; If we don’t care about the content of sharing on this page, we don’t need to call the configured sharing method, and the default is the sharing provided by wechat.

This.wx.setWxConfig(' ${baseUrl}/tuijianDetail '," Lots of discounts! Recommend friends to pay attention to the red envelope ~");Copy the code

In this way, you can use the sharing function in the upper right corner of wechat to see the content you want after you successfully share it.

  • Vue2 realized wechat payment pit point and experience;

Similarly, wechat Pay requires access to the wechat pay API. Since the wechat Pay API is triggered when we click a button, there is no need to write it in wx.ready(() => {}).

  1. The same method is defined in wx.js:
Export function chooseWXPay(data, This) {// pay wx.chooseWXPay({timestamp: Data. timeStamp, // Payment signature timeStamp, note that all used timeStamp fields in wechat JSSDK are lowercase. NonceStr: data.nonceStr, // Payment signature random string, not longer than 32 bits package: Data. package, // The prepay_id parameter value returned by the unified payment interface. The submission format is as follows: prepay_id=\*\* *) signType: SignType, // Signature mode, default is 'SHA1', to use the new version of payment need to pass 'MD5' paySign: data.paySign, // payment signature success: function (res) { This.$router.push({ path: "/myReserve", query: { "reserve": "reservation" } }); }}); };Copy the code
  1. The page calls as follows:
this.wx.chooseWXPay(res.result.list.This);
Copy the code

After the payment is successful, jump to other pages through routing;

** Note: ** wechat API successful verification, must be an external address (can access the server address), if you use your own address, put on the mobile phone test, it will not succeed.

Application of Baidu Map API in VUE project:

Official website, sample demo, reference class.

In the recent development of the project, maps will be used to display the housing data of relevant urban areas, so I choose Baidu Map.

Baidu Map JavaScript API is a set of application programming interface written by JavaScript language, which can help you build a rich and interactive map application in the website. It supports PC and mobile browser based map application development, and supports HTML5 features of map development. Baidu Map JavaScript API support HTTP and HTTPS, free of charge, can be used directly. The number of times the interface can be used is unlimited.

  • How to use Baidu Map API in VUe2.0 project

Before using the API, you need to register a Baidu account, apply to become a Baidu developer, and obtain the service key (AK) to use the relevant service functions.

The development steps are as follows:

1. To apply for baidu account and AK, click me to apply

According to the HTML standard, every HTML document should declare the correct document type. We recommend that you use the latest DOCUMENT declaration that complies with the HTML5 specification:

 <!DOCTYPE html>
Copy the code

3. Adapt to mobile page display

Let’s add a meta tag to make your pages look good on mobile platforms.

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />  
Copy the code

Set the container style size so that the map fills the browser window:

<style type="text/css"> html{height:100%} body{height:100%; margin:0px; padding:0px} #container{height:100%} </style>Copy the code

5. Reference baidu Map API file in index. HTML

< script type = "text/javascript" SRC = "http://api.map.baidu.com/api?v=3.0&ak= your key" > < / script >Copy the code

A map needs an HTML element as a container so it can be displayed on the page. Here we create a div element.

<div id="container"></div> 
Copy the code

A Map class in the BMap namespace represents a Map. You can create an instance of a Map using the new operator. The argument can be an element ID or an element object.

var map = new BMap.Map("container"); 
Copy the code

8. Set the center point coordinates

Var point = new map.point (116.404, 39.915);Copy the code

After creating the Map instance, we need to initialize it. The bmap.map.centerandZoom () method requires setting the center coordinates and Map level. The map must be initialized to perform other operations.

map.centerAndZoom(point, 15);  
Copy the code

At this point, we quickly created a map centered on Tiananmen square

  • Vue2 how to add housing overlay to the map;

As shown in figure:

After the map is initialized, we need to customize the related methods to add overlay.

Customize annotations or map coverings according to official documentation. Specific implementation code, we can be developed according to the official API.

First, you need to define the constructor for your custom Overlay. You can pass some free variables through the constructor argument. Set the prototype property of the custom Overlay object to an instance of the Overlay to inherit the Overlay base class.

Function SquareOverlay(center, length, color){this._center = center; his._length = length; this._color = color; Overlay SquareOverlay. Prototype = new Overlay. Overlay();Copy the code

2. Initialize custom coverings

Implement the Initialize method, which is called by the API when the map.addOverlay method is called. When the map.addOverlay method is called to add a custom overlay, the API calls the initialize method of the object to initialize the overlay. During initialization, the DOM elements needed to create the overlay are added to the map container. Here we choose to add to the container markerPane.

/ / implementation initialization method SquareOverlay. Prototype. The initialize = function (map) {/ / save the map object instance ihs. _map = map; Var div = document.createElement("div"); // Create a div element as a container for custom coverings. div.style.position = "absolute"; Div. Style. width = this._length + "px"; div.style.height = this._length + "px"; div.style.background = this._color; // Add div to the overlay container map.getpanes ().markerpane.appendChild (div); // save the div instance this._div = div; // The div element is required as the return value of the method, which is manipulated by the API when the show and // hide methods of the cover are called, or when the cover is removed. return div; }Copy the code

3. Draw the covering

Implement the DRAW method. So far, we’ve only added the overlay to the map, but we haven’t put it in the right place. You need to set the position of the overlay in the DRAW method, which is called by the API whenever the state of the map changes (e.g. position shift, level change) and is used to recalculate the position of the overlay. The map.pointtooverLayPixel method converts geographic coordinates to the required pixel coordinates of the overlay.

/ / implementation drawing method SquareOverlay. Prototype. The draw = function () {/ / according to geographical coordinate transformation for pixel coordinates, Var position = this._map.pointtooverLayPixel (this._center); var position = this._map.pointtooverLayPixel (this._center); this._div.style.left = position.x - this._length / 2 + "px"; this._div.style.top = position.y - this._length / 2 + "px"; }Copy the code

When calling map.removeOverlay or map.clearOverlays, the API will automatically remove the DOM elements returned from the Initialize method.

map.removeOverlay(a);Copy the code

You have now written a complete custom overlay and are ready to add it to the map.

Var map = new map. map ("container"); Var point = new map.point (116.404, 39.915); map.centerAndZoom(point, 15); Var mySquare = new SquareOverlay(map.getCenter(), 100, "red"); map.addOverlay(mySquare);Copy the code
  • How to add custom positioning control to the map and change the control icon;

To add custom controls to the map, you need to use the control class ZoomControl, using the following method:

addControlLocation(){ var that = this; Function function ZoomControl(){// Set the default docking position and offset this.defaultAnchor = BMAP_ANCHOR_BOTTOM_LEFT; this.defaultOffset = new BMap.Size(20, 50); Control zoomControl. prototype = new map.control (); ZoomControl. Prototype. The initialize = function (map) {/ / create a DOM element var img = document. The createElement method (" img "); Img. setAttribute(' SRC ', thate.locationimg) // Set the style img.style.cursor = "pointer"; Img. onclick = function(e){... } // Add DOM elements to the map map.getContainer().appendChild(img); // return DOM element img; Var myZoomCtrl = new ZoomControl(); This.mp. addControl(myZoomCtrl); }Copy the code

After the map is initialized, call the addControlLocation() method;

  • Add a custom current location annotation

As shown in figure:

Need to use new map.marker (); Set the icon size with myicon.setimagesize ();

Var myIcon = new map.icon (this.redLocation,{offset: New map. Size(10, 25), imageOffset: new map. Size(0, 0-10 * 25) // set imageOffset}); // myIcon.setStyle({width: '.666rem', height: '.666rem'}); MyIcon. SetImageSize (new BMap. Size (60, 60)); / / set the icon size let point = new BMap. Point (enclosing currentPoint, LNG, enclosing currentPoint. Lat); // Let marker = new bmap.marker (point,{icon:myIcon}); // create Marker this.mp.addOverlay(Marker); // Add current registration point},Copy the code
  • Several commonly used API (map zoom, drag, get the current location) and other functions;
  1. Map surface trigger click event:
This.mp. addEventListener(" TouchStart ", () => {});Copy the code
  1. Map zooming event:
This.mp. addEventListener(" zoomEnd ", () => {}); this.mp.adDeventListener (" zoomEnd ", () => {});Copy the code
  1. Map drag event:
This. Mp. AddEventListener (" dragstart ", () = > {}); This. Mp. AddEventListener (" dragend ", () = > {});Copy the code
  1. Get the user’s current location (latitude and longitude object) :
export function getLocationData(fn) { let geolocation = new BMap.Geolocation(); geolocation.getCurrentPosition(function (r) { if (this.getStatus() == BMAP_STATUS_SUCCESS) { fn(r.point); }}); }Copy the code
  1. Parse address information according to latitude and longitude, and return provincial and urban streets respectively:
let gc = new BMap.Geocoder(); GetLocation (item, function (rs) {//getLocation (item, function (rs)) {//getLocation (item, function (rs)); Let addComp = rs.addressComponents; let province = addComp.province; Let city = addcomp.city; // Get city});Copy the code

Project practice: Based on vue2.0 + VUEX + Element-UI background management system

Welcome to join the discussion group, together to learn to use vue, vuex, element, express, directing to build the background management system;

Let’s use the project to deepen our understanding of knowledge.