Example #1
0
        public static MapPoint GetRandomPointInGraphicsCollection(IList <Graphic> graphics)
        {
            Random   random   = new Random();
            Graphic  graphic1 = graphics[random.Next(0, graphics.Count)];
            Graphic  graphic2 = graphics[random.Next(0, graphics.Count)];
            Geometry geom1    = graphic1.Geometry;
            Geometry geom2    = graphic2.Geometry;

            if (geom1 is MapPoint)
            {
                return(geom1 as MapPoint);
            }

            Envelope mbr            = GeometryEngine.Union(geom1, geom2).Extent;
            double   x              = random.NextDouble() * (mbr.XMax - mbr.XMin) + mbr.XMin;
            double   y              = random.NextDouble() * (mbr.YMax - mbr.YMin) + mbr.YMin;
            MapPoint randomLocation = new MapPoint(x, y, SpatialReferences.Wgs84);

            return(GetNearestCoordinateInGraphicsCollection(randomLocation, new List <Graphic> {
                graphic1,                                                                                 /* graphic2 */
            }));
        }
Example #2
0
        /// <summary>
        /// Returns the point at a given geodesic distance along a line.
        /// </summary>
        /// <param name="line">The line.</param>
        /// <param name="distance">The geodesic distance along the line.</param>
        /// <returns>
        /// A point along the line; if <paramref name="distance"/> is longer than the line, returns <c>null</c>.
        /// </returns>
        public static MapPoint CreatePointAlongGeodetic(Polyline line, double distance)
        {
            // Determine the points that bound `distance`
            var points         = line.Parts.SelectMany(part => part.Points).ToArray();
            var searchDistance = 0.0;

            for (int i = 0; i < points.Length - 1; i++)
            {
                var point1 = points[i];
                var point2 = points[i + 1];

                // Ignore part boundaries
                if (point1.X == point2.X && point1.Y == point2.Y)
                {
                    continue;
                }

                // Find the distance between each point
                var pointDistanceResult = GeometryEngine.DistanceGeodetic(point1, point2, LinearUnits.Meters,
                                                                          AngularUnits.Degrees, GeodeticCurveType.Geodesic);
                var pointDistance = pointDistanceResult.Distance;
                var pointBearing  = pointDistanceResult.Azimuth1;

                // Determine whether `distance` falls between these points
                if (distance < searchDistance + pointDistance)
                {
                    var segmentDistance = distance - searchDistance;

                    // Find the extact position of the point
                    return(CreatePointAlongGeodetic(point1, pointBearing, segmentDistance));
                }

                // Continue the search
                searchDistance += pointDistance;
            }

            // Point could not be found
            return(null);
        }
Example #3
0
        private void AnimationTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            // Note: the contents of this function are solely related to animating the taxi

            // Increment the frame counter
            _frameIndex++;

            // Reset the frame counter once one segment of the path has been travelled
            if (_frameIndex == _frameMax)
            {
                _frameIndex = 0;

                // Start navigating toward the next point
                _pointIndex++;

                // Restart if finished circuit
                if (_pointIndex == _points.Length)
                {
                    _pointIndex = 0;
                }
            }

            // Get the point the taxi is travelling from
            MapPoint starting = _points[_pointIndex];
            // Get the point the taxi is travelling to
            MapPoint ending = _points[(_pointIndex + 1) % _points.Length];
            // Calculate the progress based on the current frame
            double progress = _frameIndex / (double)_frameMax;
            // Calculate the position of the taxi when it is {progress}% of the way through
            MapPoint intermediatePoint = InterpolatedPoint(starting, ending, progress);

            // Update the taxi geometry
            _taxiGraphic.Geometry = intermediatePoint;

            // Update the taxi rotation.
            GeodeticDistanceResult distance = GeometryEngine.DistanceGeodetic(starting, ending, LinearUnits.Meters, AngularUnits.Degrees, GeodeticCurveType.Geodesic);

            ((ModelSceneSymbol)_taxiGraphic.Symbol).Heading = distance.Azimuth1;
        }
Example #4
0
        private async void ConvexHullButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Create a multi-point geometry from the user tapped input map points.
                Multipoint inputMultipoint = new Multipoint(_inputPointCollection);

                // Get the returned result from the convex hull operation.
                Geometry convexHullGeometry = GeometryEngine.ConvexHull(inputMultipoint);

                // Create a simple line symbol for the outline of the convex hull graphic(s).
                SimpleLineSymbol convexHullSimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid,
                                                                                   Windows.UI.Colors.Blue, 4);

                // Create the simple fill symbol for the convex hull graphic(s) - comprised of a fill style, fill
                // color and outline. It will be a hollow (i.e.. see-through) polygon graphic with a thick red outline.
                SimpleFillSymbol convexHullSimpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Null,
                                                                                   Windows.UI.Colors.Red, convexHullSimpleLineSymbol);

                // Create the graphic for the convex hull - comprised of a polygon shape and fill symbol.
                Graphic convexHullGraphic = new Graphic(convexHullGeometry, convexHullSimpleFillSymbol);

                // Set the Z index for the convex hull graphic so that it appears below the initial input user
                // tapped map point graphics added earlier.
                convexHullGraphic.ZIndex = 0;

                // Add the convex hull graphic to the graphics overlay collection.
                _graphicsOverlay.Graphics.Add(convexHullGraphic);

                // Disable the button after has been used.
                ConvexHullButton.IsEnabled = false;
            }
            catch (System.Exception ex)
            {
                // Display an error message if there is a problem generating convex hull operation.
                MessageDialog theMessageDialog = new MessageDialog("Geometry Engine Failed: " + ex.Message);
                await theMessageDialog.ShowAsync();
            }
        }
Example #5
0
        private void UpdateViewExtentLabels()
        {
            // Get the current view point for the map view
            Viewpoint currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);

            if (currentViewpoint == null)
            {
                return;
            }

            // Get the current map extent (envelope) from the view point
            Envelope currentExtent = currentViewpoint.TargetGeometry as Envelope;

            // Project the current extent to geographic coordinates (longitude / latitude)
            Envelope currentGeoExtent = GeometryEngine.Project(currentExtent, SpatialReferences.Wgs84) as Envelope;

            // Fill the app text boxes with min / max longitude (x) and latitude (y) to four decimal places
            XMinTextBox.Text = currentGeoExtent.XMin.ToString("0.####");
            YMinTextBox.Text = currentGeoExtent.YMin.ToString("0.####");
            XMaxTextBox.Text = currentGeoExtent.XMax.ToString("0.####");
            YMaxTextBox.Text = currentGeoExtent.YMax.ToString("0.####");
        }
        private async void Initialize()
        {
            // Initialize the map with an oceans basemap
            _myMapView.Map = new Map(Basemap.CreateOceans());

            // Get the path to the ENC Exchange Set
            string encPath = DataManager.GetDataFolder("9d2987a825c646468b3ce7512fb76e2d", "ExchangeSetwithoutUpdates", "ENC_ROOT", "CATALOG.031");

            // Create the Exchange Set
            // Note: this constructor takes an array of paths because so that update sets can be loaded alongside base data
            EncExchangeSet myEncExchangeSet = new EncExchangeSet(encPath);

            // Wait for the layer to load
            await myEncExchangeSet.LoadAsync();

            // Store a list of data set extent's - will be used to zoom the mapview to the full extent of the Exchange Set
            List <Envelope> dataSetExtents = new List <Envelope>();

            // Add each data set as a layer
            foreach (EncDataset myEncDataSet in myEncExchangeSet.Datasets)
            {
                EncLayer myEncLayer = new EncLayer(new EncCell(myEncDataSet));

                // Add the layer to the map
                _myMapView.Map.OperationalLayers.Add(myEncLayer);

                // Wait for the layer to load
                await myEncLayer.LoadAsync();

                // Add the extent to the list of extents
                dataSetExtents.Add(myEncLayer.FullExtent);
            }

            // Use the geometry engine to compute the full extent of the ENC Exchange Set
            Envelope fullExtent = GeometryEngine.CombineExtents(dataSetExtents);

            // Set the viewpoint
            _myMapView.SetViewpoint(new Viewpoint(fullExtent));
        }
Example #7
0
        private async void OnMapViewTapped(object sender, GeoViewInputEventArgs e)
        {
            try
            {
                // Define the selection tolerance (half the marker symbol size so that any click on the symbol will select the feature)
                double tolerance = 14;

                // Convert the tolerance to map units
                double mapTolerance = tolerance * MyMapView.UnitsPerPixel;

                // Get the tapped point
                MapPoint geometry = e.Location;

                // Normalize the geometry if wrap-around is enabled
                //    This is necessary because of how wrapped-around map coordinates are handled by Runtime
                //    Without this step, querying may fail because wrapped-around coordinates are out of bounds.
                if (MyMapView.IsWrapAroundEnabled)
                {
                    geometry = GeometryEngine.NormalizeCentralMeridian(geometry) as MapPoint;
                }

                // Define the envelope around the tap location for selecting features
                var selectionEnvelope = new Envelope(geometry.X - mapTolerance, geometry.Y - mapTolerance, geometry.X + mapTolerance,
                                                     geometry.Y + mapTolerance, MyMapView.Map.SpatialReference);

                // Define the query parameters for selecting features
                var queryParams = new QueryParameters();

                // Set the geometry to selection envelope for selection by geometry
                queryParams.Geometry = selectionEnvelope;

                // Select the features based on query parameters defined above
                await _featureLayer.SelectFeaturesAsync(queryParams, Esri.ArcGISRuntime.Mapping.SelectionMode.New);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Sample error", ex.ToString());
            }
        }
		private async Task doCalculateAreaAndLength()
		{
			try
			{
				//Wait for user to draw
				var geom = await MyMapView.Editor.RequestShapeAsync(DrawShape.Polygon);

				//show geometry on map
				_graphicsOverlay.Graphics.Clear();

				var g = new Graphic { Geometry = geom, Symbol = LayoutRoot.Resources["DefaultFillSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol };
				_graphicsOverlay.Graphics.Add(g);


				//Calculate results
				var areaPlanar = GeometryEngine.Area(geom);
				ResultsAreaPlanar.Text = string.Format("{0} sq. miles", (areaPlanar * toSqMilesConversion).ToString("n3"));

				var perimPlanar = GeometryEngine.Length(geom);
				ResultsPerimeterPlanar.Text = string.Format("{0} miles", (perimPlanar * toMilesConversion).ToString("n3"));


				var areaGeodesic = GeometryEngine.GeodesicArea(geom);
				ResultsAreaGeodesic.Text = string.Format("{0} sq. miles", (areaGeodesic * toSqMilesConversion).ToString("n3"));

				var perimGeodesic = GeometryEngine.GeodesicLength(geom);
				ResultsPerimeterGeodesic.Text = string.Format("{0} miles", (perimGeodesic * toMilesConversion).ToString("n3"));

				Instructions.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
				Results.Visibility = Windows.UI.Xaml.Visibility.Visible;

			}
			catch (System.Threading.Tasks.TaskCanceledException)
			{
				var dlg = new MessageDialog("Current sketch has been canceled.", "Task Canceled!");
				var _x = dlg.ShowAsync();
			}

		}
        private void MapView_Tapped(object sender, Esri.ArcGISRuntime.Xamarin.Forms.GeoViewInputEventArgs e)
        {
            // Get the tapped point - this is in the map's spatial reference,
            // which in this case is WebMercator because that is the SR used by the included basemaps.
            MapPoint tappedPoint = e.Location;

            // Update the graphics.
            MyMapView.GraphicsOverlays[0].Graphics.Clear();
            MyMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(tappedPoint));

            // Project the point to WGS84
            MapPoint projectedPoint = (MapPoint)GeometryEngine.Project(tappedPoint, SpatialReferences.Wgs84);

            // Format the results in strings.
            string originalCoords  = $"Original: {tappedPoint.X:F4}, {tappedPoint.Y:F4}";
            string projectedCoords = $"Projected: {projectedPoint.X:F4}, {projectedPoint.Y:F4}";

            // Define a callout and show it in the map view.
            CalloutDefinition calloutDef = new CalloutDefinition(projectedCoords, originalCoords);

            MyMapView.ShowCalloutAt(tappedPoint, calloutDef);
        }
Example #10
0
        private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
        {
            // Show the loading indicator.
            _activityIndicator.StartAnimating();

            // Clear previous user click location and the viewshed geoprocessing task results.
            _inputOverlay.Graphics.Clear();
            _resultOverlay.Graphics.Clear();

            // Get the tapped point.
            MapPoint geometry = e.Location;

            // Create a marker graphic where the user clicked on the map and add it to the existing graphics overlay.
            Graphic inputGraphic = new Graphic(geometry);

            _inputOverlay.Graphics.Add(inputGraphic);

            // Normalize the geometry if wrap-around is enabled.
            //    This is necessary because of how wrapped-around map coordinates are handled by Runtime.
            //    Without this step, the task may fail because wrapped-around coordinates are out of bounds.
            if (_myMapView.IsWrapAroundEnabled)
            {
                geometry = (MapPoint)GeometryEngine.NormalizeCentralMeridian(geometry);
            }

            try
            {
                // Execute the geoprocessing task using the user click location.
                await CalculateViewshed(geometry);
            }
            catch (Exception ex)
            {
                new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
            finally
            {
                _activityIndicator.StopAnimating();
            }
        }
        private async void HandleMapTap(MapPoint mapLocation)
        {
            // Normalize geometry - important for geometries that will be sent to a server for processing.
            mapLocation = (MapPoint)GeometryEngine.NormalizeCentralMeridian(mapLocation);

            switch (_currentSampleState)
            {
            case SampleState.AddingBarriers:
                // Buffer the tapped point to create a larger barrier.
                Geometry bufferedGeometry = GeometryEngine.BufferGeodetic(mapLocation, 500, LinearUnits.Meters);

                // Create the graphic to show the barrier.
                Graphic barrierGraphic = new Graphic(bufferedGeometry, _barrierSymbol);

                // Add the graphic to the overlay - this will cause it to appear on the map.
                _barriersOverlay.Graphics.Add(barrierGraphic);
                break;

            case SampleState.AddingStops:
                // Get the name of this stop.
                string stopName = $"{_stopsOverlay.Graphics.Count + 1}";

                // Create the marker to show underneath the stop number.
                PictureMarkerSymbol pushpinMarker = await GetPictureMarker();

                // Create the text symbol for showing the stop.
                TextSymbol stopSymbol = new TextSymbol(stopName, Color.White, 15, HorizontalAlignment.Center, VerticalAlignment.Middle);
                stopSymbol.OffsetY = 15;

                CompositeSymbol combinedSymbol = new CompositeSymbol(new MarkerSymbol[] { pushpinMarker, stopSymbol });

                // Create the graphic to show the stop.
                Graphic stopGraphic = new Graphic(mapLocation, combinedSymbol);

                // Add the graphic to the overlay - this will cause it to appear on the map.
                _stopsOverlay.Graphics.Add(stopGraphic);
                break;
            }
        }
Example #12
0
        private void ClipButton_TouchUpInside(object sender, EventArgs e)
        {
            try
            {
                // Remove the Colorado graphic from the input geometries graphics overlay collection. That way it will be easier
                // to see the clip versions of the GeometryEngine.Clip operation.
                _inputGeometriesGraphicsOverlay.Graphics.Remove(_coloradoGraphic);

                // Loop through each graphic in the input geometries for the clip operation.
                foreach (Graphic oneGraphic in _inputGeometriesGraphicsOverlay.Graphics)
                {
                    // Perform the clip operation. The first parameter of the clip operation will always be the Colorado graphic.
                    // The second parameter of the clip operation will be one of the 3 different clip geometries (_outsideGraphic,
                    // _containedGraphic, or _intersectingGraphic).
                    Geometry myGeometry = GeometryEngine.Clip(_coloradoGraphic.Geometry, (Envelope)oneGraphic.Geometry);

                    // Only work on returned geometries that are not null.
                    if (myGeometry != null)
                    {
                        // Create the graphic as a result of the clip operation using the same symbology that was defined for
                        // the _coloradoGraphic defined in the Initialize() method previously.
                        Graphic clippedGraphic = new Graphic(myGeometry, _coloradoGraphic.Symbol);

                        // Add the clipped graphic to the clip areas graphics overlay collection.
                        _clipAreasGraphicsOverlay.Graphics.Add(clippedGraphic);
                    }
                }

                // Disable the button after has been used.
                (sender as UIBarButtonItem).Enabled = false;
            }
            catch (Exception ex)
            {
                // Display an error message if there is a problem generating clip operation.
                UIAlertController alertController = UIAlertController.Create("Geometry Engine Failed!", ex.Message, UIAlertControllerStyle.Alert);
                alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alertController, true, null);
            }
        }
        private async Task CreateSubRegionLayerGraphics(IEnumerable <Graphic> statistics)
        {
            QueryTask queryTask = new QueryTask(new Uri(LAYER_URL));
            Query     query     = new Query("1=1")
            {
                ReturnGeometry      = true,
                OutSpatialReference = mapView.SpatialReference,
                OutFields           = new OutFields(new List <string> {
                    "sub_region"
                })
            };

            var states = await queryTask.ExecuteAsync(query);

            // Create unioned graphics from state geometries for each region
            var regions = states.FeatureSet.Features
                          .GroupBy(g => g.Attributes["sub_region"], g => g.Geometry)
                          .Select(grp => new Graphic(GeometryEngine.Union(grp), statistics.First(stat => grp.Key.Equals(stat.Attributes["sub_region"])).Attributes));

            _graphicsLayer.Graphics.Clear();
            _graphicsLayer.Graphics.AddRange(regions);
        }
        private void MapView_Tapped(object sender, Esri.ArcGISRuntime.Xamarin.Forms.GeoViewInputEventArgs e)
        {
            // Make sure the user isn't adding too many stops.
            if (_stopsOverlay.Graphics.Count >= 5)
            {
                ShowMessage("Can't add stop.", "Sample limits to 5 stops per route.");
                return;
            }

            // Make sure the stop is valid before proceeding.
            if (!GeometryEngine.Contains(_routableArea, e.Location))
            {
                ShowMessage("Can't add stop.", "That location is outside of the area where offline routing data is available.");
                return;
            }

            // Add the stop for the tapped position.
            AddStop(e.Position);

            // Update the route with the final list of stops.
            UpdateRoute((TravelMode)TravelModesCombo.SelectedItem);
        }
Example #15
0
        private void LocationButton_Checked(object sender, RoutedEventArgs e)
        {
            _myLocationOverlay.Graphics.Clear();
            var point  = MyMapView.LocationDisplay.CurrentLocation.Location;
            var buffer = GeometryEngine.GeodesicBuffer(point, 300, LinearUnits.Meters);

            MyMapView.SetView(buffer.Extent);

            var symbol = new PictureMarkerSymbol()
            {
                Width = 48, Height = 48, YOffset = 24
            };

            symbol.SetSourceAsync(new Uri("ms-appx:///Assets/CollPin.png"));
            var graphic = new Graphic()
            {
                Geometry = point,
                Symbol   = symbol
            };

            _myLocationOverlay.Graphics.Add(graphic);
        }
Example #16
0
        // Continuosly accept polygons from the user and calculate label points
        private async Task CalculateLabelPointsAsync()
        {
            try
            {
                await mapView.LayersLoadedAsync();

                while (mapView.Extent != null)
                {
                    if (mapView.Editor.IsActive)
                    {
                        mapView.Editor.Cancel.Execute(null);
                    }

                    //Get the input polygon geometry from the user
                    var poly = await mapView.Editor.RequestShapeAsync(DrawShape.Polygon, ((SimpleRenderer)labelGraphics.Renderer).Symbol);

                    if (poly != null)
                    {
                        //Add the polygon drawn by the user
                        labelGraphics.Graphics.Add(new Graphic(poly));

                        //Get the label point for the input geometry
                        var labelPoint = GeometryEngine.LabelPoint(poly);
                        if (labelPoint != null)
                        {
                            labelGraphics.Graphics.Add(new Graphic(labelPoint, _pictureMarkerSymbol));
                        }
                    }
                }
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
                MessageBox.Show("Label Point Error: " + ex.Message, "Label Point Sample");
            }
        }
        private void ConvexHullButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Create a multi-point geometry from the user tapped input map points.
                Multipoint inputMultipoint = new Multipoint(_inputPointCollection);

                // Get the returned result from the convex hull operation.
                Geometry convexHullGeometry = GeometryEngine.ConvexHull(inputMultipoint);

                // Create a simple line symbol for the outline of the convex hull graphic(s).
                SimpleLineSymbol convexHullSimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 4);

                // Create the simple fill symbol for the convex hull graphic(s) - comprised of a fill style, fill
                // color and outline. It will be a hollow (i.e.. see-through) polygon graphic with a thick red outline.
                SimpleFillSymbol convexHullSimpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Null, System.Drawing.Color.Red, convexHullSimpleLineSymbol);

                // Create the graphic for the convex hull - comprised of a polygon shape and fill symbol.
                Graphic convexHullGraphic = new Graphic(convexHullGeometry, convexHullSimpleFillSymbol)
                {
                    // Set the Z index for the convex hull graphic so that it appears below the initial input user tapped map point graphics added earlier.
                    ZIndex = 0
                };

                // Add the convex hull graphic to the graphics overlay collection.
                _graphicsOverlay.Graphics.Add(convexHullGraphic);

                // Disable the button after has been used.
                _createHullButton.Enabled = false;
            }
            catch (Exception ex)
            {
                // Display an error message if there is a problem generating convex hull operation.
                UIAlertController alertController = UIAlertController.Create("Geometry Engine Failed!", ex.Message, UIAlertControllerStyle.Alert);
                alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alertController, true, null);
            }
        }
        public void RouteToAddress()
        {
            try
            {
                Logging.LogMethodCall(ClassName);
                if (SelectedAddress == null)
                {
                    return;
                }

                MapPoint pnt = null;
                if (SelectedAddress.Candidate.Location is Polygon)
                {
                    MapPoint startPoint = ((Polygon)SelectedAddress.Candidate.Location).Parts.FirstOrDefault().Points[0];
                    pnt = (MapPoint)GeometryEngine.Project((Geometry)startPoint, SpatialReferences.Wgs84);
                }
                else if (SelectedAddress.Candidate.Location is MapPoint)
                {
                    pnt = (MapPoint)GeometryEngine.Project((Geometry)SelectedAddress.Candidate.Location, SpatialReferences.Wgs84);
                }
                if (pnt != null)
                {
                    MainView.RouteTo(new Models.Point
                    {
                        Latitude  = pnt.Y,
                        Longitude = pnt.X
                    });
                }
                else
                {
                    MessageBox.Show("Unable to get a point from the selected location.");
                }
            }
            catch (Exception ex)
            {
                ErrorHelper.OnError(MethodBase.GetCurrentMethod().DeclaringType.Name, "Error routing to address", ex);
            }
        }
Example #19
0
        // Calculates a geometric difference between features and user defined geometry
        private async void DifferenceButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _differenceGraphics.Graphics.Clear();

                // wait for user to draw difference polygon
                Polygon userpoly = await MyMapView.Editor.RequestShapeAsync(DrawShape.Polygon) as Polygon;

                // Take account of WrapAround
                Polygon poly = GeometryEngine.NormalizeCentralMeridian(userpoly) as Polygon;

                // Adjust user polygon for backward digitization
                poly = GeometryEngine.Simplify(poly) as Polygon;

                // get intersecting features from the feature layer
                SpatialQueryFilter filter = new SpatialQueryFilter();
                filter.Geometry            = GeometryEngine.Project(poly, _statesLayer.FeatureTable.SpatialReference);
                filter.SpatialRelationship = SpatialRelationship.Intersects;
                filter.MaximumRows         = 52;
                var stateFeatures = await _statesLayer.FeatureTable.QueryAsync(filter);

                // Calc difference between feature geometries and user polygon and add results to graphics layer
                var states = stateFeatures.Select(feature => feature.Geometry);

                var diffGraphics = states
                                   .Select(state => ((bool)useSymmetricDifference.IsChecked)
                        ? GeometryEngine.SymmetricDifference(state, poly)
                        : GeometryEngine.Difference(state, poly))
                                   .Select(geo => new Graphic(geo, _fillSymbol));

                _differenceGraphics.Graphics.AddRange(diffGraphics);
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog("Difference Error: " + ex.Message, "Sample Error").ShowAsync();
            }
        }
        /// <summary>
        /// Create geodetic circle
        /// </summary>
        private Geometry CreateCircle(bool isFeedback)
        {
            if (Point1 == null || double.IsNaN(Distance) || Distance <= 0.0)
            {
                return(null);
            }

            var param = new GeometryEngine.GeodesicEllipseParameter();

            param.Center          = new Coordinate(Point1);
            param.AxisDirection   = 0.0;
            param.LinearUnit      = GetLinearUnit(LineDistanceType);
            param.OutGeometryType = GeometryType.Polygon;
            if (isFeedback)
            {
                param.OutGeometryType = GeometryType.Polyline;
            }
            param.SemiAxis1Length = Distance;
            param.SemiAxis2Length = Distance;
            param.VertexCount     = VertexCount;

            var geom = GeometryEngine.GeodesicEllipse(param, MapView.Active.Map.SpatialReference);

            CIMColor color = new CIMRGBColor()
            {
                R = 255, B = 0, G = 0, Alpha = 25
            };

            if (isFeedback)
            {
                color = ColorFactory.GreyRGB;
                ClearTempGraphics();
                AddGraphicToMap(Point1, ColorFactory.GreenRGB, true, 5.0);
            }
            AddGraphicToMap(geom, color, IsTempGraphic: isFeedback);

            return(geom as Geometry);
        }
        private async void ClipButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Remove the Colorado graphic from the input geometries graphics overlay collection. That way it will be easier
                // to see the clip versions of the GeometryEngine.Clip operation.
                _inputGeometriesGraphicsOverlay.Graphics.Remove(_coloradoGraphic);

                // Loop through each graphic in the input geometries for the clip operation.
                foreach (Graphic oneGraphic in _inputGeometriesGraphicsOverlay.Graphics)
                {
                    // Perform the clip operation. The first parameter of the clip operation will always be the Colorado graphic.
                    // The second parameter of the clip operation will be one of the 3 different clip geometries (_outsideGraphic,
                    // _containedGraphic, or _intersectingGraphic).
                    Geometry myGeometry = GeometryEngine.Clip(_coloradoGraphic.Geometry, (Envelope)oneGraphic.Geometry);

                    // Only work on returned geometries that are not null.
                    if (myGeometry != null)
                    {
                        // Create the graphic as a result of the clip operation using the same symbology that was defined for
                        // the _coloradoGraphic defined in the Initialize() method previously.
                        Graphic clippedGraphic = new Graphic(myGeometry, _coloradoGraphic.Symbol);

                        // Add the clipped graphic to the clip areas graphics overlay collection.
                        _clipAreasGraphicsOverlay.Graphics.Add(clippedGraphic);
                    }
                }

                // Disable the button after has been used.
                ClipButton.IsEnabled = false;
            }
            catch (System.Exception ex)
            {
                // Display an error message if there is a problem generating clip operation.
                MessageDialog theMessageDialog = new MessageDialog("Geometry Engine Failed: " + ex.Message);
                await theMessageDialog.ShowAsync();
            }
        }
Example #22
0
        private void MapView_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            if (_selectedStopGraphic != null)
            {
                // Get the position of the mouse relative to the map view.
                var hoverPoint = e.GetCurrentPoint(MyMapView);

                // Get the physical map location corresponding to the mouse position.
                MapPoint hoverLocation = MyMapView.ScreenToLocation(hoverPoint.Position);

                // Return if the location is outside the routable area.
                if (!GeometryEngine.Contains(_routableArea, hoverLocation))
                {
                    return;
                }

                // Update the location of the stop graphic.
                _selectedStopGraphic.Geometry = hoverLocation;

                // Update the route with the temporary stop.
                UpdateRoute((TravelMode)TravelModesCombo.SelectedItem ?? _availableTravelModes.First());
            }
        }
        /// <summary>Construct Nearest Coordinate sample control</summary>
        public NearestCoordinateInGeometry()
        {
            InitializeComponent();

            _vertexSymbol = new SimpleMarkerSymbol()
            {
                Color = Colors.LightGreen, Size = 8, Style = SimpleMarkerStyle.Circle
            };
            _userPointSymbol = new SimpleMarkerSymbol()
            {
                Color = Colors.Black, Size = 10, Style = SimpleMarkerStyle.Circle
            };

            _graphicsLayer   = mapView.Map.Layers["GraphicsLayer"] as GraphicsLayer;
            _targetLayer     = mapView.Map.Layers["TargetLayer"] as GraphicsLayer;
            _coordinateLayer = mapView.Map.Layers["CoordinateLayer"] as GraphicsLayer;

            mapView.Map.InitialExtent = (Envelope)GeometryEngine.Project(
                new Envelope(-83.3188395774275, 42.61428312652851, -83.31295664068958, 42.61670913269855, SpatialReferences.Wgs84),
                SpatialReferences.WebMercator);

            mapView.ExtentChanged += mapView_ExtentChanged;
        }
 private Graphic FindRelatedCountry(MapPoint location)
 {
     // TODO: Use a spatial index!
     foreach (var country in _countryOverlay.Graphics)
     {
         var      countryGeometry         = country.Geometry;
         var      countrySpatialReference = countryGeometry.SpatialReference;
         Geometry locationGeometry;
         if (location.SpatialReference.Wkid != countrySpatialReference.Wkid)
         {
             locationGeometry = GeometryEngine.Project(location, countrySpatialReference);
         }
         else
         {
             locationGeometry = location;
         }
         if (GeometryEngine.Intersects(countryGeometry, locationGeometry))
         {
             return(country);
         }
     }
     return(null);
 }
        protected override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            //Get the instance of the ViewModel
            var symbolDockPaneViewModel = FrameworkApplication.DockPaneManager.Find("ProSymbolEditor_MilitarySymbolDockpane") as MilitarySymbolDockpaneViewModel;

            //Get the map coordinates from the click point and set the property on the ViewModel.
            return(QueuedTask.Run(() =>
            {
                try
                {
                    // for now we will always project to WGS84
                    Geometry projectedGeometry = GeometryEngine.Project(geometry, SpatialReferences.WGS84);
                    symbolDockPaneViewModel.MapGeometry = projectedGeometry;
                    symbolDockPaneViewModel.CreateNewFeatureAsync(null);
                }
                catch
                {
                    //TODO: Add exception handler
                }

                return true;
            }));
        }
Example #26
0
        private void MyMapView_OnLayerLoaded(object sender, LayerLoadedEventArgs e)
        {
            // Zoom to water network
            var layer = e.Layer as ArcGISDynamicMapServiceLayer;

            if (layer != null)
            {
                var extent = layer.ServiceInfo.InitialExtent ?? layer.ServiceInfo.InitialExtent;
                if (extent != null)
                {
                    // If extent is not in the same spatial reference than map, reproject it
                    if (!SpatialReference.Equals(extent.SpatialReference, MyMapView.SpatialReference))
                    {
                        extent = GeometryEngine.Project(extent, MyMapView.SpatialReference) as Envelope;
                    }
                    if (extent != null)
                    {
                        extent = extent.Expand(0.5);
                        MyMapView.SetView(extent);
                    }
                }
            }
        }
Example #27
0
        private void MapView_Tapped(object sender, GeoViewInputEventArgs e)
        {
            // Get the tapped point - this is in the map's spatial reference,
            // which in this case is WebMercator because that is the SR used by the included basemaps.
            MapPoint tappedPoint = e.Location;

            // Update the graphics.
            MyMapView.GraphicsOverlays[0].Graphics.Clear();
            MyMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(tappedPoint));

            // Project the point to WGS84
            MapPoint projectedPoint = (MapPoint)GeometryEngine.Project(tappedPoint, SpatialReferences.Wgs84);

            // Format the results in strings.
            string originalCoords  = string.Format("Original: {0:F4}, {1:F4}", tappedPoint.X, tappedPoint.Y);
            string projectedCoords = string.Format("Projected: {0:F4}, {1:F4}", projectedPoint.X, projectedPoint.Y);
            string formattedString = string.Format("{0}\n{1}", originalCoords, projectedCoords);

            // Define a callout and show it in the map view.
            CalloutDefinition calloutDef = new CalloutDefinition("Coordinates:", formattedString);

            MyMapView.ShowCalloutAt(tappedPoint, calloutDef);
        }
        private void UpdateFeedbackWithGeoCircle()
        {
            if (Point1 == null || double.IsNaN(Distance) || Distance <= 0.0)
            {
                return;
            }

            var param = new GeometryEngine.GeodesicEllipseParameter();

            param.Center          = new Coordinate(Point1);
            param.AxisDirection   = 0.0;
            param.LinearUnit      = GetLinearUnit(LineDistanceType);
            param.OutGeometryType = GeometryType.Polyline;
            param.SemiAxis1Length = Distance;
            param.SemiAxis2Length = Distance;
            param.VertexCount     = VertexCount;

            var geom = GeometryEngine.GeodesicEllipse(param, MapView.Active.Map.SpatialReference);

            ClearTempGraphics();
            AddGraphicToMap(Point1, ColorFactory.GreenRGB, true, 5.0);
            AddGraphicToMap(geom, ColorFactory.GreyRGB, true);
        }
Example #29
0
 private void ZoomToData()
 {
     if (HasRoute)
     {
         //Zoom to the route with a bit of a buffer around it
         RequestViewpoint?.Invoke(this, new Viewpoint(GeometryEngine.Buffer(Overlays[0].Extent, Math.Max(Overlays[0].Extent.Width, Overlays[0].Extent.Height) * .25)));
     }
     else if (Overlays[1].Graphics[0].Geometry != null && Overlays[1].Graphics[1].Geometry != null)
     {
         //Zoom to the two geocoded locations
         RequestViewpoint?.Invoke(this, new Viewpoint(GeometryEngine.Buffer(Overlays[1].Extent, Math.Max(Overlays[1].Extent.Width, Overlays[1].Extent.Height) * .25)));
     }
     else if (Overlays[1].Graphics[0].Geometry != null)
     {
         //Zoom to from-location
         RequestViewpoint?.Invoke(this, new Viewpoint(Overlays[1].Graphics[0].Geometry as MapPoint, 400));
     }
     else if (Overlays[1].Graphics[1].Geometry != null)
     {
         //Zoom to to-location
         RequestViewpoint?.Invoke(this, new Viewpoint(Overlays[1].Graphics[1].Geometry as MapPoint, 400));
     }
 }
        // Calculates the geometric boundaries for each test graphic
        private void CalculateBoundaries()
        {
            var lineSymbol = (Symbol) new SimpleLineSymbol()
            {
                Color = Colors.Blue,
                Style = SimpleLineStyle.Solid,
                Width = 2
            };

            var pointSymbol = (Symbol) new SimpleMarkerSymbol()
            {
                Color = Colors.Blue,
                Style = SimpleMarkerStyle.Circle,
                Size  = 12
            };

            foreach (var testGraphic in _testGraphics.Graphics)
            {
                var boundary = GeometryEngine.Boundary(testGraphic.Geometry);
                var graphic  = new Graphic(boundary, (boundary.GeometryType == GeometryType.Polyline) ? lineSymbol : pointSymbol);
                _boundaryGraphics.Graphics.Add(graphic);
            }
        }