Document Maps JavaScript API Advanced Tutorial Service plugins and tools Mouse tool distance area measurement

Distance and area measurement

This article introduces how to use the AMap.MouseTool mouse tool plugin to implement the RagingTool distance measurement function and the measureArea area measurement function.

Example of distance and area measurement

1、Distance and area measurement AMap.MouseTool

1

1.1 Create map

const map = new AMap.Map("container", {
  zoom: 10, 
  showOversea: true,
  mapStyle: "amap://styles/whitesmoke", 
  viewMode: "2D", 
});
2

1.2 Create MouseTool instance

This example uses the asynchronous method to install plugins. The AMap.plugin method is used to introduce plugins on demand, and plugin functions are used after the plugin callback. Plugin introduction method Plugin usage.

//Asynchronously load plugin
AMap.plugin("AMap.MouseTool", function () {
  var mouseTool = new AMap.MouseTool(map); //Create mouse tool plugin instance
});
3

1.3 Measure distance

//Use the function in the plugin's callback function
mouseTool.rule({
  startMarkerOptions: { //Set the attribute object of the start point marker for measurement, optional
    icon: new AMap.Icon({
      size: new AMap.Size(19, 31), //Icon size
      imageSize: new AMap.Size(19, 31), 
      image: "//webapi.amap.com/theme/v1.3/markers/b/start.png",
    }),
    offset: new AMap.Pixel(-9, -31),
  },
  endMarkerOptions: { //Set the attribute object of the end point marker for measurement, optional
    icon: new AMap.Icon({
      size: new AMap.Size(19, 31), 
      imageSize: new AMap.Size(19, 31),
      image: "//webapi.amap.com/theme/v1.3/markers/b/end.png",
    }),
    offset: new AMap.Pixel(-9, -31),
  },
  midMarkerOptions: { //Set the attribute object of the waypoint marker for the drag route plugin, optional
    icon: new AMap.Icon({
      size: new AMap.Size(19, 31), 
      imageSize: new AMap.Size(19, 31),
      image: "//webapi.amap.com/theme/v1.3/markers/b/mid.png",
    }),
    offset: new AMap.Pixel(-9, -31),
  },
  lineOptions: { //Optional
    strokeStyle: "solid",
    strokeColor: "#FF33FF",
    strokeOpacity: 1,
    strokeWeight: 2,
  },
});
4

1.4 Measure area

//Use features in the plugin's callback function
mouseTool.measureArea({
   strokeColor:'#80d8ff',
   fillColor:'#80d8ff',
   fillOpacity:0.3
   //Same as Polygon's Option settings
 });
5

1.5 Close Mouse Tool

//Use features in the plugin's callback function
mouseTool.close();
Prompt

The mouseTool.close(ifClear) method is used to close the mouse tool. The ifClear parameter is optional (default is false). When set to true, it closes the tool and clears all overlay objects drawn by the mouse tool on the map; when set to false, it only closes the tool