ArcGIS JS Learning Note 1 using ArcGIS JS to achieve the simulation of Baidu map distance measurement and area measurement

Source: Internet
Author: User
Tags polyline

first, the outset

Registered in the blog for three years, today decided to write the first blog, warning yourself not lazy!!!

second, about the ArcGIS JS version selection

At the time of writing this blog, the official version of ArcGIS JS 4.0 has been Released. It is different from the 3.x version, the map is not a control, and really just a "graph", map (4.0 Version) needs to be shown in a view, in the Mapview is a plan, in the sceneview inside a three-dimensional map. The same map can show different effects in different view. But the 4.0 version is the original version, and there are many 3.x features that have not been added to it. So I'm going to use the 3.16 version of the API to learn ArcGIS JS, while watching the 4.x version of the update, then the 3.x version of the content of the learning notes to the 4.x Version.

third, the beginning of the cottage

I believe most giser in the study of GIS programming, the beginning is to learn how to zoom in, narrow, Acreage distance, This study note also take this feeling.

ArcGIS JS has already provided the acreage widget, but used the children's shoes know that the thing is too ugly, and the program is really very abrupt, so that their own implementation of a acreage tool is undoubtedly the best way, no picture no truth, I first put two.

Figure 1. Acreage Area

Figure 2 Acreage Distance

The official given sample, the measurement distance and area are used to geoserveice, and the Internet is similar code, are not directly on the Client's Acreage. fortunately, ArcGIS JS in the 3.13 version of the "esri/geometry/geometryengine" module, the use of this module can implement the Client's Acreage.

This module also has a lot of methods, specific content can be on the official website to view Geometryengine Details.

Calculate distance        _caldistance:function (point1, point2) {            var line = new Polyline (this.defaults.map.spatialReference); C2/>line.addpath ([point1, point2]);            If (this.defaults.map.spatialReference.isWebMercator () | | | This.defaults.map.spatialReference.wkid = = "4326") {//calculation method in the Web Mercator projection and WGS84 coordinate system return Geometryengine.geodesiclength (line, "meters");            } else {//in Other projected coordinate systems the calculation method is return geometryengine.planarlength (line, "meters")            }        },

Calculate Area        _calarea:function (polygon) {            var spatialreference = this.defaults.map.spatialReference;            If (spatialreference.iswebmercator () | | | Spatialreference.wkid = = "4326") {                return geometryengine.geodesicarea (polygon, "square-meters")            } Else {                return Geometryengine.planararea (polygon, "square-meters")            }        },

ok, The core problem is solved, and the rest only needs to be segmented to show distance and improve the user Experience.

1. Measuring distance

When drawing the line, using the ArcGIS JS draw module When the measurement is started, listen to the map click events, the map click on the point to add to the this._stoppoints array, and then each time you click on the map, the current point and the previous point for distance calculation, The results are added to the this_stopdistances array, and the results are added to the map using Graphic.

Start measuring distance _startmeasuredistance:function () {this._clearmapmouseclickevent ();            This._stoppoints = [];            This._stopdistances = [];            This._measurelayer.clear ();            This.toolbar.deactivate ();            This.toolbar.activate (draw.polyline);            var stoppoints = this._stoppoints;            var stopdistances = this._stopdistances;            var = this;                This._mapclickflag = This.defaults.map.on ("click", function (evt) {var distance = 0;                var stoppoint = evt.mappoint;                    If (stoppoints.length > 0) {var startPoint = stoppoints[stoppoints.length-1];                    Distance = self._caldistance (startPoint, stoppoint);  If (self._stopdistances.length > 0) {distance + = Self._stopdistances[self._stopdistances.length                    -1];                } Stopdistances.push (distance);} Stoppoints.push (stoppoint);                var stopgraphic = new Graphic (stoppoint, self.defaults.markerSymbol);                var textgraphic = self._getstoppointgraphic (stoppoint, distance);                Self._measurelayer.add (stopgraphic);            Self._measurelayer.add (textgraphic);        }); },

End measurement, Add Clear button, here the Clear button is drawn with the SVG path, at the end of the code this._clearmapmouseclickevent () is used to cancel the click event of the map, in the end I will post all the Code.

Measure distance end, Add clear button, measure segment        _endmeasuredistance:function (line,endpoint) {            var linegraphic = new Graphic (line, this.toolbar.lineSymbol);            var cleargraphic = this._createclearbtn (endPoint);            This._measurelayer.add (cleargraphic);            This._measurelayer.add (linegraphic);            Linegraphic.getdojoshape (). movetoback ();            This._clearmapmouseclickevent ();        },

2. Area measurement

Area measurement is relatively simple, with draw module after the completion of the polygon, using the calculated area before the calculation of the method is completed before the results are added to the map.

Start measuring area _startmeasurearea:function () {this._clearmapmouseclickevent ();            This._measurelayer.clear ();            This.toolbar.deactivate ();        This.toolbar.activate (draw.polygon);            },//measure Area end, Add clear button, measurement result _endmeasurearea:function (polygon) {var areas = This._calarea (polygon);            If (area > 1000000) {area = (area/1000000). toFixed (2) + "square kilometer";            } else {area = area.tofixed (2) + "square meter";            } var center = polygon.getcentroid ();            var ploygongraphic = new Graphic (polygon, this.toolbar.fillSymbol);            var textsymbol = This._createtextsymbol (area);            Textsymbol.setoffset (30, 10);            var textgraphic = new Graphic (center, textsymbol);            var clearbtn = this._createclearbtn (center);            This._measurelayer.add (ploygongraphic);            This._measurelayer.add (textgraphic); This._measurelayer.add (clearbtn);        Ploygongraphic.getdojoshape (). Movetoback (); },

Let's take a look at how to use this custom measurement module.

<! DOCTYPE html>

The Add ". measure-distance" class represents the measurement distance when making a measurement tool at construction time; the Add ". measure-area" class represents the measurement Area. In this example, my custom module is called dextra, which is loaded according to Dojo's AMD specification when adding references.

Require ([    "esri/map",    "dextra/dijit/measuretools", "    dextra/layers/googleimagelayer",    "dextra/ Layers/googleimageannolayer ",    " dojo/domready! "],    function (Map,             demeasuretools,googleimagelayer, Googleimageannolayer) {        var map = new map ("map", {           showattribution:false,           fadeonzoom:true,           force3dtransforms:true,           center: [101.7, 24.6],           zoom:10,           autoresize:true,           sliderposition: " Bottom-right ",           logo:false,        });        var googleimglayer=new googleimagelayer ();        var googleannolayer=new googleimageannolayer ();        Map.addlayer (googleimglayer);        Map.addlayer (googleannolayer);        var measuretool=new demeasuretools ({            map:map        }, "measuretools")});

Here is the full code for the tool

/** * Created by Dextra.    * Description: enables the client to measure distances and areas of function * version:1.0.0 */define ("dextra/dijit/measuretools", ["dojo/dom", "dojo/query", "dojo/_base/declare", "dojo/_base/lang", "dijit/_widgetbase", "dojo/on", "esri/graphic", "esri/layers/graph Icslayer "," esri/toolbars/draw "," esri/color "," esri/symbols/font "," esri/geometry/polyline "," esri/symbols /simplemarkersymbol "," esri/symbols/simplelinesymbol "," esri/symbols/textsymbol "," esri/geometry/geometryengine ", ], function (dom, query, declare, lang, _widgetbase, on, Graphic, graphicslayer, Draw, Color, Font , Polyline, markersymbol, linesymbol, textsymbol, geometryengine) {var measuretools = declare (_widgetbase, {de                Claredclass: "dextra.dijit.MeasureTools", defaults: {map:null, linesymbol:new Linesymbol ( linesymbol.style_solid, new Color ("#FFA500"), 2), MarKersymbol:new markersymbol (markersymbol.style_circle, New Linesymbol (linesymbol.style_solid, New color ("#DC143C"), 2), new color ("#FFA500")),}, srcrefnode:null, Toolba r:null, _stoppoints:null, _stopdistances:null, _measurelayer:null, _mapclickflag:null,//            Used to cancel the map click event constructor:function (options, srcrefnode) {declare.safemixin (this.defaults, options);            This.srcrefnode = srcrefnode;            This._measurelayer = new Graphicslayer ();            This.defaults.map.addLayer (this._measurelayer);            This._initaltoolbar ();        This._initialmeasurelayer (); },//initialize measure Layer Event _initialmeasurelayer:function () {this._measurelayer.on ("mouse-over", lang.hitch                (this, function (evt) {var graphic = evt.graphic; If (graphic.symbol.isClearBtn) {this.defaults.map.setMapCursor ("pointer");                        On.once (graphic.getshape (), "click", lang.hitch (this, function () {this._measurelayer.clear ();                    This.defaults.map.setMapCursor ("default");                }));            }            })); This._measurelayer.on ("mouse-out", lang.hitch (this, function (evt) {this.defaults.map.setMapCursor ("defaul            T ");        }));  },//initialize Drawing toolbar _initaltoolbar:function () {var map = This.defaults.map This.toolbar =            New Draw (map, {showtooltips:false});            This.toolbar.on ("draw-complete", Lang.hitch (this, this._drawcomplete));            Query ("#" + this.srcrefnode + ">. measure-distance"). on ("click", lang.hitch (this, this._startmeasuredistance));        Query ("#" + this.srcrefnode + ">. measure-area"). on ("click", lang.hitch (this, this._startmeasurearea));       },//end Drawing _drawcomplete:function (evt) {     if (evt.geometry.type = = "polygon") {this._endmeasurearea (evt.geometry)} else {                var endPoint = this._stoppoints[this._stoppoints.length-1];            This._endmeasuredistance (evt.geometry, endPoint);        } this.toolbar.deactivate ();            },//start measuring distance _startmeasuredistance:function () {this._clearmapmouseclickevent ();            This._stoppoints = [];            This._stopdistances = [];            This._measurelayer.clear ();            This.toolbar.deactivate ();            This.toolbar.activate (draw.polyline);            var stoppoints = this._stoppoints;            var stopdistances = this._stopdistances;            var = this;                This._mapclickflag = This.defaults.map.on ("click", function (evt) {var distance = 0;                var stoppoint = evt.mappoint; If (stoppoints.length > 0) {var startPoint = Stoppoints[stoppoints.length-1];                    Distance = self._caldistance (startPoint, stoppoint);  If (self._stopdistances.length > 0) {distance + = Self._stopdistances[self._stopdistances.length                    -1];                } Stopdistances.push (distance);                } Stoppoints.push (stoppoint);                var stopgraphic = new Graphic (stoppoint, self.defaults.markerSymbol);                var textgraphic = self._getstoppointgraphic (stoppoint, distance);                Self._measurelayer.add (stopgraphic);            Self._measurelayer.add (textgraphic);        }); },//measure distance end, Add clear button, measure segment _endmeasuredistance:function (line, endPoint) {var linegraphic = new Gr            Aphic (line, this.toolbar.lineSymbol);            var cleargraphic = this._createclearbtn (endPoint);            This._measurelayer.add (cleargraphic);            This._measurelayer.add (linegraphic); LinegraphiC.getdojoshape (). Movetoback ();        This._clearmapmouseclickevent (); },//get the measurement point of the graphics _getstoppointgraphic:function (stoppoint, distance) {var textsymbol = This.            _createtextsymbol ("starting point"); If (distance > 0 && distance >=) {textsymbol = Textsymbol.settext ((distance/1000). ToF            Ixed (2) + "km"); } ElseIf (distance > 0 && Distance < +) {textsymbol = Textsymbol.settext (distance.tofixed            () + "m");        } returnnew Graphic (stoppoint, textsymbol); },//calculate distance _caldistance:function (point1, point2) {var line = new Polyline (this.defaults.map.spa            tialreference);            Line.addpath ([point1, point2]); If (this.defaults.map.spatialReference.isWebMercator () | | this.defaults.map.spatialReference.wkid = = "4326") {//            The calculation method in the Web Mercator projection and WGS84 coordinate system return geometryengine.geodesiclength (line, "meters"); } else {//inCalculation method in other projection coordinate system return geometryengine.planarlength (line, "meters")},//start measuring area _startmeasur            Earea:function () {this._clearmapmouseclickevent ();            This._measurelayer.clear ();            This.toolbar.deactivate ();        This.toolbar.activate (draw.polygon);            },//measure Area end, Add clear button, measurement result _endmeasurearea:function (polygon) {var areas = This._calarea (polygon);            If (area > 1000000) {area = (area/1000000). toFixed (2) + "square kilometer";            } else {area = area.tofixed (2) + "square meter";            } var center = polygon.getcentroid ();            var ploygongraphic = new Graphic (polygon, this.toolbar.fillSymbol);            var textsymbol = This._createtextsymbol (area);            Textsymbol.setoffset (30, 10);            var textgraphic = new Graphic (center, textsymbol);            var clearbtn = this._createclearbtn (center); This._measurelayer.add (ploygongraphic);            This._measurelayer.add (textgraphic);            This._measurelayer.add (clearbtn);        Ploygongraphic.getdojoshape (). Movetoback (); },//calculate area _calarea:function (polygon) {var spatialreference = This.defaults.map.spatialReferenc            E If (spatialreference.iswebmercator () | | spatialreference.wkid = = "4326") {return geometryengine.geodesicar             EA (polygon, "square-meters")} Else {return geometryengine.planararea (polygon, "square-meters")  }}, _createclearbtn:function (point) {var iconpath = "m13.618,2.397 c10.513,-0.708 5.482,-0.713 2.383,2.386 c-0.718,5.488-0.715,10.517 2.392,13.622 c5.497,16.727 10.529,16.731 13.627,13.632 C16.727, 10.533 16.724,5.502 13.618,2.397 l13.618,2.397 Z m9.615,11.351 l7.927,9.663 l6.239,11.351 C5.55,12.04 5.032,12.64 4.21,11.819 c3.39,10.998 3.987,10.48 4.679,9.79 l6.367,8.103 l4.679,6.415 c3.989,5.726 3.39,5.208 4.21,4.386 c5.032,3.566 5.55,4.165 6.239,4.855 l7.927,6.541 l9.615,4.855 c10.305,4.166 10.82,3.565 11.642,4.386 C12.464, 5.208 11.865,5.726 11.175,6.415 l9.487,8.102 l11.175,9.789 c11.864,10.48 12.464,10.998 11.642,11.819 C10.822,12.64            10.305,12.04 9.615,11.351 l9.615,11.351 Z "var iconcolor =" #b81b1b ";            var clearsymbol = new Markersymbol ();            Clearsymbol.setoffset (-40, 15);            Clearsymbol.setpath (iconpath);            Clearsymbol.setcolor (new Color (iconcolor));            Clearsymbol.setoutline (null);            CLEARSYMBOL.ISCLEARBTN = true;        return Graphic (point, clearsymbol);            }, _createtextsymbol:function (text) {var fontcolor = new Color ("#696969");            var holocolor = new Color ("#fff");            var font = new Font ("10pt", font.style_italic, font.variant_normal, font.weight_bold, "Courier");            var textsymbol = new Textsymbol (text, font, fontcolor); Textsymbol.setoffset (ten). SetHalocolor (holocolor). sethalosize (2);            Textsymbol.setalign (textsymbol.align_middle);        Return textsymbol; }, _clearmapmouseclickevent:function () {if (this._mapclickflag! = Null) {this._mapcli            Ckflag.remove ();    }        }    }); Return measuretools;});

ArcGIS JS Learning Note 1 using ArcGIS JS to achieve the imitation of Baidu map distance measurement and area measurement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.