Custom Layer
The JS API allows the creation of custom layers to display personalized map data. This article introduces how to create custom layers and provides some simple and practical examples.
Custom Layer Example
1、Custom Layer
1.1 Create a custom layer
A custom layer is a layer where the drawing method is entirely specified by the developer. This layer can be a canvas, SVG, or even a DOM-based layer. The JS API enables synchronization of custom layers with Amap for panning and zooming, and it calls the developer's render method to redraw the layer. Custom layers are constructed using AMap.CustomLayer, and the constructor accepts two parameters: the first is the DOM canvas serving as the layer, and the second is the related property settings of the layer, which are the same as those of general layers. Below is the usage method of custom layers:
//Create canvas
var canvas = document.createElement('canvas');
//Set the width and height of the canvas to match the map instance
canvas.width = map.getSize().width;
canvas.height = map.getSize().height;
//Create a custom layer
var customLayer = new AMap.CustomLayer(canvas, {
zIndex: 12,
zooms: [3, 18] //Set the visibility level, this layer is visible when the map zoom level is between 3 and 18
});
//Add a custom layer to the map
map.add(customLayer);1.2 Custom rendering method
You can use the render method to customize layer rendering. You should update the pixel position within the container used for drawing to redraw the layer content. The pixel position is converted from latitude and longitude coordinates, usually using the map.lnglatToContainermethod.
The render method is called when the custom layer is initially drawn, and when map movement and zooming ends.
//Draw a circle at the center of the map using canvas
customLayer.render = () => {
//Get the center point of the map
var center = map.getCenter(); //Get the latitude and longitude coordinates of the current map center
var pos = map.lngLatToContainer(center); //Convert map latitude and longitude coordinates to map container pixel coordinates
var r = 20;
//Draw a circle using canvas
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#08f";
ctx.strokeStyle = "#fff";
ctx.beginPath();
ctx.moveTo(pos.x + r, pos.y);
ctx.arc(pos.x, pos.y, r, 0, 2 * Math.PI);
ctx.lineWidth = 3;
ctx.closePath();
ctx.stroke();
ctx.fill();
};