Some configurations of the AMap API for the first time (VUE + Autonavi JSAPI)
The official website provides relevant configuration. Here I provide my own configuration for reference only
The website address
1. Register an account and apply for a Key
See official documentation
2 Configure the key and security key
I use method 2 — “key with static security key set in plaintext” and “use Loader as NPM”
HTML version of official website:
-
Add script script
// Add proxy server setup script tag (must be before loading loader.js)<script type="text/javascript"> window._AMapSecurityConfig = { securityJsCode:'Your requested security Key',}</script>/ / load the loader. Js<script src="https://webapi.amap.com/loader.js"></script> Copy the code
-
Install the loader
npm i @amap/amap-jsapi-loader --save Copy the code
-
Using the loader
import AMapLoader from '@amap/amap-jsapi-loader'; AMapLoader.load({ "key": "".// The obtained Web developer Key is required when the load is invoked for the first time "version": "2.0".// 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 }).then((AMap) = >{ map = new AMap.Map('container'); }).catch(e= > { console.log(e); }) Copy the code
Vue version:
In the SRC folder, create the utils folder. In the utils folder, create the ode
/* JSAPI key with static security key set in plaintext (insecure, recommended only in development environment) */
import AMapLoader from '@amap/amap-jsapi-loader';
const securityJsCode = 'xxxxxxxx'; // The security key you requested
const key = 'xxxxxxxx'; // The obtained Web developer Key is required when the load is invoked for the first time
const version = '2.0'; // Specify the version of JSAPI to load, which is 1.4.15 by default
const adress = 'https://webapi.amap.com/loader.js'; // Proxy server address
window._AMapSecurityConfig = {
securityJsCode // The security key you requested
};
/** * Load map *@param {*} Plugins map configuration items *@returns promise* /
const mapLoader = plugins= >
AMapLoader.load({
key, // The obtained Web developer Key is required when the load is invoked for the first time
version, // 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
});
// Dynamically create script tags to import proxy servers
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = adress;
document.body.appendChild(script);
// Export the function used to load the map
export default mapLoader;
Copy the code
Since amaploader.load is a promise, we split the then and catch parts of it out
3. Get a map container
Official HTML version:
<div id="container"></div>
Copy the code
#container {width:300px; height: 180px; }
Copy the code
Vue version:
Create a new component mymap.vue and mount it in app.vue
<template> <div :class="$style.root"> <! <div :class="$style.container" id="container" :style="{width: width + 'px', height: Height + 'px'}"></div> </div> </template> <script> export default {data() {return {width: 1000, // 600, // map height}; }, <style lang="scss" module> .root { width: 1920px; height: 1080px; } </style>Copy the code
4. Create a Map (and show it)
Official HTML version:
var map = new AMap.Map('container', {
resizeEnable: true.// Whether to monitor map container size changes
zoom:11.// Initialize the map hierarchy
center: [116.397428.39.90923] // Initializes the map center point
});
Copy the code
Vue version:
-
Add data containers to data
data() { return { AMap: null.map: null.width: 1000.// Map width height: 600.// Map height plugins: [ 'AMap.Scale' /* Scale */.'AMap.ToolBar' /* Toolbar */.'AMap.Marker' / * marked * /.'AMap.Geolocation' / * location * /.'AMap.MapType' /* Layer switch */].// Map plugin config: { resizeEnable: true.// Map initializes to the current city (will be overwritten by Center) // center: [], // Map center point zoom: 10.// Set the zoom level of the map mapStyle: 'amap://styles/normal' // Set the display style of the map } // Map configuration items }; }, Copy the code
-
CreateMap provides a method to initialize the map
// Initialize the map async createMap() { try { // Make the map independent (to prevent the need for multiple maps), privatize an AMap in the current component this.AMap = await mapLoader(this.plugins); // The then part of the promise this.map = new AMap.Map('container'.this.config); } catch (e) { // Catch part of the promise console.log(e); }},Copy the code
-
AsnycLoaderPlugins provide methods to load multiple plug-ins asynchronously at the same time
// Asynchronously load multiple plug-ins simultaneously asnycLoaderPlugins(AMap, map, plugins) { AMap.plugin(plugins, function () { map.addControl(new AMap.Scale()); // add scale map.addControl(new AMap.ToolBar()); // Add a toolbar map.addControl(new AMap.MapType()); // Add layer toggles // map.add( // new AMap.Marker({ // position: map.getCenter(), // content: '
1/ /}) / /); // Add tags // High precision positioning highAccuracyGeolocation(AMap, map); // Add a circular overlay // map.add( // new AMap.Circle({ // center: map.getCenter(), // center position // radius: 1000, // circle radius // fillColor: 'red', // circle fillColor // strokeColor: '# FFF ', // strokeColor // strokeWeight: 2 // stroke width / /}) // ); }); Copy the code -
Export the highAccuracyGeolocation method in a separate JS file
- High precision positioning is usually used during initialization because by default only the current location is located
- The browser must have location permission enabled
- Chrome may not be able to use high precision positioning, which is available with Firefox
- See cause of official Geolocation location failure
- The main reason why the function is imported in js file is that the callback function has this pointing problem
- High-precision positioning is plug-in loading and is called in the asnycLoaderPlugins method
/** ** high precision positioning *@param {*} AMap * @param {*} map* / const highAccuracyGeolocation = (AMap, map) = > { // After initialization, locate to local (high precision positioning, Chrome will fail, Firefox can succeed) var geolocation = new AMap.Geolocation({ // Whether to use high precision positioning. Default: true enableHighAccuracy: true.// Set the locating timeout period. The default value is 5s timeout: 10000.// The offset of the location button's docking position, default: Pixel(10, 20) buttonOffset: new AMap.Pixel(10.20), // After successful positioning, adjust the map view range to make the positioning position and accuracy range visible in the view. Default: false zoomToAccuracy: true.// Locate the position of the button, RB represents the lower right buttonPosition: 'RB' }); map.addControl(geolocation); geolocation.getCurrentPosition(); geolocation.on('complete', onComplete); geolocation.on('error', onError); function onComplete(data) { // Data is specific location information console.log(data); } function onError(data) { // Location error console.log(data); }};export default highAccuracyGeolocation; Copy the code
5. Use MouseTool to draw a circle and find the area
-
Note that these plug-ins are available on the official website, see distance, length, area
-
I’m just trying to provide a method here
-
Hold down the left mouse button drag animation circle, release the left button to complete the drawing circle, right mouse button to clear the drawing circle
/** * Draw circles to get information *@param {*} AMap * @param {*} map* / function getMessageByDrawCircle(AMap, map) { map.plugin('AMap.MouseTool'.() = > { // Add the MouseTool plugin to the map const mouseTool = new AMap.MouseTool(map); // Use the mouse tool to draw a circle mouseTool.circle(); // Add events mouseTool.on('draw'.function (e) { // console.log(e.obj); if(e.obj.getRadius()===0) return console.log('Radius of the circle' + e.obj.getRadius()); // Get the radius console.log('Area of a circle' +e.obj.getArea()); // Get the area console.log('Latitude of the center of the circle' +e.obj.getCenter().getLat()); // Get the latitude of the center point console.log('Longitude of the center of a circle' +e.obj.getCenter().getLng()); // Get the longitude of the center point }); const container = document.getElementById('container'); container.oncontextmenu = function (e) { // Right click the code to execute mouseTool.close(true); getMessageByDrawCircle(AMap, map) return false; // Block the browser's default popover behavior }; }); } export default getMessageByDrawCircle; Copy the code
6. Complete code for the component
<template> <div :class="$style.root"> <! <div :class="$style.container" id="container" :style="{width: width + 'px', height: height + 'px' }"></div> </div> </template> <script> import mapLoader from '@/utils/gaode'; import highAccuracyGeolocation from '@/utils/highAccuracyGeolocation'; import getMessageByDrawCircle from '@/utils/getMessageByDrawCircle'; export default { mounted() { this.createMap(); }, data() {return {AMap: null, map: null, width: 1000, // map width: 600, // map height: 600, [' AMap. Scale Scale / * * /, 'AMap. The ToolBar / * * / ToolBar,' AMap. Marker tags * / / * and 'AMap. Geolocation / * * /, 'MapType' /* Layer switch */], // map plugin config: {resizeEnable: true, // map initialization location to the current city (will be covered by center) // Center: [], // map center point zoom: 10, // set map zoom level mapStyle: 'amap://styles/normal' // set map display style} // map configuration item}; }, methods: {// initialize map async createMap() {try {this.amap = await mapLoader(this.plugins); this.map = new AMap.Map('container', this.config); AsnycLoaderPlugins (this.amap, this.map, this.plugins); getMessageByDrawCircle(this.AMap, this.map); } catch (e) { console.log(e); }}, // async plugins (AMap, map, plugins) {amap.plugins (AMap, map, plugins) { function () { map.addControl(new AMap.Scale()); // Add scale map.addControl(new amap.toolbar ()); // Add toolbar map.addControl(new map.mapType ()); Map.add (// new map.marker ({// position: map.getCenter(), // content: '< div style = "fontSize: 16 px" > 1 < / div >' content / / / / custom some markers covering}) / /); // Add markup // highAccuracyGeolocation(AMap, map); Add (// new amap.circle ({// center: map.getCenter(), // center: map.getCenter(), // radius: 1000, // Circle radius: 1000, // Circle radius: 1000, // Circle radius: 1000, // fillColor: Circular fill color 'red', / / / / strokeColor: '# FFF, / / / / strokeWeight stroke color: 2 / / / / / / stroke width})); }); }}}; </script> <style lang="scss" module> .root { width: 1920px; height: 1080px; } </style>Copy the code