Recently, I have been doing business related to visual large screen. I would like to share the part of AUtonavi API involved. The following is the development process and scene example
First, register an account and apply for a Key
1. First of all, register a developer account and become an Autonavi Open Platform developer
There are differences in daily quotas and response times per second for a particular service depending on developer permissions
2. After login, click Create New Application on the Application Management page.
3. Select a service platform to add a Key
Second, the introduction of
<script type="text/javascript" id="AMapJS_id" src="Https://webapi.amap.com/maps? v = 1.4.15 & key = xxx&plugin = AMap. The Geocoder, AMap. The Autocomplete, AMap. PlaceSearch, AMap. Heatmap" async ></script>
Copy the code
// AMapLoader.js
let waitAMapExpList = []; // Resolve a bug where different components of the same page introduce the MapLoader and the callback only executes once
export default function MapLoader() {
let AMapJS_id = document.getElementById('AMapJS_id');
return new Promise((resolve, reject) = > {
if (window.AMap) { resolve(window.AMap); } else if (!window.AMap && AMapJS_id) { waitAMapExpList.push({ resolve, reject }); } else { let script = document.createElement('script'); script.type = 'text/javascript'; script.id = 'AMapJS_id'; script.async = true; script.src = 'https://webapi.amap.com/maps?v=1.4.15&callback=initAMap&key=xxx&plugin=AMap.Geocoder, AMap. Autocomplete, AMap. PlaceSearch ,AMap.Heatmap'; script.onerror = reject; document.head.appendChild(script); window.initAMap = (a)= > { resolve(window.AMap); if(waitAMapExpList.length ! = =0) { waitAMapExpList.forEach(item= > { item.resolve(window.AMap); }); } }; } }); } Copy the code
Custom map theme
Get style ID from Autonavi Open Platform, custom map template
this.mapInstance.setMapStyle('amap://styles/c1c78364476283c25201f6c342b4d636');
Copy the code
Four, the current use of plug-ins and API introduction
1. Search selection and map selection
const AMap = await MapLoader(); // Load the map
// Search the selection
AMap.plugin(['AMap.Autocomplete'.'AMap.PlaceSearch'], () = > { const autocomplete = new AMap.Autocomplete({
input: 'address-input'
}); this.placeSearch = new AMap.PlaceSearch({ pageSize: 1 }); AMap.event.addListener(autocomplete, 'select', e => { console.log(e, 'autocomplete'); this.curSelectPoi.address = e.poi.name; let poi_selected = e.poi, lng, lat; lat = poi_selected.location.lat; lng = poi_selected.location.lng; this.curSelectPoi.lat = lat; this.curSelectPoi.lng = lng; this.curSelectPoi.cityCode = e.poi.adcode; // Move the center of the map and mark the location if (lng && lat) { let lnglat = new AMap.LngLat(lng, lat); this.curSelectPoi.address && this.$refs.amapCom.setMarker({ lnglat }); } }); }); // Map selection if (!this.mapInstance) { this.mapInstance = new AMap.Map(this.$refs.mapid, { resizeEnable: true. doubleClickZoom: false. center: this.center, zoom: this.zoom }); } // Click the map to get the latitude and longitude this.mapInstance.on('click', e => { console.log(e.lnglat); this.geocoderInfo.lng = e.lnglat.lng; this.geocoderInfo.lat = e.lnglat.lat; let lnglat = [e.lnglat.lng, e.lnglat.lat]; this.setMarker({ lnglat }); this.getGeocoderInfo(lnglat); }); // Create a geocoded object AMap.plugin(['AMap.Geocoder'], () = > { this.geocoder = new AMap.Geocoder({}); }); // Get address information according to latitude and longitude. / / https://restapi.amap.com/v3/geocode/regeo?location=$or use the web service API {lnglat} & key = XXX `); getGeocoderInfo(lnglat) { this.geocoder.getAddress(lnglat, (status, result) => { if (status === 'complete' && result.regeocode) { this.geocoderInfo.address = result.regeocode.formattedAddress; this.$emit('getGeocoderInfo'.this.geocoderInfo); } else { console.error('Failed to query address by latitude and longitude'); this.geocoderInfo.address = ' '; this.$emit('getGeocoderInfo'.this.geocoderInfo); } }); }, setMarker(e) { console.log('marker info', e); / / create a marker if (!this.locationMarker) { this.locationMarker = new AMap.Marker({ icon: new AMap.Icon({ size: new AMap.Size(29.37), image: 'locationIcon.png'. imageSize: new AMap.Size(29.37) }) }); this.mapInstance.add([this.locationMarker]); } this.locationMarker.setPosition(e.lnglat);// Set the marker position this.center = [e.lnglat.lng, e.lnglat.lat]; this.mapInstance.setZoomAndCenter(e.zoom || this.zoom, e.lnglat);// Move the center of the map this.mapInstance.setFitView(this.locationMarker); // Automatically zoom the map to the appropriate view level }, Copy the code
2. Search + Radius selection
const AMap = await MapLoader(); // Load the map
let circleInstance = new AMap.Circle({
center: this.center, // The center of the circle
radius: this.scope * 1000./ / radius
strokeColor: '#ee5d40'./ / thread color
strokeWeight: 2./ / line width fillColor: '#ef4d2d'./ / fill color fillOpacity: 0.2 // Fill transparency }) circleInstance.setMap(map) // Display the circle this.mapInstance.setFitView() // Automatically scale the map to the appropriate view level according to the distribution of added coverings // Change the scope size circleInstance.setOptions({ radius: this.scope * 1000./ / radius center: this.center, // The center of the circle strokeColor: '#ee5d40'./ / thread color strokeWeight: 2./ / line width fillColor: '#ef4d2d'./ / fill color fillOpacity: 0.2 // Fill transparency }) Copy the code
3. Polygon circle selected area
<amap-draw ref="amapDraw" width="100%" height="500px" :showDrawTool="true" :mapCenter="center" :cityCode="cityCode" @getPathData="getPathData" />
Copy the code
const AMap = await MapLoader(); // Load the map
this.mapInstance = new AMap.Map(this.$refs.mapid, {
resizeEnable: true. doubleClickZoom: false. center: this.center, zoom: this.zoom }); initPath() { // View the path to enter and reproduce if (this.pathData.type) { if (this.pathData.type == 'Circle') { this.circle_radius = this.pathData.circle_radius; this.center = this.pathData.location_center; } else { this.PolygonPath = this.pathData.location_circle; } } else { // Edit entry, basic path Settings this.PolygonPath = [ [this.center[0].this.center[1] + 0.005]. [this.center[0] - 0.005.this.center[1] - 0.005]. [this.center[0] + 0.005.this.center[1] - 0.005] ]; let southWest = new AMap.LngLat( this.center[0] - 0.01. this.center[1] - 0.005 ); let northEast = new AMap.LngLat( this.center[0] + 0.01. this.center[1] + 0.005 ); this.rectangleBounds = new AMap.Bounds(southWest, northEast); } }, // Draw the path drawPath(pathType) { this.pathType = pathType; // Get the circle center point by searching if (this.cityCode == ' ' && this.showDrawTool) { this.$message.closeAll(); this.$message({ showClose: true. duration: 2000. type: 'error'. message: 'Please select the circled position by searching first' }); return; } this.initPath(); // Loads the default circled path created centered around the search location !this.pathData.type && this.mapInstance.clearMap(); // Type The default value is "" to avoid drawing the initial path repeatedly switch (pathType) { case 'Circle': this.linePath = new AMap.Circle({ center: this.center, radius: this.circle_radius, / / radius borderWeight: 3. strokeColor: '#FF33FF'. strokeOpacity: 1. strokeWeight: 6. strokeOpacity: 0.6. fillOpacity: 0.4. strokeStyle: 'dashed'. strokeDasharray: [10.10]. fillColor: '#1791fc'. zIndex: 50 }); this.linePath.setMap(this.mapInstance); this.pathEditor = new AMap.CircleEditor( this.mapInstance, this.linePath ); break; case 'Polygon': this.linePath = new AMap.Polygon({ path: this.PolygonPath, strokeColor: '#FF33FF'. strokeWeight: 6. strokeStyle: 'dashed'. strokeOpacity: 0.6. fillOpacity: 0.4. fillColor: '#1791fc'. zIndex: 50 }); this.mapInstance.add(this.linePath); this.pathEditor = new AMap.PolyEditor( this.mapInstance, this.linePath ); break; case 'Rectangle': this.linePath = new AMap.Rectangle({ bounds: this.rectangleBounds, strokeColor: '#FF33FF'. strokeWeight: 6. strokeOpacity: 0.6. strokeDasharray: [30.10]. strokeStyle: 'dashed'. fillColor: '#1791fc'. fillOpacity: 0.4. cursor: 'pointer'. zIndex: 50 }); this.linePath.setMap(this.mapInstance); this.pathEditor = new AMap.RectangleEditor( this.mapInstance, this.linePath ); break; } // Draw and scale the map to the appropriate view level this.mapInstance.setFitView([this.linePath]); // Open area editing !this.pathData.type && this.pathEditor.open(); // Triggered during region adjustment this.pathEditor.on('adjust', event => { console.log('adjust'.'Restricted area code'.this.cityCode, event); }); // Triggered when editing ends to get the path this.pathEditor.on('end'.async event => { console.log('end', event.target); }); }, // Confirm the selected area and obtain the path closePathEditor() { this.pathEditor.close(); // Trigger close region editing to get editing path let path = this.linePath.getPath(); let pathData = { type: this.pathType, location_circle = path.map(ele= > [ele.lng, ele.lat]); // Connect the desired path format }; this.$emit('getPathData', pathData); }, // Clear the circle to reset the data clearPath() { this.mapInstance.clearMap(); this.$emit('getPathData', { type: ' '. location_circle: [] }); this.pathEditor = null; } Copy the code
4. Display data by administrative region
const AMap = await MapLoader(); // Load the map
// Initialize the map instance
this.mapInstance = new AMap.Map('geo-map', {
viewMode: '3D'. resizeEnable: false. center: this.center, mapStyle: 'amap://styles/c1c78364476283c25201f6c342b4d636'. zoom: this.zoom }); AMapUI.load([], (DistrictExplorer, $) => { // Create an instance this.districtExplorer = new DistrictExplorer({ map: this.mapInstance, eventSupport: true // Turn on event support }); // mouse hover prompt content let $tipMarkerContent = $('<div class="tipMarker"></div>'); let tipMarker = new AMap.Marker({ content: $tipMarkerContent.get(0), offset: new AMap.Pixel(0.0), bubble: true }); this.switch2AreaNode(this.adcode); / / feature by clicking this.districtExplorer.on('featureClick'.async (e, feature) => { console.log(feature.properties); let props = feature.properties; let { level, name } = feature.properties; // If there are child nodes if (props.childrenNum > 0) { // Get data this.curRenderData = await this.getInsideArea({ label: name, level: level == 'province' && name.indexOf('the city') > - 1 ? 'district' : level == 'city' ? 'district' : 'city' }); // Switch focus area this.switch2AreaNode(props.adcode); } }); // The outer area is clicked this.districtExplorer.on('outsideClick', e => { this.districtExplorer.locatePosition( e.originalEvent.lnglat, async (error, routeFeatures) => { console.log(routeFeatures); if (routeFeatures && routeFeatures.length > 1) { // Switch to the provincial region let { level, name } = routeFeatures[1].properties; this.curRenderData = await this.getInsideArea({ label: routeFeatures[1].properties.name, level: level == 'province' && name.indexOf('the city') > - 1 ? 'district' : level == 'city' ? 'district' : 'city' }); this.switch2AreaNode(routeFeatures[1].properties.adcode); } else { // Switch to nationwide this.curRenderData = this.provinceData; this.switch2AreaNode(100000); } }, { levelLimit: 2 } ); }); }); switch2AreaNode(adcode){ this.districtExplorer.loadAreaNode(adcode, (error, areaNode) => { this.currentAreaNode = areaNode; // Set the current location node this.districtExplorer.setAreaNodesForLocating([this.currentAreaNode]); this.renderAreaPolygons(areaNode); }); }; renderAreaPolygons(areaNode) { // Update map view this.mapInstance.setBounds(areaNode.getBounds(), null.null.true); // Clear the existing drawing content this.districtExplorer.clearFeaturePolygons(); // Draw subregions this.districtExplorer.renderSubFeatures(areaNode, (feature, i) => { let fillColor = this.getFillColor( this.curRenderData, feature.properties.name ); const strokeColor = '#fff'; return { cursor: 'default'. bubble: true. strokeColor: strokeColor, / / thread color strokeOpacity: 1.// Line transparency strokeWeight: 1./ / line width fillColor: fillColor, / / fill color fillOpacity: 0.35 // Fill transparency }; }); // Draw the parent region this.districtExplorer.renderParentFeature(areaNode, { cursor: 'default'. bubble: true. strokeColor: '#fff'./ / thread color strokeOpacity: 1.// Line transparency strokeWeight: 1./ / line width fillColor: null./ / fill color fillOpacity: 0.35 // Fill transparency }); } Copy the code
5. Historical heat is rotated at different times
const AMap = await MapLoader(); // Load the map
this.mapInstance = new AMap.Map('loca-map', {
mapStyle: 'amap://styles/c1c78364476283c25201f6c342b4d636'.
pitch: 60.
center: this.center,
zoom: this.zoom
});
// Loca is a geospatial data visualization rendering engine based on Autonavi JS API map and pure JavaScript implementation
this.heatMapLayer = new Loca.HeatmapLayer({
map: this.mapInstance,
eventSupport: true
});
this.heatMapLayer.setOptions({
style: {
radius: 30.
color: {
0.5: 'blue'.
0.65: 'RGB (117211248)..
0.7: 'rgb(0, 255, 0)'.
0.9: '#ffea00'.
1.0: 'red'
}
}
});
// Render heat
renderHeatData() {
this.heatMapLayer.setData(this.heatmapData, {
lnglat: function(obj) {
let val = obj.value;
return [val['lng'], val['lat']].
},
value: 'count'.
type: 'json'
});
this.heatMapLayer.render();
},
Copy the code
6. Coordinate system transformation
/ *
The longitude and latitude of the same geographical position on the earth will have less than offset in different coordinate systems. The common coordinate systems in China are mainly divided into three types:
Earth coordinate system - WGS84: common in GPS equipment, Google maps and other international standard coordinate system.
Mars coordinate system -- GCJ-02: the coordinate system used in China after forced encryption, and Autonavi coordinate system belongs to this coordinate system.
Baidu coordinate system -- BD-09: The coordinate system used by Baidu Map is encrypted again on the basis of Mars coordinate system.
Therefore, before using different coordinate systems, we need to use the amap.convertfrom () method to convert these non-High German coordinate systems.
* /
let ltapi_geo_json = [[116.3.39.9], [116.3.39.9]].
AMap.convertFrom(ltapi_geo_json, 'gps', (status, result) => {
if (result.info === 'ok') {
console.log(result);
ltapi_geo_json = result.locations.map(ele= > [ele.lng, ele.lat]);
console.log(ltapi_geo_json);
}
});
Copy the code
Echarts is equipped with AMap
import MapLoader from '@/utils/AMapUtil'; / / AMap load
// Import echarts modules as needed
const echarts = require('echarts/lib/echarts'); // Introduce the ECharts main module
require('echarts/lib/chart/effectScatter'); // Introduce a scatter
require('echarts/lib/chart/lines'); // Import route
require('zrender/lib/svg/svg'); / / SVG support
let AMapOption = {
maxPitch: 60.
pitch: 30./ / 45 pitching Angle
resizeEnable: true.
center: [103.788625.36.136601].
viewMode: '3D'.// The TV browser cannot render, 2D will be enabled
mapStyle: 'amap://styles/c1c78364476283c25201f6c342b4d636'.
zoom: 8.// Map zoom level
zooms: [5.18] // The default zoom range is 3-18
};
const AMapChart = null; / / echarts instance
const mapInstance = null; // Map instance
const heatmapInstance = null; // Thermal map examples
// Get the map instance and render the Gaode thermal map
MapLoader().then(AMap= > {
// Initialize echarts
AMapChart = echarts.init(
document.getElementById('heat-map'),
null.
{ renderer: 'canvas' }
); // lines render with canvas
AMapChart.setOption({amap: AMapOption});
// Get the map instance
mapInstance = AMapChart
.getModel()
.getComponent('amap')
.getAMap();
// Set the theme style
mapInstance.setMapStyle(
'amap://styles/c1c78364476283c25201f6c342b4d636'
);
// Use autonavi thermal map plug-in to reduce data processing
mapInstance.plugin(['AMap.Heatmap'], () = > {
// Create a HeatMap instance
heatmapInstance = new AMap.Heatmap(mapInstance, {
radius: 30.// Set the radius
opacity: [0.0.8].
gradient: {
'0.2': '# 571545'.
'0.4': '#91083c'.
'0.6': '#ca0436'.
'0.8': '#e16118'.
'1.0': '#ee903e'
}
});
});
}).catch(err= > console.log(err));
// Render data
let linesConfig = [
{
offset: 0.
color: '#6b46f9' // The color at 0%
},
{
offset: 1.
color: '#00d7e6' // Color at 100%
}
];
// Render the heat map
let heatData = [{"count":"1"."lat":"39.86183166503906"."lng":"116.40495300292969"}]
heatmapInstance.setDataSet({data: heatData});
// Render scatter and route
let topPoiList = [{"index":1."label":No.19 student Dormitory of China University of Geosciences."value":"8.81"."lng":116.348902."lat":39.992882."count":17."symbolSize":55}]
AMapChart.setOption({
amap: AMapOption,
series: [{
type: 'lines'./ / route
zlevel: 2.// Controls the Lines and effectScatter levels
animation: false.
coordinateSystem: 'amap'.// Use the Gaud coordinate system
effect: {
show: self.level == 1.// The TV side is seriously stuck, and the basic version turns off special effects animation
period: 4.
trailLength: 0.1.
color: '#fff'.
symbolSize: 8
},
lineStyle: {
normal: {
color: {
type: 'linear'.
x: 0.
y: 0.
x2: 0.
y2: 1.
colorStops: linesConfig / / thread color
},
width: 2.
curveness: 0.2
}
},
data: self.formtLinesData(topPoiList, self.screenCenter, false)
},
{
type: 'effectScatter'./ / scatter
coordinateSystem: 'amap'.
zlevel: 3.
rippleEffect: {
period: 6.
scale: 2.5.
brushType: 'stroke'
},
label: {
normal: {
color: '#fff'.
show: true.
position: 'inside'.
formatter: '{b}'.
textBorderColor: '# 000'
}
},
itemStyle: {
normal: {
color: linesConfig[0].color / / some color
}
},
data: self.formtVData(topPoiList, self.screenCenter)
}]
});
Copy the code
Give me a thumbs up if you think it helps. I will keep updating as the usage scenarios increase. Welcome Mark