Amap is used in Vue projects

In some simple large-screen display applications/web pages, map-related display scenes are often used. Except for some special 3D scenes that need Gis/BIM or WebGL, some simple businesses can be directly completed by Using Autonavi or Baidu Map.

This article mainly describes the way to reference autonavi JavaScript API in Vue project and the use of some simple API.

Demo project Use Vue CLI 4.0 scaffolding to build the project.

1. Reference

Before amap 2.0 was released, there were usually only two generic ways to load amAP, either by adding script tags directly to the header of public/index.html, or asynchronously when needed, passing in callback functions.

1.1 index.htmlAdded directly

// This method must be introduced in head<script src="' the key of your own application for https://webapi.amap.com/maps?v=1.4.13&key="></script>
Copy the code

This is a JavaScript file that downloads AMap before the page loads and creates an AMap object under the Window object.

1.2 vue.config.jsThe introduction of

module.exports = {
    // ...
    chainWebpack: function(config) {
        config.plugin("html").tap(args= > {
            const cdn ={
                css: [].js: [
                    "' the key of your own application for https://webapi.amap.com/maps?v=1.4.13&key="."/ / webapi.amap.com/ui/1.0/main.js"]}// Determine the environment
            if (process.env.NODE_ENV === "production") {
                args[0].cdn = cdn;
            }
            if (process.env.NODE_ENV === "development") {
                args[0].cdn = cdn;
            }
            returnargs; })},configureWebpack: function(config) {
        config.externals = {
        	AMap: "AMap"}}}Copy the code

This approach is similar to the direct introduction of public/index.html, where the corresponding address is inserted in the header of the entry page when developing and publishing production environments.

1.3 Asynchronous Import

Asynchronous references can reduce the rendering time of the home page, but if you need to render the map directly when the home page loads, there is no performance improvement.

Write asynchronous load methods

Start by creating a load file called remoteloadamap.js under SRC /utils/.

export function loadAMap(key, loadUI = true, version = "2.0") {
    return new Promise((resolve, reject) = > {
        if(! key) {throw new Error("Key cannot be empty");
        }
        if (window.AMap) {
            return resolve(window.AMap);
        }
        const src = `https://webapi.amap.com/maps?v=${version}&key=${key}&callback=onAMapLoad`;
        const script = document.createElement("script");
        script.onerror = () = > {
          return reject();
        };
        script.src = src;
        document.head.appendChild(script);
        window.onAMapLoad = async() = > {if (loadUI) {
                await loadAMapUI();
            }
            resolve(window.AMap); }})}export function loadAMapUI() {
	return new Promise((resolve, reject) = > {
        if (window.AMapUI) {
            return resolve(window.AMapUI);
        }
        const script = document.createElement("script");
        script.src = "https://webapi.amap.com/ui/1.1/main.js";
        document.head.appendChild(script);
        script.onload = () = > {
            return resolve(window.AMapUI);
        };
        script.onerror = () = > {
            return reject();
        };
    });
}
Copy the code

1.4 the officialloaderloading

After AMap released V 2.0, a JSAPI Loader was also provided to load amap.js asynchronously.

It is recommended to use

1.4.1 installation

npm install @amap/amap-jsapi-loader --save
// or
yarn add @amap/amap-jsapi-loader --save
Copy the code

1.4.2 use

Directly introduced and initialized in the script section of the amap. vue file.

import AMapLoader from '@amap/amap-jsapi-loader';

export default {
    name: "AMap".beforeCreate() {
        AMapLoader.load({
            "key": "".// The obtained Web developer Key is required when the load is invoked for the first time
            "version": "1.4.15".// Specify the version of JSAPI to load, which is 1.4.15 by default
            "plugins": [].// List of plug-ins to use, such as Scale' amap.scale 'etc
            "AMapUI": {             // Whether to load AMapUI
            	"version": '1.1'.// AMapUI defaults to 1.1
            	"plugins": []// The AMapUI UI plug-in needs to be loaded
            },
            "Loca": {               // Whether to load Loca
            	"version": '1.3.2'  // Loca version, default 1.3.2
            }
        }).then( AMap= > {
            this.$nextTick(() = > this.initMap(AMap));
        }).catch(e= > {
        	console.error(e); })},methods: {
        initMap(AMap) {
            this.map = new AMap.Map("container");
            // or use $refs to get the node
            // this.map = new AMap.Map(this.$refs.container);}}}Copy the code

Either way, you end up adding an object attribute, AMap, under the Window object

2. Use

You need to make sure that amap.js has been loaded before initialization. You are advised to check whether the AMap attribute exists in the window.

2.1 Initializing map instances

// template
<div class="amap" ref="map-container"></div>

// script
<script>
window.AMap && (const map = new window.AMap.Map(this.$ref["map-container"]));
</script>

Copy the code

2.2 Asynchronously loading map plug-ins

In addition to preloading plug-ins directly when initializing the map, you can also load plug-ins asynchronously where they need to be called.

A. Synchronize preloading plug-ins

When referencing the AMap API, you can pass in the name of the plug-in you want to use directly after the address as a parameter.

// 1. public.html
<script type="text/javascript" src="Https://webapi.amap.com/maps?v=2.0&key= you for applying to the key value of & plugin = AMap. The ToolBar, AMap. Driving"></script>

// 2. AMapLoader
<script>
import AMapLoader from '@amap/amap-jsapi-loader';

export default {
    name: "AMap".beforeCreate() {
        AMapLoader.load({
            "key": "".// The obtained Web developer Key is required when the load is invoked for the first time
            "version": "1.4.15".// Specify the version of JSAPI to load, which is 1.4.15 by default
            "plugins": [].// List of plug-ins to use, such as Scale' amap.scale 'etc
            "AMapUI": {             // Whether to load AMapUI
            	"version": '1.1'.// AMapUI defaults to 1.1
            	"plugins": ["AMap.ToolBar"."AMap.Driving"]        // The AMapUI UI plug-in needs to be loaded
            },
            "Loca": {               // Whether to load Loca
            	"version": '1.3.2'  // Loca version, default 1.3.2
            }
        }).then( AMap= > {
            this.$nextTick(() = > this.initMap(AMap));
        }).catch(e= > {
        	console.error(e); })},methods: {
        initMap(AMap) {
            this.map = new AMap.Map("container");
            // or use $refs to get the node
            // this.map = new AMap.Map(this.$refs.container);}}}</script>
Copy the code

B. Load the plug-in asynchronously

AMap’s AMap prototype provides the method amap.plugin () for asynchronously loading plug-ins.

The amap.plugin takes two parameters: the first parameter is the name of the plug-in to load or an array of plug-in names, and the second parameter is the callback function to execute after loading.

var map = new AMap.Map('container', {zoom:12.center: [116.39.39.9]});// A single plug-in
AMap.plugin('AMap.ToolBar'.function(){// Load the plug-in asynchronously
    var toolbar = new AMap.ToolBar();
    map.addControl(toolbar);
});

// Multiple plug-ins
AMap.plugin(['AMap.ToolBar'.'AMap.Driving'].function(){// Asynchronously load multiple plug-ins simultaneously
    var toolbar = new AMap.ToolBar();
    map.addControl(toolbar);
    var driving = new AMap.Driving();// Driving route planning
    driving.search(/ * * /)});Copy the code

C. List of available plug-ins

The name of the class Class Function description
AMap.ElasticMarker Flexible point markers, markers that can change style and size with the map level
AMap.ToolBar Toolbar to control map zooming, panning, etc
AMap.Scale Scale, displays the scale in the center of the current map
AMap.HawkEye Eagle eye, display thumbnails
AMap.MapType Layer switching, for several commonly used layer switching display
AMap.Geolocation Location provides a method to obtain the user’s current exact location and city
AMap.AdvancedInfoWindow Advanced information form, integrated peripheral search, route planning function
AMap.AutoComplete Input prompt, provides the function of obtaining prompt information according to the keyword
AMap.PlaceSearch Location search services, providing keyword search, peripheral search, scope search and other functions
AMap.DistrictSearch Administrative query service, which provides information based on the name keyword,citycode,adcodeTo query administrative information function
AMap.LineSearch Bus route service, providing bus route related information query service
AMap.StationSearch Bus station query service, providing information such as bus route and station location
AMap.Driving The driving route planning service provides the function of driving routes according to the starting and ending points
AMap.TruckDriving Truck route planning
AMap.Transfer Bus route planning service provides the function of starting and ending bus routes
AMap.Walking The walking route planning service provides the function of starting and ending the walking route
AMap.Riding Cycle route planning service provides the function of starting and ending cycle routes
AMap.DragRoute Drag and drop navigation plug-in, you can drag up the end point, passing point to re-plan the route
AMap.ArrivalRange Bus arrival circle, according to the coordinates of the starting point, the length of time to calculate whether the bus trip is reachable and the reachable range
AMap.Geocoder Geocoding and inverse geocoding services provide translation between addresses and coordinates
AMap.CitySearch The city access service obtains the city information of the user or queries the city information according to the given IP parameter
AMap.IndoorMap Indoor map, used to display the indoor map in the map
AMap.MouseTool Mouse tool plug-in
AMap.CircleEditor Circular editor plug-in
AMap.PolygonEditor Polygon editing plug-in
AMap.PolylineEditor Polyline editor
AMap.MarkerCluster Point aggregation plug-in
AMap.RangingTool Ranging plug-in, can be measured with distance or area
AMap.CloudDataSearch Cloud search service, according to the keyword search cloud point information
AMap.Weather Weather forecast plug-in, used to get future weather information
AMap.RoadInfoSearch Road information query, stopped data update, feedback information for reference only
AMap.HeatMap Thermal map plug-in

2.3 Map life cycle

  1. Create:const map = new AMap.Map("container")
  2. When the map resource is loaded, it will triggercompleteEvents:map.on("complete", () => {})
  3. Destruction:map.destroy()After execution, the map object is destroyed, freeing memory

3. Map

Map object class, encapsulating the map attribute setting, layer change, event interaction interface class.

See amap.map for parameters and method details

3.1 parameter

const map = new AMap.Map(div: (String| HTMLDivElement), opts? : MapOptions);Copy the code
  1. Div: When the parameter type is String, the DOM node whose ID is equal to the parameter value is searched internally.

  2. Opts: indicates the map initialization parameters.

Opts :MapOptions Main parameters are as follows:

Name Description
center: ([Number, Number] | LngLat) Initial central longitude and latitude
zoom: Number Map display zoom level, can be set to floating point number; If center and level are not specified, the city range of the user is displayed during map initialization by default.
rotation: Number = 0 The value ranges from 0 to 360. Default value: 0
pitch: Number = 0 The pitching Angle is 0 by default, and the maximum value increases continuously according to the current zoom level of the map, which is invalid under 2D maps.
viewMode: String = '2D' Map view mode, default is’ 2D ‘, optional ‘3D’, select ‘3D’ to display THE 3D map effect.
features: Array<String> = ['bg','point','road','building'] Set the type of elements displayed on the map, supporting ‘BG’, ‘point’, ‘road’, ‘building’
layers: Array<Layer> Map layer array, the array can be one or more layers, the default is normal two-dimensional map. When you stack multipleThe layer, the ordinary two-dimensional map needs to be instantiated by oneTileLayerClass implements. If you want to create a default base layer, useAMap.createDefaultLayer()
Zooms: [Number, Number] = [2,20] Zoom level range displayed on the map, default is [2, 20], value range is [2 ~ 20]
dragEnable: Boolean = true Whether the map can be dragged and panned by mouse. Default is true. This property can besetStatus/getStatusMethods to control
zoomEnable: Boolean = true Whether the map is zoomable. The default value is true. This property can besetStatus/getStatusMethods to control
jogEnable: Boolean = true The default value is true. This property can besetStatus/getStatusMethods to control
pitchEnable: Boolean = true Whether the pitching Angle can be set. The value is true in 3D view and invalid in 2D view.
mapStyle: String Set the display style of the map, currently support two map styles: the first: custom map style, such as”amap://styles/d6bf8c1d69cea9f5c696185ad4ac4c86“You can go to the map custom platform to customize your own personalized map style; Second: official style templates, such as”amap://styles/grey“. Instructions for other template styles and custom maps can be found in the development guide
rotateEnable: Boolean = true Whether the map is rotatable, the graph defaults to true
showBuildingBlock: Boolean = true Whether to display map 3D block, default true
`skyColor: String Array`

3.2 methods

Name Description Parameters Return
resize() Recalculate the container size
setCenter() Reset the center point ` center: number [] LngLat; “Central latitude and longitude”<br />immediately: boolean = false; “Is the target location immediately located (no animation)?”<br />duration? : number; “Transition animation duration, in ms” ‘
setZoom() Rescale Zoom: number; "Map zoom level"

immediately: boolean = false; "Is the target location immediately located (no animation)?"

duration? : number; "Transition animation duration in ms"
setZoomAndCenter() Reset the center point and zoom ` center: number [] LngLat; “Central latitude and longitude”<br />Zoom: number; “Map zoom level”<br />immediately: boolean = false; “Is the target location immediately located (no animation)?”<br />duration? : number; “Transition animation duration, in ms” ‘
getCenter() Gets the current center point LngLat
getZoom() Gets the current scale hierarchy digits: Number; "Small digit accuracy at zoom level, default 2" number
getSize() Gets the map container size {width: number; height: number}
getContainer() Get the map container DOM HTMLElement
addLayer() Add a map layer layer: Layer
setLayers() Replaces the current map layer layers: Layers[]
getLayers() Gets the current map layer Layer[]
setZooms() Gets the map zoom level range zooms: [number, number]
getZooms() Resets the map zoom level range
setMapStyle() Sets the display style of the map mapstyle: string
getMapStyle() Gets the display style of the map
getAllOverlays() Gets all added overlay objects type? : stringincludingMarker, polygonEtc., all types of coverings are returned by default Overlays[]
setFitView() Automatically zoom the map to the appropriate view level according to the distribution of added coverings on the map, parameters can be default. overlays (Array<Overlay>)mulch

immediately (Boolean = false)Whether to transition immediately

avoid (Array < Number > = [60,60,60,60])Four perimeter distance, up, down, left, right

maxZoom (Number = CoreMap.defaultZooms[1])Maximum zoom level
Bounds
clearMap() Remove all overlay from the map
destory() Destruction of the map

3.3 event

Name Description
complete Event triggered after map resource is loaded
resize Map container size change event
click Left mouse click event
dblclick Double-click the left mouse button
mapmove Trigger event when map pans
movestart Triggered when map panning starts
moveend Triggered when the map moves, including panning, and zooming for center point changes. If the map has a drag effect, it will trigger after the end of the drag effect
zoomchange Triggered when map zoom level changes
zoomstart Triggered when scaling starts
zoomend Triggered when scaling ends
rightclick Right mouse click event
dragstart Triggered when you start dragging the map
dragging Triggered during map dragging
dragend Triggered when stopping dragging maps. If the map has a drag effect, it will trigger before the drag stops and the drag starts
touchstart Trigger event when touch starts, mobile device only
touchmove Triggered during map dragging. Only applicable to mobile devices
touchend Trigger event at the end of touch, mobile device only