Rectangle Drawing and Editing
AMap.Rectangle can draw rectangles, which are fillable shapes formed by latitude and longitude ranges on the map. This article introduces how to draw and edit rectangles on the map, and set properties such as fill color and outline style.
Example of Rectangle Drawing and Editing
1、Rectangle Drawing
1.1 Create Map
var map = new AMap.Map("container", {
center: [100.491422, 13.749313],
showOversea: true, //Enable world Map
mapStyle: "amap://styles/whitesmoke",
viewMode: "2D",
zoom: 13,
});1.2 Set the rectangular range
//Set the rectangular range, consisting of the latitude and longitude coordinates of the southwest and northeast corners
var southWest = new AMap.LngLat(100.456575, 13.74256); //Latitude and longitude coordinates of the southwest corner
var northEast = new AMap.LngLat(100.518716, 13.762569); //Latitude and longitude coordinates of the northeast corner
var bounds = new AMap.Bounds(southWest, northEast); //Create a latitude and longitude bounding box for a feature objectPrompt
The latitude and longitude coordinates of the rectangle must be in the order of bottom-left, top-right.
1.3 Create a Rectangle instance
var rectangle = new AMap.Rectangle({
bounds: bounds, //The range of the rectangle
strokeColor: "red",
strokeWeight: 6,
strokeOpacity: 0.5,
strokeStyle: "dashed", //Outline style, dashed for dotted lines, and also supports solid for solid lines
strokeDasharray: [30, 10],
fillColor: "blue",
fillOpacity: 0.5,
cursor: "pointer",
zIndex: 50,
});1.4 Add Rectangle object to Map
map.add(rectangle);
//Adjust the view based on the coverage area
map.setFitView([rectangle]);1.5 Add events to Rectangle
rectangle.on("mouseover", () => {
rectangle.setOptions({ //Method of modifying rectangle properties
fillOpacity: 0.7,
fillColor: "#7bccc4",
});
});
rectangle.on("mouseout", () => {
rectangle.setOptions({
fillOpacity: 0.5,
fillColor: "blue",
});
});2、Rectangle editing
The AMap.RectangleEditor rectangle editing plugin supports modifying existing rectangles or dynamically drawing rectangles directly on the map, achieving real-time editing and drawing by adjusting the position and size of the rectangle
2.1 Construct a rectangle editing object and enable the editing state of the rectangle
//Introduce the rectangle editor plugin
map.plugin(["AMap.RectangleEditor"], function () {
//Instantiate the rectangle editor, passing in the map instance and the rectangle instance to be edited
var rectangleEditor = new AMap.RectangleEditor(map, rectangle);
//Enable edit mode
rectangleEditor.open();
});Prompt
rectangleEditor.open() is the method to start editing the object. If you want to finish editing, you can call the rectangleEditor.close() method.