本文主要介绍利用GeometryService实现面积和长度的计算。首先看一下实现本功能的主要过程:
接下来就一步步介绍实现本功能的具体步骤和方法:
(本文的代码来自https://developers.arcgis.com/javascript/jssamples/util_measurepoly.html,本文只是提炼部分核心代码,讲解实现的思路,如需获取所有代码,请参考上述链接)
1、创建Draw对象
var tb = new Draw(map);
tb.on("draw-end", lang.hitch(map, getAreaAndLength));
tb.activate(Draw.FREEHAND_POLYGON);
2、创建GeomeService对象
var geometryService = new GeometryService("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Utilities/Geometry/GeometryServer");
geometryService.on("areas-and-lengths-complete", outputAreaAndLength);
3、getAreaAndLength方法的实现,注意本方法只有在draw-end事件触发时才会执行
function getAreaAndLength(evtObj) { var map = this, geometry = evtObj.geometry; map.graphics.clear(); var graphic = map.graphics.add(new Graphic(geometry, new SimpleFillSymbol())); //setup the parameters for the areas and lengths operation var areasAndLengthParams = new AreasAndLengthsParameters(); areasAndLengthParams.lengthUnit = GeometryService.UNIT_FOOT; areasAndLengthParams.areaUnit = GeometryService.UNIT_ACRES; areasAndLengthParams.calculationType = "geodesic"; geometryService.simplify([geometry], function (simplifiedGeometries) { areasAndLengthParams.polygons = simplifiedGeometries; geometryService.areasAndLengths(areasAndLengthParams); }); }
4、outputAreaAndLength方法的实现,注意,本方法只有GeomeService对象计算完面积和周长才会触发
function outputAreaAndLength(evtObj) { var result = evtObj.result; console.log(json.stringify(result)); dom.byId("area").innerHTML = result.areas[0].toFixed(3) + " acres"; dom.byId("length").innerHTML = result.lengths[0].toFixed(3) + " feet"; }
下面看一下效果图: