private void Initialize()
        {
            // Create new Map with basemap.
            Map myMap = new Map(new Uri(BasemapUrl));

            // Display the map.
            _myMapView.Map = myMap;

            // Create and add graphics overlay for displaying the trail.
            _locationHistoryLineOverlay = new GraphicsOverlay();
            SimpleLineSymbol locationLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Lime, 2);

            _locationHistoryLineOverlay.Renderer = new SimpleRenderer(locationLineSymbol);
            _myMapView.GraphicsOverlays.Add(_locationHistoryLineOverlay);

            // Create and add graphics overlay for showing points.
            _locationHistoryOverlay = new GraphicsOverlay();
            SimpleMarkerSymbol locationPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Red, 3);

            _locationHistoryOverlay.Renderer = new SimpleRenderer(locationPointSymbol);
            _myMapView.GraphicsOverlays.Add(_locationHistoryOverlay);

            // Create the polyline builder.
            _polylineBuilder = new PolylineBuilder(SpatialReferences.WebMercator);

            // Get permissions.
            AskForLocationPermission();
        }
Example #2
0
        private Geometry CreatePolyline()
        {
            if (Point1 == null || Point2 == null)
            {
                return(null);
            }
            CurveType  curveType = DeriveCurveType(LineType);
            LinearUnit lu        = DeriveUnit(LineDistanceType);

            try
            {
                // create line
                var polyline = QueuedTask.Run(() =>
                {
                    var segment = LineBuilder.CreateLineSegment(Point1, Point2);
                    return(PolylineBuilder.CreatePolyline(segment));
                }).Result;
                Geometry newline = GeometryEngine.GeodeticDensifyByLength(polyline, 0, lu, curveType);
                AddGraphicToMap(newline);
                ResetPoints();

                return(newline as Geometry);
            }
            catch (Exception ex)
            {
                // do nothing
                return(null);
            }
        }
Example #3
0
        private List <Graphic> GenerateGraphics(Diamond14EntityLine line, string type, Color color)
        {
            var result = new List <Graphic>();

            var lineBuilder = new PolylineBuilder(SpatialReferences.WebMercator);

            foreach (var point in line.Items)
            {
                if (point.IsValid())
                {
                    var mapPointWgs84 = new MapPoint(point.Longitude, point.Latitude, SpatialReferences.Wgs84);
                    var mapPoint      = GeometryEngine.Project(mapPointWgs84, SpatialReferences.WebMercator) as MapPoint;
                    lineBuilder.AddPoint(mapPoint);
                }
            }

            var geometry   = lineBuilder.ToGeometry();
            var resultLine = new Graphic
            {
                Geometry = geometry,
                Symbol   = new SimpleLineSymbol
                {
                    Color = color,
                    Width = line.Width
                }
            };

            resultLine.Attributes[Diamond14Attributes.LineValue] = line.LabelValue?.ToString() ?? string.Empty;
            resultLine.Attributes[Diamond14Attributes.LineType]  = type;

            result.Add(resultLine);

            return(result);
        }
Example #4
0
        private static Polyline CreateWkbMultiLineString(BinaryReader reader, WkbByteOrder byteOrder)
        {
            // Get the number of linestrings in this multilinestring.
            var numLineStrings = (int)ReadUInt32(reader, byteOrder);

            if (numLineStrings < 1)
            {
                throw new Exception("Could not create linestring");
            }

            // Read linestring header
            reader.ReadByte();
            ReadUInt32(reader, byteOrder);

            var mline = new PolylineBuilder(CreateWkbLineString(reader, byteOrder));

            // Loop on the number of linestrings.
            for (var i = 1; i < numLineStrings; i++)
            {
                // Read linestring header
                reader.ReadByte();
                ReadUInt32(reader, byteOrder);

                mline.AddParts(CreateWkbLineString(reader, byteOrder).Parts);
            }

            // Create and return the MultiLineString.
            return(mline.ToGeometry());
        }
Example #5
0
        private void GeneratePolyGeometry()
        {
            //PolyCoordinates.ToList()
            List <MapPoint> points = new List <MapPoint>();

            foreach (CoordinateObject coordObject in PolyCoordinates)
            {
                //points.Add(new MapPointBuilder(coordObject.MapPoint.X, coordObject.MapPoint.Y, 0, coordObject.MapPoint.SpatialReference));
                points.Add(coordObject.MapPoint);
            }

            ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
            {
                if (GeometryType == GeometryType.Polyline)
                {
                    PolylineBuilder polylineBuilder = new PolylineBuilder(points);
                    polylineBuilder.HasZ            = true;
                    MapGeometry = polylineBuilder.ToGeometry();
                }
                else if (GeometryType == GeometryType.Polygon)
                {
                    PolygonBuilder polygonBuilder = new PolygonBuilder(points);
                    polygonBuilder.HasZ           = true;
                    MapGeometry = polygonBuilder.ToGeometry();
                }
            });
        }
Example #6
0
        public static async Task <Polyline> DrawPolylineAsync(SceneView sceneView, System.Threading.CancellationToken cancellationToken)
        {
            var             tcs             = new TaskCompletionSource <Polyline>();
            PolylineBuilder polylineBuilder = new PolylineBuilder(sceneView.SpatialReference);

            polylineBuilder.AddPart(new MapPoint[] { });
            var     sketchlayer = CreateSketchLayer(sceneView);
            Graphic lineGraphic = new Graphic()
            {
                Symbol = DefaultLineSymbol
            };
            Graphic lineMoveGraphic = new Graphic()
            {
                Symbol = DefaultLineMoveSymbol
            };

            sketchlayer.Graphics.AddRange(new Graphic[] { lineGraphic, lineMoveGraphic });
            Action cleanupEvents = SetUpHandlers(sceneView,
                                                 (p) => //On mouse move, move completion line around
            {
                if (p != null && polylineBuilder.Parts.Count > 0 && polylineBuilder.Parts[0].Count > 0)
                {
                    lineMoveGraphic.Geometry = new Polyline(new MapPoint[] { polylineBuilder.Parts[0].Last().EndPoint, p });
                }
            },
                                                 (p) => //On tap add a vertex
            {
                if (p != null)
                {
                    polylineBuilder.AddPoint(p);
                    if (polylineBuilder.Parts.Count > 0 && polylineBuilder.Parts[0].Count >= 1)
                    {
                        lineGraphic.Geometry = polylineBuilder.ToGeometry();
                    }
                }
            },
                                                 (p) => //View tapped - completes task and returns point
            {
                tcs.SetResult(polylineBuilder.ToGeometry());
            });
            Action cleanup = () =>
            {
                cleanupEvents();
                sceneView.GraphicsOverlays.Remove(sketchlayer);
            };

            cancellationToken.Register(() => tcs.SetCanceled());

            Polyline result = null;

            try
            {
                result = await tcs.Task;
            }
            finally
            {
                cleanup();
            }
            return(result);
        }
Example #7
0
        private async Task UpdateGeometry(MapPoint point)
        {
            if (_selectedFeature.Geometry is Polyline line)
            {
                // Get the nearest point on the selected line.
                ProximityResult nearestVertex = GeometryEngine.NearestVertex(line, point);

                // Create a new polyline.
                PolylineBuilder polylineBuilder = new PolylineBuilder(line);
                Part            part            = polylineBuilder.Parts[nearestVertex.PartIndex];

                // Replace the nearest point with the new point.
                part.SetPoint(nearestVertex.PointIndex, point);

                // Update the geometry of the feature.
                _selectedFeature.Geometry = GeometryEngine.Project(polylineBuilder.ToGeometry(), _selectedFeature.Geometry.SpatialReference);
                await _selectedFeature.FeatureTable.UpdateFeatureAsync(_selectedFeature);
            }
            else if (_selectedFeature.Geometry is MapPoint)
            {
                // Update the geometry of the feature.
                _selectedFeature.Geometry = point;
                await _selectedFeature.FeatureTable.UpdateFeatureAsync(_selectedFeature);
            }

            // Clear the selection.
            (_selectedFeature.FeatureTable.Layer as FeatureLayer).ClearSelection();
            _selectedFeature = null;
        }
Example #8
0
        public TrackModel(TaskEventArgs args, Action <string> callback)
        {
            Callback    = callback;
            TrackPoints = new List <Graphic>();
            TrackLine   = new Graphic {
                Geometry = new Polyline(new PointCollection())
            };

            PolylineBuilder polylineBuilder = new PolylineBuilder(TrackLine.Geometry as Polyline);

            XmlNodeList pts = args.GetXmlNodes("//PLocation");

            if (pts == null)
            {
                return;
            }

            var sms = GetPointSymbol(args.GetXmlNode("//LSymbol"));

            foreach (XmlNode n in pts)
            {
                var tp = GetGraphic(n);
                tp.Symbol = sms;
                TrackPoints.Add(tp);
                polylineBuilder.AddPoint(tp.Geometry as MapPoint);
            }

            TrackLine.Geometry = polylineBuilder.ToGeometry();
            TrackLine.Symbol   = GetTrackSymbol(args.GetXmlNode("//LSymbol"));


            GetIcon(args.GetXmlNode("//PData"));
        }
Example #9
0
 private void MySceneView_MouseDoubleClick(object sender, MouseEventArgs e)
 {
     if (type == "line" && mapPoint_list.Count != 0)
     {
         BorderContentText.Visibility = Visibility.Visible;
         var boatPositions = new PolylineBuilder(SpatialReferences.Wgs84);
         for (var i = 0; i < mapPoint_list.Count; i++)
         {
             boatPositions.AddPoint(new MapPoint(mapPoint_list[i].X, mapPoint_list[i].Y));
         }
         var boatRoute = boatPositions.ToGeometry();
         _mapViewModel.Line(boatRoute, "line");
         LineText.Text = "Line Length: " + GeometryEngine.LengthGeodetic(boatRoute).ToString("N2") + " meters";
     }
     else if (type == "area" && mapPoint_list.Count != 0)
     {
         BorderContentText.Visibility = Visibility.Visible;
         var boatPositions = new PolygonBuilder(SpatialReferences.Wgs84);
         for (var i = 0; i < mapPoint_list.Count; i++)
         {
             boatPositions.AddPoint(new MapPoint(mapPoint_list[i].X, mapPoint_list[i].Y));
         }
         var boatRoute = boatPositions.ToGeometry();
         _mapViewModel.Area(boatRoute);
         AreaText.Text = "Area Size: " + GeometryEngine.AreaGeodetic(boatRoute).ToString("N2") + "  square meters";
     }
     mapPoint_list.Clear();
 }
    protected override void OnClick()
    {
      QueuedTask.Run(async() =>
      {
        //get sketch geometry
        var sketchGeom = await MapView.Active.GetCurrentSketchAsync();

        //return if the sketch doesn't have enough points for its geometry type
        if ((sketchGeom.GeometryType == GeometryType.Polygon && sketchGeom.PointCount < 3) || (sketchGeom.GeometryType == GeometryType.Polyline && sketchGeom.PointCount < 2))
          return;

        //get the sketch as a point collection
        var pointCol = ((Multipart)sketchGeom).Points;

        //get the last point in the sketch based on its geometry type
        var lastSketchPoint = pointCol[(sketchGeom.GeometryType == GeometryType.Polygon) ? pointCol.Count -2 : pointCol.Count -1];

        //build a geometry with the last sketch point and set the sketch
        if (sketchGeom.GeometryType == GeometryType.Polygon)
        {
          //sketch polygons need two points for the initial feedback to work
          var sketchPoly = new PolygonBuilder(new[] { lastSketchPoint,lastSketchPoint });
          await MapView.Active.SetCurrentSketchAsync(sketchPoly.ToGeometry());
        }
        else
        {
          var sketchPolyline = new PolylineBuilder(new[] { lastSketchPoint });
          await MapView.Active.SetCurrentSketchAsync(sketchPolyline.ToGeometry());
        }
      });
    }
Example #11
0
        private async void MySceneView_MouseLeftDown(object sender, MouseEventArgs e)
        {
            if (edit == true && (type == "line" || type == "area"))
            {
                if (MySceneView.GetCurrentViewpoint(ViewpointType.BoundingGeometry) == null)
                {
                    return;
                }
                _mapViewModel.Clear(type);
                System.Windows.Point screenPoint = e.GetPosition(MySceneView);
                MapPoint             mapPoint    = await MySceneView.ScreenToLocationAsync(screenPoint);

                if (mapPoint.X != 0 && mapPoint.Y != 0 && mapPoint.Z != 0)
                {
                    mapPoint = GeometryEngine.NormalizeCentralMeridian(mapPoint) as MapPoint;
                    mapPoint_list.Add(new MapPoint(mapPoint.X, mapPoint.Y));
                    if (mapPoint_list.Count > 1)
                    {
                        var boatPositions = new PolylineBuilder(SpatialReferences.Wgs84);
                        boatPositions.AddPoint(new MapPoint(mapPoint_list[mapPoint_list.Count - 2].X, mapPoint_list[mapPoint_list.Count - 2].Y));
                        boatPositions.AddPoint(new MapPoint(mapPoint_list[mapPoint_list.Count - 1].X, mapPoint_list[mapPoint_list.Count - 1].Y));
                        var boatRoute = boatPositions.ToGeometry();
                        _mapViewModel.Line(boatRoute, "temp");;
                    }
                }
            }
        }
        private void Initialize()
        {
            // Add event handler for when this sample is unloaded.
            Unloaded += SampleUnloaded;

            // Create new Map with basemap.
            Map myMap = new Map(Basemap.CreateDarkGrayCanvasVector());

            // Display the map.
            MyMapView.Map = myMap;

            // Create and add graphics overlay for displaying the trail.
            _locationHistoryLineOverlay = new GraphicsOverlay();
            SimpleLineSymbol locationLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Lime, 2);

            _locationHistoryLineOverlay.Renderer = new SimpleRenderer(locationLineSymbol);
            MyMapView.GraphicsOverlays.Add(_locationHistoryLineOverlay);

            // Create and add graphics overlay for showing points.
            _locationHistoryOverlay = new GraphicsOverlay();
            SimpleMarkerSymbol locationPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Red, 3);

            _locationHistoryOverlay.Renderer = new SimpleRenderer(locationPointSymbol);
            MyMapView.GraphicsOverlays.Add(_locationHistoryOverlay);

            // Create the polyline builder.
            _polylineBuilder = new PolylineBuilder(SpatialReferences.WebMercator);

            // Start location services.
            HandleLocationReady();
        }
Example #13
0
        protected override void OnClick()
        {
            QueuedTask.Run(async() =>
            {
                //get sketch geometry
                var sketchGeom = await MapView.Active.GetCurrentSketchAsync();

                //return if the sketch doesn't have enough points for its geometry type
                if ((sketchGeom.GeometryType == GeometryType.Polygon && sketchGeom.PointCount < 3) || (sketchGeom.GeometryType == GeometryType.Polyline && sketchGeom.PointCount < 2))
                {
                    return;
                }

                //get the sketch as a point collection
                var pointCol = ((Multipart)sketchGeom).Points;

                //get the last point in the sketch based on its geometry type
                var lastSketchPoint = pointCol[(sketchGeom.GeometryType == GeometryType.Polygon) ? pointCol.Count - 2 : pointCol.Count - 1];

                //build a geometry with the last sketch point and set the sketch
                if (sketchGeom.GeometryType == GeometryType.Polygon)
                {
                    //sketch polygons need two points for the initial feedback to work
                    var sketchPoly = new PolygonBuilder(new[] { lastSketchPoint, lastSketchPoint });
                    await MapView.Active.SetCurrentSketchAsync(sketchPoly.ToGeometry());
                }
                else
                {
                    var sketchPolyline = new PolylineBuilder(new[] { lastSketchPoint });
                    await MapView.Active.SetCurrentSketchAsync(sketchPolyline.ToGeometry());
                }
            });
        }
        private void Initialize()
        {
            // Create new Map with basemap.
            Map myMap = new Map(new Uri(BasemapUrl));

            // Display the map.
            MyMapView.Map = myMap;

            // Create and add graphics overlay for displaying the trail.
            _locationHistoryLineOverlay = new GraphicsOverlay();
            SimpleLineSymbol locationLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Lime, 2);

            _locationHistoryLineOverlay.Renderer = new SimpleRenderer(locationLineSymbol);
            MyMapView.GraphicsOverlays.Add(_locationHistoryLineOverlay);

            // Create and add graphics overlay for showing points.
            _locationHistoryOverlay = new GraphicsOverlay();
            SimpleMarkerSymbol locationPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Red, 3);

            _locationHistoryOverlay.Renderer = new SimpleRenderer(locationPointSymbol);
            MyMapView.GraphicsOverlays.Add(_locationHistoryOverlay);

            // Create the polyline builder.
            _polylineBuilder = new PolylineBuilder(SpatialReferences.Wgs84);

            MyMapView.PropertyChanged += (o, e) =>
            {
                if (e.PropertyName == nameof(MyMapView.LocationDisplay) && MyMapView.LocationDisplay != null)
                {
                    // Configure location.
                    HandleLocationReady();
                }
            };
        }
        private static Geometry GetGeometryFromBuffer(byte[] geomBuffer, SpatialReference sr)
        {
            var geomType = GetGeometryType(geomBuffer);

            switch (geomType)
            {
            case GeometryType.Point:
            {
                int    offset = 4;
                double x      = DoubleWithNaN(BitConverter.ToDouble(geomBuffer, offset));
                offset += 8;
                double y = DoubleWithNaN(BitConverter.ToDouble(geomBuffer, offset));

                var mp = MapPointBuilder.FromEsriShape(geomBuffer, sr);
                //System.Diagnostics.Debug.WriteLine($@"x: {x} = {mp.X} y: {y} = {mp.Y}");
                return(mp);
            }

            case GeometryType.Polyline:
            {
                var line = PolylineBuilder.FromEsriShape(geomBuffer, sr);
                return(line);
            }

            case GeometryType.Polygon:
            {
                var poly = PolygonBuilder.FromEsriShape(geomBuffer, sr);
                return(poly);
            }
            }
            return(null);
        }
Example #16
0
        /// <summary>
        /// Create polyline features from graphics and add to table
        /// </summary>
        /// <param name="graphicsList">List of graphics to add to table</param>
        /// <returns></returns>
        private static async Task CreateFeatures(List <Graphic> graphicsList)
        {
            RowBuffer rowBuffer = null;

            try
            {
                await QueuedTask.Run(() =>
                {
                    var layer = MapView.Active.GetSelectedLayers()[0];
                    if (layer is FeatureLayer)
                    {
                        var featureLayer = layer as FeatureLayer;
                        using (var table = featureLayer.GetTable())
                        {
                            TableDefinition definition = table.GetDefinition();
                            int shapeIndex             = definition.FindField("Shape");

                            //EditOperation editOperation = new EditOperation();
                            //editOperation.Callback(context =>
                            //{
                            foreach (Graphic graphic in graphicsList)
                            {
                                //int nameIndex = featureClassDefinition.FindField("NAME");
                                rowBuffer = table.CreateRowBuffer();

                                if (graphic.Geometry is Polyline)
                                {
                                    rowBuffer[shapeIndex] = new PolylineBuilder(graphic.Geometry as Polyline).ToGeometry();
                                }
                                else if (graphic.Geometry is Polygon)
                                {
                                    rowBuffer[shapeIndex] = new PolygonBuilder(graphic.Geometry as Polygon).ToGeometry();
                                }

                                Row row = table.CreateRow(rowBuffer);

                                //To Indicate that the Map has to draw this feature and/or the attribute table to be updated
                                //context.Invalidate(row);
                            }
                            //});
                            //bool editResult = editOperation.Execute();
                            //bool saveResult = await Project.Current.SaveEditsAsync();
                        }
                    }
                });
            }
            catch (GeodatabaseException exObj)
            {
                Console.WriteLine(exObj);
                throw;
            }
            finally
            {
                if (rowBuffer != null)
                {
                    rowBuffer.Dispose();
                }
            }
        }
        /// <summary>
        /// Create sample polyline feature using the geometries from the point feature layer.
        /// </summary>
        /// <param name="polylineLayer">Polyline geometry feature layer used to add the new features.</param>
        /// <param name="pointLayer">The geometries from the point layer are used as vertices for the new line features.</param>
        /// <returns></returns>
        private Task <bool> constructSamplePolylines(FeatureLayer polylineLayer, FeatureLayer pointLayer)
        {
            // execute the fine grained API calls on the CIM main thread
            return(QueuedTask.Run(() =>
            {
                // get the underlying feature class for each layer
                var polylineFeatureClass = polylineLayer.GetTable() as FeatureClass;
                var pointFeatureClass = pointLayer.GetTable() as FeatureClass;

                // retrieve the feature class schema information for the feature classes
                var polylineDefinition = polylineFeatureClass.GetDefinition() as FeatureClassDefinition;
                var pointDefinition = pointFeatureClass.GetDefinition() as FeatureClassDefinition;

                // construct a cursor for all point features, since we want all feature there is no
                // QueryFilter required
                var pointCursor = pointFeatureClass.Search(null, false);

                // initialize a counter variable
                int pointCounter = 0;
                // initialize a list to hold 5 coordinates that are used as vertices for the polyline
                var lineCoordinates = new List <Coordinate>(5);

                // set up the edit operation for the feature creation
                var createOperation = new EditOperation();
                createOperation.Name = "Create polylines";
                createOperation.SelectNewFeatures = false;

                // set up the datum transformation to be used in the projection
                ProjectionTransformation transformation = ProjectionTransformation.CreateFromEnvironment(pointDefinition.GetSpatialReference(),
                                                                                                         polylineDefinition.GetSpatialReference());

                // loop through the point features
                while (pointCursor.MoveNext())
                {
                    pointCounter++;

                    var pointFeature = pointCursor.Current as Feature;
                    // add the feature point geometry as a coordinate into the vertex list of the line
                    // - ensure that the projection of the point geometry is converted to match the spatial reference of the line
                    // with a datum transformation considering the different spheroids
                    lineCoordinates.Add(((MapPoint)GeometryEngine.ProjectEx(pointFeature.GetShape(), transformation)).Coordinate);

                    // for every 5 geometries, construct a new polyline and queue a feature create
                    if (pointCounter % 5 == 0)
                    {
                        // construct a new polyline by using the 5 point coordinate in the current list
                        var newPolyline = PolylineBuilder.CreatePolyline(lineCoordinates, polylineDefinition.GetSpatialReference());
                        // queue the create operation as part of the edit operation
                        createOperation.Create(polylineLayer, newPolyline);
                        // reset the list of coordinates
                        lineCoordinates = new List <Coordinate>(5);
                    }
                }

                // execute the edit (create) operation
                return createOperation.ExecuteAsync();
            }));
        }
    /// <summary>
    /// Runs the tile task, resulting data will be stored in Data.
    /// </summary>
    /// <param name="featureCollections">The feature collections this tile task will be building.</param>
    public void Start(IEnumerable <FeatureCollection> featureCollections)
    {
        float inverseTileScale = 1.0f / (float)address.GetSizeMercatorMeters();

        foreach (var styleLayer in featureStyling.Layers)
        {
            foreach (var collection in featureCollections)
            {
                foreach (var feature in styleLayer.GetFilter().Filter(collection))
                {
                    var    layerStyle  = styleLayer.Style;
                    string featureName = "";
                    object identifier;

                    if (feature.TryGetProperty("id", out identifier))
                    {
                        featureName += identifier.ToString();
                    }

                    // Resulting data for this feature.
                    FeatureMesh featureMesh = new FeatureMesh(address.ToString(), collection.Name, styleLayer.Name, featureName);
                    Debug.Log("^^^^^^^^^^^^^^^^^^--> 1 Tile:  " + address.ToString());
                    Debug.Log("^^^^^^^^^^^^^^^^^^--> 2 Collection: " + collection.Name);
                    Debug.Log("^^^^^^^^^^^^^^^^^^--> 3 Layer: " + styleLayer.Name);
                    Debug.Log("^^^^^^^^^^^^^^^^^^--> 4 Identifier " + featureName);

                    IGeometryHandler handler = null;

                    if (feature.Type == GeometryType.Polygon || feature.Type == GeometryType.MultiPolygon)
                    {
                        var polygonOptions = layerStyle.GetPolygonOptions(feature, inverseTileScale);

                        if (polygonOptions.Enabled)
                        {
                            handler = new PolygonBuilder(featureMesh.Mesh, polygonOptions, Transform);
                        }
                    }

                    if (feature.Type == GeometryType.LineString || feature.Type == GeometryType.MultiLineString)
                    {
                        var polylineOptions = layerStyle.GetPolylineOptions(feature, inverseTileScale);

                        if (polylineOptions.Enabled)
                        {
                            handler = new PolylineBuilder(featureMesh.Mesh, polylineOptions, Transform);
                        }
                    }

                    if (handler != null)
                    {
                        feature.HandleGeometry(handler);
                        data.Add(featureMesh);
                    }
                }
            }
        }
    }
Example #19
0
        private Polyline CreateGeometryFromWayPoints(List <wptType> wayPoints)
        {
            var builder = new PolylineBuilder(new SpatialReference(4326));

            foreach (var wayPoint in wayPoints)
            {
                builder.AddPoint(new MapPoint((double)wayPoint.lon, (double)wayPoint.lat));
            }
            return(builder.ToGeometry());
        }
Example #20
0
        protected override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            //Run on MCT
            return(QueuedTask.Run(() =>
            {
                //get the templates
                var map = MapView.Active.Map;
                IEnumerable <Layer> layers = map.GetLayersAsFlattenedList().AsEnumerable();
                Layer mainLayer = layers.FirstOrDefault(l => l.Name == "main");
                Layer mhLayer = layers.FirstOrDefault(l => l.Name == "Manhole");
                Layer conLayer = layers.FirstOrDefault(l => l.Name == "Connector");

                if ((mainLayer == null) || (mhLayer == null) || (conLayer == null))
                {
                    return false;
                }

                var mainTemplate = mainLayer.GetTemplate("main");
                var mhTemplate = mhLayer.GetTemplate("Manhole");
                var conTemplate = conLayer.GetTemplate("Connector");

                if ((mainTemplate == null) || (mhTemplate == null) || (conTemplate == null))
                {
                    return false;
                }

                var op = new EditOperation()
                {
                    Name = "Create main-connector-manhole",
                    SelectModifiedFeatures = false,
                    SelectNewFeatures = false
                };

                //create the main geom
                var mainGeom = GeometryEngine.Instance.Move(geometry, 0, 0, -20);
                op.Create(mainTemplate, mainGeom);

                //create manhole points and connector
                foreach (var pnt in ((Polyline)geometry).Points)
                {
                    //manhole point at sketch vertex
                    op.Create(mhTemplate, pnt);

                    //vertical connector between mahole and main
                    var conPoints = new List <MapPoint>
                    {
                        pnt,                                                     //top of vertical connector
                        GeometryEngine.Instance.Move(pnt, 0, 0, -20) as MapPoint //bottom of vertical connector
                    };
                    var conPolyLine = PolylineBuilder.CreatePolyline(conPoints);
                    op.Create(conTemplate, conPolyLine);
                }
                return op.Execute();
            }));
        }
        private static Polyline GetCutPolyLine(Geometry geometry)
        {
            IList <Coordinate> cutLine = new List <Coordinate>();

            cutLine.Add(new Coordinate(geometry.Extent.XMin, geometry.Extent.YMin, geometry.Extent.ZMin));
            cutLine.Add(new Coordinate(geometry.Extent.Center));
            cutLine.Add(new Coordinate(geometry.Extent.XMax, geometry.Extent.YMax, geometry.Extent.ZMin));
            var polyLine = PolylineBuilder.CreatePolyline(cutLine, geometry.SpatialReference);

            return(polyLine);
        }
Example #22
0
 /// <summary>
 /// Create a line graphic.
 /// </summary>
 /// <param name="fieldOfJoy"></param>
 /// <param name="a"></param>
 /// <param name="b"></param>
 /// <param name="lineSymbol"></param>
 private static void CreateLine(GraphicsLayer fieldOfJoy, MapPoint a, MapPoint b, CIMLineSymbol lineSymbol)
 {
     fieldOfJoy.AddElement(new CIMLineGraphic()
     {
         Symbol = lineSymbol.MakeSymbolReference(),
         Line   = PolylineBuilder.CreatePolyline(new List <MapPoint>()
         {
             a, b
         }, fieldOfJoy.GetSpatialReference())
     });
 }
Example #23
0
        public static Polyline ToEsriPolyline(this LineString line)
        {
            PolylineBuilder bld = new PolylineBuilder(SpatialReferences.Wgs84);

            foreach (var coord in line.Coordinates)
            {
                bld.AddPoint(new MapPoint(coord.X, coord.Y, SpatialReferences.Wgs84));
            }

            return(bld.ToGeometry());
        }
Example #24
0
        private Task OnBeforeSketchCompletedEvent(BeforeSketchCompletedEventArgs arg)
        {
            //replace curved sketch segments with straight segments

            //return if sketch geometry is not polygon or polyline
            if (!(arg.Sketch.GeometryType == GeometryType.Polyline || arg.Sketch.GeometryType == GeometryType.Polygon))
            {
                return(Task.CompletedTask);
            }

            var sketchMP = arg.Sketch as Multipart;

            //if the sketch doesnt have curves then return
            if (!sketchMP.HasCurves)
            {
                return(Task.CompletedTask);
            }

            //itterate through each sketch part
            var newParts = new List <List <Segment> >();

            foreach (var sketchPart in sketchMP.Parts)
            {
                //itterate through each sketch segment
                var newSegments = new List <Segment>();
                foreach (var sketchSegment in sketchPart)
                {
                    if (sketchSegment.IsCurve)
                    {
                        newSegments.Add(LineBuilder.CreateLineSegment(sketchSegment.StartPoint, sketchSegment.EndPoint));
                    }
                    else
                    {
                        newSegments.Add(sketchSegment);
                    }
                }
                newParts.Add(newSegments);
            }

            //create the new sketch geometry based on sketch type and set back on the sketch
            if (arg.Sketch.GeometryType == GeometryType.Polyline)
            {
                var polyline = PolylineBuilder.CreatePolyline(newParts);
                arg.SetSketchGeometry(polyline);
            }
            else
            {
                var polygon = PolygonBuilder.CreatePolygon(newParts);
                arg.SetSketchGeometry(polygon);
            }

            return(Task.CompletedTask);
        }
Example #25
0
        private Geometry CreatePolyline()
        {
            if (Point1 == null || Point2 == null)
            {
                return(null);
            }

            var nameConverter           = new EnumToFriendlyNameConverter();
            GeodeticCurveType curveType = DeriveCurveType(LineType);
            LinearUnit        lu        = DeriveUnit(LineDistanceType);

            try
            {
                // create line
                var polyline = QueuedTask.Run(() =>
                {
                    var point2Proj = GeometryEngine.Instance.Project(Point2, Point1.SpatialReference);
                    var segment    = LineBuilder.CreateLineSegment(Point1, (MapPoint)point2Proj);
                    return(PolylineBuilder.CreatePolyline(segment));
                }).Result;
                Geometry newline = GeometryEngine.Instance.GeodeticDensifyByLength(polyline, 0, lu, curveType);


                var displayValue = nameConverter.Convert(LineDistanceType, typeof(string), new object(), CultureInfo.CurrentCulture);
                // Hold onto the attributes in case user saves graphics to file later
                LineAttributes lineAttributes = new LineAttributes()
                {
                    mapPoint1    = Point1,
                    mapPoint2    = Point2,
                    distance     = distance,
                    angle        = (double)azimuth,
                    angleunit    = LineAzimuthType.ToString(),
                    distanceunit = displayValue.ToString(),
                    originx      = Point1.X,
                    originy      = Point1.Y,
                    destinationx = Point2.X,
                    destinationy = Point2.Y
                };

                CreateLineFeature(newline, lineAttributes);

                ResetPoints();

                return((Geometry)newline);
            }
            catch (Exception ex)
            {
                // do nothing
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return(null);
            }
        }
Example #26
0
        /// <summary>
        /// Clips the given polylines to the given clipping region. Using the specified viewport extents, this
        /// routine also eliminates duplicate points that would otherwise occur after the viewport transformation.
        /// </summary>
        /// <typeparam name="P"> Output polyline type. </typeparam>
        /// <typeparam name="T"> Input point type. </typeparam>
        /// <param name="sz"> Viewport extents. </param>
        /// <param name="rc"> Logical clipping rectangle. </param>
        /// <param name="polylines"> Input polylines. </param>
        /// <param name="convPnt"> Function converting an input point of type T to System.Windows.Point. </param>
        /// <param name="addPnt"> Procedure adding a System.Windows.Point to the resulting polyline of type P. </param>
        /// <param name="reductionOnly">Specifies that only the reduction should be performed without clipping.</param>
        /// <returns> The reduced and optionally clipped polyline. </returns>
        public static ICollection <P> ClipPolylineReducePoints <P, T>(Size sz, Rect rc, ICollection <ICollection <T> > polylines, Func <T, Point> convPnt, Action <P, Point> addPnt, bool reductionOnly) where P : class, new()
        {
            // re-initialize rc, assuring left <= right and top <= bottom
            rc = new Rect(Math.Min(rc.Left, rc.Right), Math.Min(rc.Top, rc.Bottom), Math.Abs(rc.Width), Math.Abs(rc.Height));

            // create result object storing the clipped lines
            var polylineBuilder = new PolylineBuilder <P>(addPnt, new Size(rc.Width / sz.Width, rc.Height / sz.Height));

            if (polylines == null)
            {
                return(polylineBuilder.Polyline);
            }

            // loop through given polylines
            foreach (ICollection <T> polyline in polylines)
            {
                // enumerator for accessing points
                IEnumerator <T> e = polyline?.GetEnumerator();

                // fetch first point
                if (e == null || !e.MoveNext())
                {
                    continue;
                }

                // initialize starting point
                var p0 = convPnt(e.Current);

                // number of points in current polyline
                int lastPointIndex = polyline.Count - 1;

                // loop through remaining points
                for (int pointIndex = 1; e.MoveNext(); ++pointIndex)
                {
                    // fetch end point. p0 and p1 now mark the start and end point of the current line.
                    var p1 = convPnt(e.Current);

                    // clip the current line. CohenSutherland.clip returns true, if any section of the current line is visible.
                    if (reductionOnly || CohenSutherlandClipping.Clip(rc, ref p0, ref p1))
                    {
                        // Append current line. Append also does the magic of point reduction and line splitting polylines where necessary.
                        polylineBuilder.Append(p0, pointIndex == 1, p1, pointIndex == lastPointIndex);
                    }

                    // current end point is the next starting point
                    p0 = convPnt(e.Current);
                }
            }

            // return the polyline
            return(polylineBuilder.Polyline);
        }
 internal Task <Polyline> CreatePolylineFromPointAsync(MapPoint pt, double tolerance)
 {
     return(QueuedTask.Run(() =>
     {
         // create a polyline from a starting point
         //use a tolerance to construct the second point
         MapPoint pt2 = MapPointBuilder.CreateMapPoint(pt.X + tolerance, pt.Y, pt.SpatialReference);
         return PolylineBuilder.CreatePolyline(new List <MapPoint>()
         {
             pt, pt2
         });
     }));
 }
Example #28
0
        public static Polyline ToPolyline(this List <Vertex> path, MapPoint start, MapPoint end)
        {
            var polyline = new PolylineBuilder(SpatialReferences.Wgs84);

            polyline.AddPoint(start);
            foreach (var v in path)
            {
                var mapPoint = v.Coordinates.ToMapPoint();
                polyline.AddPoint(mapPoint);
            }
            polyline.AddPoint(end);
            return(polyline.ToGeometry());
        }
Example #29
0
        public async Task RedrawObservationAsync()
        {
            await QueuedTask.Run(() =>
            {
                _disposeInnerLine?.Dispose();
                _disposeOuterLine?.Dispose();

                if (_measurementPoint?.IsObservationVisible() ?? false)
                {
                    MapView thisView   = MapView.Active;
                    MapPoint measPoint = _measurementPoint?.Point;
                    MapPoint mapPointObsLine;

                    if ((measPoint != null) && (!double.IsNaN(measPoint.X)) && (!double.IsNaN(measPoint.Y)))
                    {
                        Point winMeasPoint = thisView.MapToScreen(measPoint);
                        Point winObsPoint  = thisView.MapToScreen(Point);

                        double xdir           = ((winMeasPoint.X - winObsPoint.X) * 3) / 2;
                        double ydir           = ((winMeasPoint.Y - winObsPoint.Y) * 3) / 2;
                        Point winPointObsLine = new Point(winObsPoint.X + xdir, winObsPoint.Y + ydir);
                        mapPointObsLine       = thisView.ScreenToMap(winPointObsLine);
                    }
                    else
                    {
                        mapPointObsLine = MapPointBuilder.CreateMapPoint((Point.X + (XDir * DistLine)), (Point.Y + (YDir * DistLine)));
                    }

                    IList <MapPoint> linePointList = new List <MapPoint>();
                    linePointList.Add(mapPointObsLine);
                    linePointList.Add(Point);
                    Polyline polyline = PolylineBuilder.CreatePolyline(linePointList);

                    Color outerColorLine             = Viewer?.Color ?? Color.DarkGray;
                    CIMColor cimOuterColorLine       = ColorFactory.Instance.CreateColor(Color.FromArgb(255, outerColorLine));
                    CIMLineSymbol cimOuterLineSymbol = SymbolFactory.Instance.DefaultLineSymbol;
                    cimOuterLineSymbol.SetColor(cimOuterColorLine);
                    cimOuterLineSymbol.SetSize(OuterLineSize);
                    CIMSymbolReference cimOuterLineSymbolRef = cimOuterLineSymbol.MakeSymbolReference();
                    _disposeOuterLine = thisView.AddOverlay(polyline, cimOuterLineSymbolRef);

                    Color innerColorLine             = Color.LightGray;
                    CIMColor cimInnerColorLine       = ColorFactory.Instance.CreateColor(innerColorLine);
                    CIMLineSymbol cimInnerLineSymbol = SymbolFactory.Instance.DefaultLineSymbol;
                    cimInnerLineSymbol.SetColor(cimInnerColorLine);
                    cimInnerLineSymbol.SetSize(InnerLineSize);
                    CIMSymbolReference cimInnerLineSymbolRef = cimInnerLineSymbol.MakeSymbolReference();
                    _disposeInnerLine = thisView.AddOverlay(polyline, cimInnerLineSymbolRef);
                }
            });
        }
Example #30
0
        private static Geometry FromEsriShapeBuffer([NotNull] byte[] byteArray,
                                                    [CanBeNull] SpatialReference spatialReference)
        {
            var shapeType = EsriShapeFormatUtils.GetShapeType(byteArray);

            if (byteArray.Length == 5 && shapeType == EsriShapeType.EsriShapeNull)
            {
                // in case the original geometry was empty, ExportToWkb does not store byte order nor geometry type.
                throw new ArgumentException(
                          "The provided byte array represents an empty geometry with no geometry type information. Unable to create geometry");
            }

            Geometry result;

            var geometryType = EsriShapeFormatUtils.TranslateEsriShapeType(shapeType);

            switch (geometryType)
            {
            case ProSuiteGeometryType.Point:
                result = MapPointBuilder.FromEsriShape(byteArray, spatialReference);
                break;

            case ProSuiteGeometryType.Polyline:
                result = PolylineBuilder.FromEsriShape(byteArray, spatialReference);
                break;

            case ProSuiteGeometryType.Polygon:
                result = PolygonBuilder.FromEsriShape(byteArray, spatialReference);
                break;

            case ProSuiteGeometryType.Multipoint:
                result = MultipointBuilder.FromEsriShape(byteArray, spatialReference);
                break;

            case ProSuiteGeometryType.MultiPatch:
                result = MultipatchBuilder.FromEsriShape(byteArray, spatialReference);
                break;

            case ProSuiteGeometryType.Bag:
                result = GeometryBagBuilder.FromEsriShape(
                    byteArray, spatialReference);                             // experimental
                break;

            default:
                throw new ArgumentOutOfRangeException(
                          $"Unsupported geometry type {shapeType}");
            }

            return(result);
        }
Example #31
0
        private bool ValidateConnectivity(Dictionary <int, List <Polyline> > parts)
        {
            var geoEngine = GeometryEngine.Instance;
            var builder   = new PolylineBuilder(SpatialReferenceBuilder.CreateSpatialReference(26912));
            var partLines = new List <Polyline>();

            foreach (int partNum in parts.Keys)
            {
                foreach (Polyline polyline in parts[partNum])
                {
                    builder.AddPart(polyline.Points);
                }

                var partLine = geoEngine.SimplifyPolyline(builder.ToGeometry(), SimplifyType.Network);

                if (partLine.PartCount > 1)
                {
                    ShowInvalidOverlays(partLine);

                    return(false);
                }

                partLines.Add(partLine);
                builder.SetEmpty();
            }

            foreach (Polyline partLine in partLines)
            {
                // check to make sure that the last point of the main polyline matches with the first point of the new part
                var mainLine = builder.ToGeometry();
                if (mainLine.PointCount > 1 && mainLine.Points[mainLine.PointCount - 1].IsEqual(partLine.Points[0]))
                {
                    builder.AddPart(partLine.Points);
                }
                else
                {
                    builder.AddPart(partLine.Points.Reverse());
                }
            }
            var routeLine = geoEngine.SimplifyPolyline(builder.ToGeometry(), SimplifyType.Network, true);

            if (routeLine.PartCount > 1)
            {
                ShowInvalidOverlays(routeLine);

                return(false);
            }

            return(true);
        }
Example #32
0
        /// <summary>
        /// Create sample polygon feature using the point geometries from the multi-point feature using the 
        /// ConvexHull method provided by the GeometryEngine.
        /// </summary>
        /// <param name="polygonLayer">Polygon geometry feature layer used to add the new feature.</param>
        /// <param name="lineLayer">The polyline feature layer containing the features used to construct the polygon.</param>
        /// <returns></returns>
        private Task<bool> constructSamplePolygon(FeatureLayer polygonLayer, FeatureLayer lineLayer)
        {

            // execute the fine grained API calls on the CIM main thread
            return QueuedTask.Run(() =>
            {
                // get the underlying feature class for each layer
                var polygonFeatureClass = polygonLayer.GetTable() as FeatureClass;
                var polygonDefinition = polygonFeatureClass.GetDefinition() as FeatureClassDefinition;
                var lineFeatureClass = lineLayer.GetTable() as FeatureClass;

                // construct a cursor to retrieve the line features
                var lineCursor = lineFeatureClass.Search(null, false);

                // set up the edit operation for the feature creation
                var createOperation = new EditOperation()
                {
                    Name = "Create polygons",
                    SelectNewFeatures = false
                };

                PolylineBuilder polylineBuilder = new PolylineBuilder(polygonDefinition.GetSpatialReference());

                while (lineCursor.MoveNext())
                {
                    // retrieve the first feature
                    var lineFeature = lineCursor.Current as Feature;

                    // add the coordinate collection of the current geometry into our overall list of collections
                    var polylineGeometry = lineFeature.GetShape() as Polyline;
                    polylineBuilder.AddParts(polylineGeometry.Parts);
                }

                // use the ConvexHull method from the GeometryEngine to construct the polygon geometry
                var newPolygon = GeometryEngine.ConvexHull(polylineBuilder.ToGeometry()) as Polygon;

                // queue the polygon creation
                createOperation.Create(polygonLayer, newPolygon);

                // execute the edit (polygon create) operation
                return createOperation.ExecuteAsync();
            });
        }
        /// <summary>
        /// Create polyline features from graphics and add to table
        /// </summary>
        /// <param name="graphicsList">List of graphics to add to table</param>
        /// <returns></returns>
        private static async Task CreateFeatures(List<Graphic> graphicsList)
        {
            RowBuffer rowBuffer = null;
                
            try
            {
                await QueuedTask.Run(() =>
                {
                    var layer = MapView.Active.GetSelectedLayers()[0];
                    if (layer is FeatureLayer)
                    {
                        var featureLayer = layer as FeatureLayer;
                        using (var table = featureLayer.GetTable())
                        {
                            TableDefinition definition = table.GetDefinition();
                            int shapeIndex = definition.FindField("Shape");
                                
                            //EditOperation editOperation = new EditOperation();
                            //editOperation.Callback(context =>
                            //{
                                foreach (Graphic graphic in graphicsList)
                                {
                                    //int nameIndex = featureClassDefinition.FindField("NAME");
                                    rowBuffer = table.CreateRowBuffer();

                                    if (graphic.Geometry is Polyline)
                                        rowBuffer[shapeIndex] = new PolylineBuilder(graphic.Geometry as Polyline).ToGeometry();
                                    else if (graphic.Geometry is Polygon)
                                        rowBuffer[shapeIndex] = new PolygonBuilder(graphic.Geometry as Polygon).ToGeometry();

                                    Row row = table.CreateRow(rowBuffer);

                                    //To Indicate that the Map has to draw this feature and/or the attribute table to be updated
                                    //context.Invalidate(row);
                                }
                            //});
                            //bool editResult = editOperation.Execute();
                            //bool saveResult = await Project.Current.SaveEditsAsync();
                        }
                    }
                });

            }
            catch (GeodatabaseException exObj)
            {
                Console.WriteLine(exObj);
                throw;
            }
            finally
            {
                if (rowBuffer != null)
                    rowBuffer.Dispose();
            }
        }
		// Creates a polyline with four paths in the shape of a box centered at the given point
		private Polyline CreatePolylineBox(MapPoint center, double length)
		{
			var halfLen = length / 2.0;
			var spacer = length / 10.0;

			PolylineBuilder polylineBuilder = new PolylineBuilder(MyMapView.SpatialReference);
			
			// First path
			polylineBuilder.AddPart(new Geometry.PointCollection()
				{
					new MapPoint(center.X - halfLen + spacer, center.Y + halfLen),
					new MapPoint(center.X + halfLen - spacer, center.Y + halfLen)
				});

			// Second path
			polylineBuilder.AddPart(new Geometry.PointCollection()
				{
					new MapPoint(center.X + halfLen, center.Y + halfLen - spacer),
					new MapPoint(center.X + halfLen, center.Y - halfLen + spacer)
				});

			// Third path
			polylineBuilder.AddPart(new Geometry.PointCollection()
				{
					new MapPoint(center.X + halfLen - spacer, center.Y - halfLen),
					new MapPoint(center.X - halfLen + spacer, center.Y - halfLen)
				});

			// Forth path
			polylineBuilder.AddPart(new Geometry.PointCollection()
				{
					new MapPoint(center.X - halfLen, center.Y - halfLen + spacer),
					new MapPoint(center.X - halfLen, center.Y + halfLen - spacer)
				});

			return polylineBuilder.ToGeometry();
		}
		public static async Task<Polyline> DrawPolylineAsync(SceneView sceneView, System.Threading.CancellationToken cancellationToken)
		{
			var tcs = new TaskCompletionSource<Polyline>();
			PolylineBuilder polylineBuilder = new PolylineBuilder(sceneView.SpatialReference);
			var sketchlayer = CreateSketchLayer(sceneView);
			Graphic lineGraphic = new Graphic() { Symbol = DefaultLineSymbol };
			Graphic lineMoveGraphic = new Graphic() { Symbol = DefaultLineMoveSymbol };
			sketchlayer.Graphics.AddRange(new Graphic[] { lineGraphic, lineMoveGraphic });
			Action cleanupEvents = SetUpHandlers(sceneView,
				(p) => //On mouse move, move completion line around
				{
					if (p != null && polylineBuilder.Parts.Count > 0 && polylineBuilder.Parts[0].Count > 0)
					{
						lineMoveGraphic.Geometry = new Polyline(new MapPoint[] { polylineBuilder.Parts[0].Last().EndPoint, p });
					}
				},
				(p) => //On tap add a vertex
				{
					if (p != null)
					{
						polylineBuilder.AddPoint(p);
						if (polylineBuilder.Parts.Count > 0 && polylineBuilder.Parts[0].Count >= 1)
							lineGraphic.Geometry = polylineBuilder.ToGeometry();
					}
				},
				(p) => //View tapped - completes task and returns point
				{
					tcs.SetResult(polylineBuilder.ToGeometry());
				});
			Action cleanup = () =>
			{
				cleanupEvents();
				sceneView.GraphicsOverlays.Remove(sketchlayer);
			};
			cancellationToken.Register(() => tcs.SetCanceled());

			Polyline result = null;
			try
			{
				result = await tcs.Task;
			}
			finally
			{
				cleanup();
			}
			return result;
		}
        /// <summary>
        /// Edit existing <see cref="Polyline"/>. This will activate editing experience on the map. Edit is completed on double click.
        /// </summary>
        /// <param name="sceneView">The <see cref="SceneView"/> that is used for editing.</param>
        /// <exception cref="TaskCanceledException">If previous task wasn't completed, <see cref="TaskCanceledException"/>
        /// will be thrown. The task is cancelled if <see cref="Cancel"/> method or if any other draw or edit method is called.
        /// </exception>
        /// <returns>Return edited <see cref="Polygon"/> based on the user interactions.</returns>
        public static async Task<Polyline> EditPolylineAsync(SceneView sceneView, Polyline polyline)
		{
            Initialize();

			var tcs = new TaskCompletionSource<Polyline>();
			PolylineBuilder polylineBuilder = new PolylineBuilder(sceneView.SpatialReference);
			var sketchlayer = CreateSketchLayer(sceneView);
			var vertexlayer = CreateSketchLayer(sceneView);

			// Create vertices from the original polyline
			var vertices = new List<Graphic>();
			foreach (var vertex in (polyline.Parts[0].GetPoints()))
				vertices.Add(new Graphic(vertex, DefaultVertexSymbol));

			// Default to original polyline
			var newPolyline = new Polyline(polyline.Parts);

			Graphic lineGraphic = new Graphic(newPolyline) { Symbol = DefaultLineSymbol };
			Graphic lineMoveGraphic = new Graphic() { Symbol = DefaultLineMoveSymbol };

			sketchlayer.Graphics.AddRange(new Graphic[] { lineGraphic, lineMoveGraphic });
			vertexlayer.Graphics.AddRange(vertices);

			CancellationTokenSource tokenSource = null;
			Graphic selectedVertex = null;
			bool isEditingVertex = false;

			Action cleanupEvents = SetUpHandlers(sceneView,
				(p) => //On mouse move, move completion line around
				{
					if (p != null && isEditingVertex)
					{
						// Update visual indicator polyline
						var vertexPoints = newPolyline.Parts[0].GetPoints().ToList();
						var index = vertexPoints
							.IndexOf(vertexPoints.Where
								(point => GeometryEngine.Equals(point, selectedVertex.Geometry)).First());
						var temporaryVertices = new List<MapPoint>();

						if (index > 0)
							temporaryVertices.Add(vertexPoints[index - 1]); // Add previous segment
						temporaryVertices.Add(p);
						if (index != vertexPoints.Count() - 1)
							temporaryVertices.Add(vertexPoints[index + 1]); // Add next segment

						var builder = new PolylineBuilder(temporaryVertices);
						lineMoveGraphic.Geometry = builder.ToGeometry();
						lineMoveGraphic.IsVisible = true;
					}
				},
				async (p) => //On tap add a vertex
				{
					if (p == null) return;
					if (isEditingVertex) return;
					if (selectedVertex != null) selectedVertex.IsSelected = false;

					selectedVertex = await vertexlayer.HitTestAsync(sceneView, sceneView.LocationToScreen(p));

					// No vertex found so return
					if (selectedVertex == null)
						return;

					isEditingVertex = true;
					selectedVertex.IsSelected = true;
					tokenSource = new CancellationTokenSource();
					try
					{
						var newPoint = await SceneDrawHelper.DrawPointAsync(sceneView, tokenSource.Token);

						if (newPoint == null) return;
						
						var vertexPoints = newPolyline.Parts[0].GetPoints();
						var index = vertexPoints.ToList()
							.IndexOf(vertexPoints.Where
								(point => GeometryEngine.Equals(point, selectedVertex.Geometry)).First());
						var builder = new PolylineBuilder(vertexPoints);
						builder.Parts[0].MovePoint(index, newPoint);

						lineGraphic.Geometry = null;

						// Update polyline
						newPolyline = builder.ToGeometry();
						lineGraphic.Geometry = newPolyline;

						// Update vertex
						selectedVertex.Geometry = newPoint;
						tokenSource = null;
					}
					catch (TaskCanceledException tce)
					{
					}
					finally
					{
						lineMoveGraphic.IsVisible = false;
						selectedVertex.IsSelected = false;
						selectedVertex = null;
						isEditingVertex = false;
					}
				},
				(p) => // Double tapped - completes task and returns new polyline
                {
					tcs.SetResult(newPolyline);
				});
			Action cleanup = () =>
			{
				cleanupEvents();
                sceneView.GraphicsOverlays.Remove(sketchlayer);
                sceneView.GraphicsOverlays.Remove(vertexlayer);
				if (tokenSource != null) tokenSource.Cancel();
                Cleanup();
			};
            _drawTaskTokenSource.Token.Register(() => tcs.SetCanceled());

			Polyline result = null;
			try
			{
				result = await tcs.Task;
			}
			finally
			{
				cleanup();
			}
			return result;
		}
        private void GeneratePolyGeometry()
        {
            //PolyCoordinates.ToList()
            List<MapPoint> points = new List<MapPoint>();
            foreach (CoordinateObject coordObject in PolyCoordinates)
            {
                points.Add(coordObject.MapPoint);
            }

            ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
            {
                if (GeometryType == GeometryType.Polyline)
                {
                    PolylineBuilder polylineBuilder = new PolylineBuilder(points);
                    polylineBuilder.HasZ = true;
                    MapGeometry = polylineBuilder.ToGeometry();
                }
                else if (GeometryType == GeometryType.Polygon)
                {
                    PolygonBuilder polygonBuilder = new PolygonBuilder(points);
                    polygonBuilder.HasZ = true;
                    MapGeometry = polygonBuilder.ToGeometry();
                }
            });
        }