Ejemplo n.º 1
0
        private async Task QueryStateFeature(string stateName)
        {
            try
            {
                // Create a query parameters that will be used to Query the feature table
                QueryParameters queryParams = new QueryParameters();

                // Trim whitespace on the state name to prevent broken queries
                string formattedStateName = stateName.Trim().ToUpper();

                // Construct and assign the where clause that will be used to query the feature table
                queryParams.WhereClause = "upper(STATE_NAME) LIKE '%" + formattedStateName + "%'";

                // Query the feature table
                FeatureQueryResult queryResult = await _featureTable.QueryFeaturesAsync(queryParams);

                // Cast the QueryResult to a List so the results can be interrogated.
                List <Feature> features = queryResult.ToList();

                if (features.Any())
                {
                    // Create an envelope.
                    EnvelopeBuilder envBuilder = new EnvelopeBuilder(SpatialReferences.WebMercator);

                    // Loop over each feature from the query result.
                    foreach (Feature feature in features)
                    {
                        // Add the extent of each matching feature to the envelope.
                        envBuilder.UnionOf(feature.Geometry.Extent);

                        // Select each feature.
                        _featureLayer.SelectFeature(feature);
                    }

                    // Zoom to the extent of the selected feature(s).
                    await myMapView.SetViewpointGeometryAsync(envBuilder.ToGeometry(), 50);
                }
                else
                {
                    await((Page)Parent).DisplayAlert("State Not Found!", "Add a valid state name.", "OK");
                }
            }
            catch (Exception)
            {
                await((Page)Parent).DisplayAlert("Sample error", "An error occurred", "OK");
            }
        }
Ejemplo n.º 2
0
        private async void AsyncInitProcesses()
        {
            await _redlandsBoundary.LoadAsync();

            await _mapView.SetViewpointAsync(new Viewpoint(_redlandsBoundary.FullExtent.Extent));

            // await _water.LoadAsync();

            await _parks.LoadAsync();

            // Holds locations of hospitals around San Diego.

            _parkPolygons = new List <Polygon>();
            // Create query parameters to select all features.
            QueryParameters queryParams = new QueryParameters()
            {
                WhereClause = "1=1"
            };

            FeatureQueryResult redlandsResult = await _redlandsBoundary.FeatureTable.QueryFeaturesAsync(queryParams);

            List <Polygon> redlandsBound = redlandsResult.ToList().Select(feature => (Polygon)feature.Geometry).ToList();
            //GeometryEngine.Union()
            await _mapView.SetViewpointAsync(new Viewpoint(GeometryEngine.Union(redlandsBound).Extent));

            // Query all features in the facility table.
            FeatureQueryResult facilityResult = await _parks.FeatureTable.QueryFeaturesAsync(queryParams);

            // Add all of the query results to facilities as new Facility objects.
            _parkPolygons.AddRange(facilityResult.ToList().Select(feature => (Polygon)feature.Geometry));

            //await _mapView.SetViewpointAsync(new Viewpoint(_parkPolygons[0].Extent));

            FeatureQueryResult buildingsResult = await _buildings.FeatureTable.QueryFeaturesAsync(queryParams);

            _buildingGeometry = buildingsResult.ToList().Select(feature => (Polygon)feature.Geometry).ToList();

            /*
             * foreach(Polygon building in _buildingGeometry)
             * {
             *  Graphic bgraphic = new Graphic(building, new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Blue, new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.Gray, 3.0)));
             *  _barrierOverlay.Graphics.Add(bgraphic);
             * }
             */
        }
Ejemplo n.º 3
0
        private async Task QueryStateFeature(string stateName)
        {
            try
            {
                // Hide keyboard
                _queryTextView.ResignFirstResponder();

                // Create a query parameters that will be used to Query the feature table
                QueryParameters queryParams = new QueryParameters();

                // Trim whitespace on the state name to prevent broken queries
                String formattedStateName = stateName.Trim().ToUpper();

                // Construct and assign the where clause that will be used to query the feature table
                queryParams.WhereClause = "upper(STATE_NAME) LIKE '%" + formattedStateName + "%'";

                // Query the feature table
                FeatureQueryResult queryResult = await _featureTable.QueryFeaturesAsync(queryParams);

                // Cast the QueryResult to a List so the results can be interrogated
                var features = queryResult.ToList();

                if (features.Any())
                {
                    // Get the first feature returned in the Query result
                    Feature feature = features[0];

                    // Add the returned feature to the collection of currently selected features
                    _featureLayer.SelectFeature(feature);

                    // Zoom to the extent of the newly selected feature
                    await _myMapView.SetViewpointGeometryAsync(feature.Geometry.Extent);
                }
                else
                {
                    var alert = new UIAlertView("State Not Found!", "Add a valid state name.", null, "OK", null);
                    alert.Show();
                }
            }
            catch (Exception ex)
            {
                var alert = new UIAlertView("Sample error", ex.ToString(), null, "OK", null);
                alert.Show();
            }
        }
Ejemplo n.º 4
0
        private async void Initialize()
        {
            // Create a new Map with a vector streets basemap.
            Map myMap = new Map(Basemap.CreateStreetsVector());

            // Create the URI to the Service Requests map service.
            Uri serviceRequestUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/ServiceRequest/MapServer");

            // Create a new ArcGISMapImageLayer that uses the service URI.
            ArcGISMapImageLayer serviceRequestsMapImageLayer = new ArcGISMapImageLayer(serviceRequestUri);

            // Load all sublayers and tables contained by the map image layer.
            await serviceRequestsMapImageLayer.LoadTablesAndLayersAsync();

            // Set the initial map extent to the extent of all service request features.
            Envelope requestsExtent = serviceRequestsMapImageLayer.FullExtent;

            myMap.InitialViewpoint = new Viewpoint(requestsExtent);

            // Add the layer to the map.
            myMap.OperationalLayers.Add(serviceRequestsMapImageLayer);

            // Get the service request comments table from the map image layer.
            ServiceFeatureTable commentsTable = serviceRequestsMapImageLayer.Tables[0];

            // Create query parameters to get all non-null service request comment records (features) from the table.
            QueryParameters queryToGetNonNullComments = new QueryParameters
            {
                WhereClause = "requestid <> '' AND comments <> ''"
            };

            // Query the comments table to get the non-null records.
            FeatureQueryResult commentQueryResult = await commentsTable.QueryFeaturesAsync(queryToGetNonNullComments, QueryFeatureFields.LoadAll);

            // Show the records from the service request comments table in the list view control.
            CommentsListBox.ItemsSource = commentQueryResult.ToList();

            // Create a graphics overlay to show selected features and add it to the map view.
            _selectedFeaturesOverlay = new GraphicsOverlay();
            MyMapView.GraphicsOverlays.Add(_selectedFeaturesOverlay);

            // Assign the map to the MapView.
            MyMapView.Map = myMap;
        }
        private async Task QueryStateFeature(string stateName)
        {
            // Create dialog to display alert information
            var alert = new AlertDialog.Builder(this);

            try
            {
                // Create a query parameters that will be used to Query the feature table
                QueryParameters queryParams = new QueryParameters();

                // Construct and assign the where clause that will be used to query the feature table
                queryParams.WhereClause = "upper(STATE_NAME) LIKE '%" + (stateName.Trim().ToUpper()) + "%'";

                // Query the feature table
                FeatureQueryResult queryResult = await _featureTable.QueryFeaturesAsync(queryParams);

                // Cast the QueryResult to a List so the results can be interrogated
                var features = queryResult.ToList();

                if (features.Any())
                {
                    // Get the first feature returned in the Query result
                    Feature feature = features[0];

                    // Add the returned feature to the collection of currently selected features
                    _featureLayer.SelectFeature(feature);

                    // Zoom to the extent of the newly selected feature
                    await _myMapView.SetViewpointGeometryAsync(feature.Geometry.Extent);
                }
                else
                {
                    alert.SetTitle("State Not Found!");
                    alert.SetMessage("Add a valid state name.");
                    alert.Show();
                }
            }
            catch (Exception ex)
            {
                alert.SetTitle("Sample Error");
                alert.SetMessage(ex.Message);
                alert.Show();
            }
        }
Ejemplo n.º 6
0
        private async Task ShowTurtleData()
        {
            myMap.OperationalLayers.Add(_featureLayer);
            GreenSeaTurtleCheckbox.IsChecked     = true;
            LeatherbackCheckbox.IsChecked        = true;
            OliveRidleyCheckbox.IsChecked        = true;
            LoggerheadCheckbox.IsChecked         = true;
            UnidentifiedTurtleCheckBox.IsChecked = true;

            try
            {
                // Create a query parameters that will be used to Query the feature table.
                QueryParameters queryParams = new QueryParameters();

                // Construct and assign the where clause that will be used to query the feature table.
                queryParams.WhereClause = "1=1";

                // Query the feature table.
                FeatureQueryResult queryResult = await _featureTable.QueryFeaturesAsync(queryParams);

                // Cast the QueryResult to a List so the results can be interrogated.
                List <Feature> features = queryResult.ToList();

                if (features.Any())
                {
                    // Loop over each feature from the query result.
                    foreach (Feature feature in features)
                    {
                        var attributevalue     = feature.GetAttributeValue("Species").ToString();
                        var attributeDatevalue = feature.GetAttributeValue("Date").ToString();
                        // Select each feature.
                        _featureLayer.SetFeatureVisible(feature, true);
                    }
                }
                else
                {
                    MessageBox.Show("No Features to Select");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred.\n" + ex, "Sample error");
            }
        }
        private async void MapView_Tapped(object sender, Esri.ArcGISRuntime.Xamarin.Forms.GeoViewInputEventArgs e)
        {
            // Clear any existing selection.
            _damageLayer.ClearSelection();

            // Reconfigure the button.
            DeleteButton.IsEnabled = false;
            DeleteButton.Text      = "Delete feature";

            try
            {
                // Perform an identify to determine if a user tapped on a feature.
                IdentifyLayerResult identifyResult = await MyMapView.IdentifyLayerAsync(_damageLayer, e.Position, 5, false);

                // Do nothing if there are no results.
                if (!identifyResult.GeoElements.Any())
                {
                    return;
                }

                // Otherwise, get the ID of the first result.
                long featureId = (long)identifyResult.GeoElements.First().Attributes["objectid"];

                // Get the feature by constructing a query and running it.
                QueryParameters qp = new QueryParameters();
                qp.ObjectIds.Add(featureId);
                FeatureQueryResult queryResult = await _damageLayer.FeatureTable.QueryFeaturesAsync(qp);

                _tappedFeature = queryResult.First();

                // Select the feature.
                _damageLayer.SelectFeature(_tappedFeature);

                // Update the button to allow deleting the feature.
                ConfigureDeletionButton(_tappedFeature);
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
            }
        }
        private async void MapView_Tapped(object sender, GeoViewInputEventArgs e)
        {
            // Clear any existing selection.
            _damageLayer.ClearSelection();

            // Dismiss any existing callouts.
            _myMapView.DismissCallout();

            try
            {
                // Perform an identify to determine if a user tapped on a feature.
                IdentifyLayerResult identifyResult = await _myMapView.IdentifyLayerAsync(_damageLayer, e.Position, 8, false);

                // Do nothing if there are no results.
                if (!identifyResult.GeoElements.Any())
                {
                    return;
                }

                // Otherwise, get the ID of the first result.
                long featureId = (long)identifyResult.GeoElements.First().Attributes["objectid"];

                // Get the feature by constructing a query and running it.
                QueryParameters qp = new QueryParameters();
                qp.ObjectIds.Add(featureId);
                FeatureQueryResult queryResult = await _damageLayer.FeatureTable.QueryFeaturesAsync(qp);

                Feature tappedFeature = queryResult.First();

                // Select the feature.
                _damageLayer.SelectFeature(tappedFeature);

                // Show the callout.
                ShowDeletionCallout(tappedFeature);
            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString(), "There was a problem.");
            }
        }
        private async Task QueryStateFeature(string stateName)
        {
            try
            {
                // Create a query parameters that will be used to Query the feature table
                QueryParameters queryParams = new QueryParameters();

                // Construct and assign the where clause that will be used to query the feature table
                queryParams.WhereClause = "upper(STATE_NAME) LIKE '%" + (stateName.ToUpper()) + "%'";

                // Query the feature table
                FeatureQueryResult queryResult = await _featureTable.QueryFeaturesAsync(queryParams);

                // Cast the QueryResult to a List so the results can be interrogated
                var features = queryResult.ToList();

                if (features.Any())
                {
                    // Get the first feature returned in the Query result
                    Feature feature = features[0];

                    // Add the returned feature to the collection of currently selected features
                    _featureLayer.SelectFeature(feature);

                    // Zoom to the extent of the newly selected feature
                    await myMapView.SetViewpointGeometryAsync(feature.Geometry.Extent);
                }
                else
                {
                    var message = new MessageDialog("State Not Found!", "Add a valid state name.");
                    await message.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                var message = new MessageDialog("Sample error: " + ex.ToString(), "An error occurred");
                await message.ShowAsync();
            }
        }
Ejemplo n.º 10
0
        private async Task <List <TrackInfo> > GetPlaylistArtists(Paging <PlaylistTrack> playlistTracks, FeatureTable artistPlaces)
        {
            List <TrackInfo> artists = new List <TrackInfo>();

            foreach (PlaylistTrack plt in playlistTracks.Items)
            {
                SimpleArtist artist = plt.Track.Artists.FirstOrDefault();

                string artistid  = artist.Id;
                string trackid   = plt.Track.Id;
                string trackname = plt.Track.Name;

                QueryParameters query = new QueryParameters
                {
                    WhereClause = "artistid = '" + artistid + "'"
                };

                FeatureQueryResult queryResult = await artistPlaces.QueryFeaturesAsync(query);

                foreach (Feature f in queryResult)
                {
                    await(f as ArcGISFeature).LoadAsync();
                    string      artistname = f.Attributes["artistname"].ToString();
                    string      hometown   = f.Attributes["placename"].ToString();
                    string      bio        = f.Attributes["bioshort"].ToString();
                    bool        isOnTour   = int.Parse(f.Attributes["isontour"].ToString()) == 1;
                    string      imgUrl     = f.Attributes["imageurl"].ToString();
                    BitmapImage src        = new BitmapImage(new Uri(imgUrl, UriKind.Absolute));

                    TrackInfo thisArtist = new TrackInfo(artistname, artistid, bio, src, hometown, trackname, trackid, f.Geometry as MapPoint, isOnTour);

                    // Add the track info to the list
                    artists.Add(thisArtist);
                }
            }

            return(artists);
        }
Ejemplo n.º 11
0
        // 点选
        private async void myMapViewGetAttributeValue(object sender, Esri.ArcGISRuntime.UI.Controls.GeoViewInputEventArgs e)
        {
            StackPanel stackPanel = (StackPanel)w.FindName("cykGeometryCalcuEdit");

            if (layersComboBox.SelectedIndex >= 0 && stackPanel.Visibility == Visibility.Visible)
            {
                myShapeFileResult = await myMapView.IdentifyLayerAsync(featureLayer, e.Position, 15, false);

                //if(myShapeFileResult != null)  MessageBox.Show("" + 12 + " " + myShapeFileResult);

                // 要素选择高亮
                try
                {
                    string          numberFID   = ((Feature)(myShapeFileResult.GeoElements[0])).GetAttributeValue("FID") + "";
                    QueryParameters queryParams = new QueryParameters
                    {
                        //WhereClause = "upper(FID) = " + numberFID
                        Geometry = e.Location
                    };
                    FeatureQueryResult queryResult = await featureLayer.SelectFeaturesAsync(queryParams, Esri.ArcGISRuntime.Mapping.SelectionMode.New);

                    IEnumerator <Feature> resultFeatures = queryResult.GetEnumerator();
                    List <Feature>        features       = new List <Feature>();
                    while (resultFeatures.MoveNext())
                    {
                        features.Add(resultFeatures.Current);
                    }

                    // 每一次"选择"都需要点击一次"选择"按钮
                    myMapView.GeoViewTapped -= myMapViewGetAttributeValue;
                    //t1.Text = numberFID + " ID;" + features.Count + "个;  " + e.Location.X + ", " + e.Location.Y + "  //  投影" + myMapView.Map.SpatialReference + "," + myMapView.UnitsPerPixel;
                }
                catch (Exception ex)
                {
                }
                //t1.Text += featureLayer.Description + table.DisplayName + "...";
            }
        }
Ejemplo n.º 12
0
        private async void GetFeaturesFromQuery()
        {
            try
            {
                // Create a service feature table to get features from.
                ServiceFeatureTable featTable = new ServiceFeatureTable(new Uri(FeatureLayerUrl));

                // Create a query to get all features in the table.
                QueryParameters queryParams = new QueryParameters
                {
                    WhereClause = "1=1"
                };

                // Query the table to get all features.
                FeatureQueryResult featureResult = await featTable.QueryFeaturesAsync(queryParams);

                // Create a new feature collection table from the result features.
                FeatureCollectionTable collectTable = new FeatureCollectionTable(featureResult);

                // Create a feature collection and add the table.
                FeatureCollection featCollection = new FeatureCollection();
                featCollection.Tables.Add(collectTable);

                // Create a layer to display the feature collection, add it to the map's operational layers.
                FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featCollection);
                _myMapView.Map.OperationalLayers.Add(featureCollectionLayer);

                // Zoom to the extent of the feature collection layer.
                await featureCollectionLayer.LoadAsync();

                await _myMapView.SetViewpointGeometryAsync(featureCollectionLayer.FullExtent, 50);
            }
            catch (Exception e)
            {
                new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
Ejemplo n.º 13
0
        private async Task ShowWindData()
        {
            myMap.OperationalLayers.Add(_windFeatureLayer);
            try
            {
                // Create a query parameters that will be used to Query the feature table.
                QueryParameters queryParams = new QueryParameters();

                // Construct and assign the where clause that will be used to query the feature table.
                queryParams.WhereClause = "1=1";

                // Query the feature table.
                FeatureQueryResult queryResult = await _windFeatureTable.QueryFeaturesAsync(queryParams);

                // Cast the QueryResult to a List so the results can be interrogated.
                List <Feature> features = queryResult.ToList();

                if (features.Any())
                {
                    // Loop over each feature from the query result.
                    foreach (Feature feature in features)
                    {
                        // Select each feature.
                        _windFeatureLayer.SetFeatureVisible(feature, true);
                        _windFeatureLayer.MinScale = 100000000;
                    }
                }
                else
                {
                    MessageBox.Show("No Features to Select");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred.\n" + ex, "Sample error");
            }
        }
Ejemplo n.º 14
0
        private async void unionBtn_Click(object sender, RoutedEventArgs e)
        {
            FeatureQueryResult r = await layer.GetSelectedFeaturesAsync();

            IEnumerator <Feature> resultFeatures = r.GetEnumerator();
            List <Feature>        features       = new List <Feature>();

            while (resultFeatures.MoveNext())
            {
                features.Add(resultFeatures.Current);
            }


            for (int i = 0; i < features.Count - 1; i++)
            {
                resultGeometry = GeometryEngine.Union(features[i].Geometry, features[i + 1].Geometry.Extent);
            }
            try
            {
                if (featureStyle == 1)
                {
                    graphic = new Graphic(resultGeometry, simplePointSymbol);
                }
                else if (featureStyle == 2)
                {
                    graphic = new Graphic(resultGeometry, simpleLineSymbol);
                }
                else if (featureStyle == 3)
                {
                    graphic = new Graphic(resultGeometry, simpleFillSymbol);
                }
                MainWindow.graphicsOverlay.Graphics.Add(graphic);
            }
            catch
            {
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Temporary method.  Just displays attributes and values from a single record in the passed table.
        /// </summary>
        /// <param name="testLayer">from which to get the single record</param>
        /// <returns>marker indicating the task is complete</returns>
        public async Task <bool> ShowSingleRecordAsync(TesterLayer testLayer)
        {
            if (testLayer.LayerLoadException != null)
            {
                this.LogLayerLoadException(testLayer);
            }
            else if (testLayer.FeatureTable != null)
            {
                FeatureTable    aTable      = testLayer.FeatureTable;
                QueryParameters queryParams = new QueryParameters();
                queryParams.MaxFeatures    = 1;
                queryParams.ReturnGeometry = true;
                queryParams.WhereClause    = "1=1";
                FeatureQueryResult fqr = await aTable.QueryFeaturesAsync(queryParams);

                IEnumerator <Feature> features = fqr.GetEnumerator();
                this.LoggingText = "=============";
                this.LoggingText = "TABLE: " + aTable.TableName;
                Feature aFeature = null;

                while (features.MoveNext())
                {
                    aFeature         = features.Current;
                    this.LoggingText = "\tShape = " + aFeature.Geometry;

                    foreach (string attName in aFeature.Attributes.Keys)
                    {
                        this.LoggingText = "\t" + attName + " = " + aFeature.Attributes[attName];
                    }
                }

                this.LoggingText = "=============";
            }

            return(true);
        }
        private async void Initialize()
        {
            // Create a new Map with a vector streets basemap.
            Map myMap = new Map(Basemap.CreateStreetsVector());

            // Create the URI to the Service Requests map service.
            Uri serviceRequestUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/ServiceRequest/MapServer");

            // Create a new ArcGISMapImageLayer that uses the service URI.
            ArcGISMapImageLayer serviceRequestsMapImageLayer = new ArcGISMapImageLayer(serviceRequestUri);

            try
            {
                // Load all sublayers and tables contained by the map image layer.
                await serviceRequestsMapImageLayer.LoadTablesAndLayersAsync();

                // Set the initial map extent to the extent of all service request features.
                Envelope requestsExtent = serviceRequestsMapImageLayer.FullExtent;
                myMap.InitialViewpoint = new Viewpoint(requestsExtent);

                // Add the layer to the map.
                myMap.OperationalLayers.Add(serviceRequestsMapImageLayer);

                // Get the service request comments table from the map image layer.
                ServiceFeatureTable commentsTable = serviceRequestsMapImageLayer.Tables[0];

                // Create query parameters to get all non-null service request comment records (features) from the table.
                QueryParameters queryToGetNonNullComments = new QueryParameters
                {
                    WhereClause = "requestid <> '' AND comments <> ''"
                };

                // Query the comments table to get the non-null records.
                FeatureQueryResult commentQueryResult = await commentsTable.QueryFeaturesAsync(queryToGetNonNullComments, QueryFeatureFields.LoadAll);

                // Show the records from the service request comments table in the UITableView control.
                foreach (ArcGISFeature commentFeature in commentQueryResult)
                {
                    _serviceRequestComments.Add(commentFeature);
                }

                // Create the table view source that uses the list of features.
                _commentsTableSource = new ServiceRequestCommentsTableSource(_serviceRequestComments);

                // Assign the table view source to the table view control.
                _tableView.Source = _commentsTableSource;

                // Subscribe to event.
                _commentsTableSource.ServiceRequestCommentSelected += CommentsTableSource_ServiceRequestCommentSelected;

                // Create a graphics overlay to show selected features and add it to the map view.
                _selectedFeaturesOverlay = new GraphicsOverlay();
                _myMapView.GraphicsOverlays.Add(_selectedFeaturesOverlay);

                // Assign the map to the MapView.
                _myMapView.Map = myMap;

                // Reload the table view data to refresh the display.
                _tableView.ReloadData();
            }
            catch (Exception e)
            {
                new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
Ejemplo n.º 17
0
        private async void MainWindow_Click(object sender, Esri.ArcGISRuntime.UI.Controls.GeoViewInputEventArgs e)
        {
            if (count == 0)
            {
                count      = 1;
                _downPoint = e.Location;
                //_downPointP = e.Position;
                //dragSelectRectangle.Margin = new Thickness(0, 0, 0, 0);
                //dragSelectRectangle.Width = 0;
                //dragSelectRectangle.Height = 0;
            }
            else
            {
                count = 0;
                var _endpoint = e.Location;

                try
                {
                    double   tolerance    = 0.0001;
                    double   mapTolerance = tolerance /** myMapView.UnitsPerPixel*/;
                    MapPoint geometry     = new MapPoint((_downPoint.X + _endpoint.X) / 2, (_downPoint.Y + _endpoint.Y) / 2, myMapView.SpatialReference);
                    if (myMapView.IsWrapAroundEnabled)
                    {
                        geometry = (MapPoint)GeometryEngine.NormalizeCentralMeridian(geometry);
                    }
                    Envelope        selectionEnvelope = new Envelope(geometry, Math.Abs(_downPoint.X - _endpoint.X), Math.Abs(_downPoint.Y - _endpoint.Y) /*geometry.X - mapTolerance, geometry.Y - mapTolerance, geometry.X + mapTolerance, geometry.Y + mapTolerance,*/ /*myMapView.Map.SpatialReference*/);
                    QueryParameters queryParams       = new QueryParameters()
                    {
                        Geometry = selectionEnvelope
                    };

                    FeatureLayer       tempLayer = (FeatureLayer)(myMapView.Map.OperationalLayers[0]);
                    FeatureQueryResult fr        = await tempLayer.SelectFeaturesAsync(queryParams, Esri.ArcGISRuntime.Mapping.SelectionMode.New);

                    IEnumerator <Feature> frr      = fr.GetEnumerator();
                    List <Feature>        features = new List <Feature>();
                    while (frr.MoveNext())
                    {
                        features.Add(frr.Current);
                    }

                    // 查看属性
                    Esri.ArcGISRuntime.Data.FeatureTable tempTable = (Esri.ArcGISRuntime.Data.FeatureTable)tempLayer.FeatureTable;
                    long          row        = tempTable.NumberOfFeatures;
                    int           col        = tempTable.Fields.Count;
                    List <String> fieldNames = new List <string>();
                    for (int i = 0; i < col; i++)
                    {
                        fieldNames.Add(tempTable.Fields[i] + "");
                    }

                    StackPanel  stackPanel = new StackPanel();
                    WrapPanel[] wrapPanels = new WrapPanel[row];

                    // 字段名
                    WrapPanel wrapPanelField = new WrapPanel()
                    {
                        Margin = new Thickness()
                        {
                            Left   = 10,
                            Top    = 1,
                            Right  = 10,
                            Bottom = 1
                        }
                    };
                    for (int i = 0; i < col; i++)
                    {
                        Button button = new Button()
                        {
                            Content    = fieldNames[i],
                            ToolTip    = fieldNames[i],
                            Width      = 60,
                            Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 100, 183, 134))
                        };
                        wrapPanelField.Children.Add(button);
                    }
                    stackPanel.Children.Add(wrapPanelField);

                    // 记录
                    for (int i = 0; i < row; i++)
                    {
                        wrapPanels[i] = new WrapPanel()
                        {
                            Margin = new Thickness()
                            {
                                Left   = 10,
                                Top    = 1,
                                Right  = 10,
                                Bottom = 1
                            }
                        };
                        for (int j = 0; j < col; j++)
                        {
                            Button button = new Button()
                            {
                                Width   = 60,
                                Content = features[i].GetAttributeValue(fieldNames[j]),
                                ToolTip = features[i].GetAttributeValue(fieldNames[j])
                            };
                            wrapPanels[i].Children.Add(button);
                        }
                        stackPanel.Children.Add(wrapPanels[i]);
                    }

                    ScrollViewer scrollViewer = new ScrollViewer();
                    scrollViewer.VerticalScrollBarVisibility   = ScrollBarVisibility.Visible;
                    scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
                    scrollViewer.Content = stackPanel;

                    var window = new Window();
                    window.Content               = scrollViewer;
                    window.SizeToContent         = SizeToContent.WidthAndHeight;
                    window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    window.MaxHeight             = 700;
                    window.MaxWidth              = 1000;

                    window.Title = "要素多选属性表";
                    window.Show();
                }
                catch
                {
                    t1.Text = "要素多选发生错误";
                }
            }
        }
        private async void submitQuery(UIAlertAction obj)
        {
            // If the population value entered is not numeric, warn the user and exit.
            double populationNumber;

            if (!double.TryParse(_queryEntry.Text.Trim(), out populationNumber))
            {
                UIAlertController alert = UIAlertController.Create("Invalid number", "Population value must be numeric.", UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);

                return;
            }

            // Get the USA map image layer (the first and only operational layer in the map).
            ArcGISMapImageLayer usaMapImageLayer = (ArcGISMapImageLayer)_myMapView.Map.OperationalLayers[0];

            try
            {
                // Use a utility method on the map image layer to load all the sublayers and tables.
                await usaMapImageLayer.LoadTablesAndLayersAsync();

                // Get the sublayers of interest (skip 'Highways' since it doesn't have the POP2000 field).
                ArcGISMapImageSublayer citiesSublayer   = (ArcGISMapImageSublayer)usaMapImageLayer.Sublayers[0];
                ArcGISMapImageSublayer statesSublayer   = (ArcGISMapImageSublayer)usaMapImageLayer.Sublayers[2];
                ArcGISMapImageSublayer countiesSublayer = (ArcGISMapImageSublayer)usaMapImageLayer.Sublayers[3];

                // Get the service feature table for each of the sublayers.
                ServiceFeatureTable citiesTable   = citiesSublayer.Table;
                ServiceFeatureTable statesTable   = statesSublayer.Table;
                ServiceFeatureTable countiesTable = countiesSublayer.Table;

                // Create the query parameters that will find features in the current extent with a population greater than the value entered.
                QueryParameters populationQuery = new QueryParameters
                {
                    WhereClause = "POP2000 > " + populationNumber,
                    Geometry    = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry
                };

                // Query each of the sublayers with the query parameters.
                FeatureQueryResult citiesQueryResult = await citiesTable.QueryFeaturesAsync(populationQuery);

                FeatureQueryResult statesQueryResult = await statesTable.QueryFeaturesAsync(populationQuery);

                FeatureQueryResult countiesQueryResult = await countiesTable.QueryFeaturesAsync(populationQuery);

                // Display the selected cities in the graphics overlay.
                SimpleMarkerSymbol citySymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Red, 16);
                foreach (Feature city in citiesQueryResult)
                {
                    Graphic cityGraphic = new Graphic(city.Geometry, citySymbol);

                    _selectedFeaturesOverlay.Graphics.Add(cityGraphic);
                }

                // Display the selected counties in the graphics overlay.
                SimpleLineSymbol countyLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.Cyan, 2);
                SimpleFillSymbol countySymbol     = new SimpleFillSymbol(SimpleFillSymbolStyle.DiagonalCross, Color.Cyan, countyLineSymbol);
                foreach (Feature county in countiesQueryResult)
                {
                    Graphic countyGraphic = new Graphic(county.Geometry, countySymbol);

                    _selectedFeaturesOverlay.Graphics.Add(countyGraphic);
                }

                // Display the selected states in the graphics overlay.
                SimpleLineSymbol stateLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.DarkCyan, 6);
                SimpleFillSymbol stateSymbol     = new SimpleFillSymbol(SimpleFillSymbolStyle.Null, Color.Cyan, stateLineSymbol);
                foreach (Feature state in statesQueryResult)
                {
                    Graphic stateGraphic = new Graphic(state.Geometry, stateSymbol);

                    _selectedFeaturesOverlay.Graphics.Add(stateGraphic);
                }
            }
            catch (Exception e)
            {
                new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
Ejemplo n.º 19
0
        // 레이에서 해당 Feature 찾기
        private async Task QueryStateFeature(string _FTR_CDE, string _FTR_IDN, FeatureLayer _featureLayer)
        {
            try
            {
                // 0.Feature 테이블 가져오기
                //FeatureLayer __featureLayer = _featureLayer.Clone() as FeatureLayer;
                FeatureTable _featureTable = _featureLayer.FeatureTable;



                // Create a query parameters that will be used to Query the feature table.
                QueryParameters queryParams = new QueryParameters();


                // Construct and assign the where clause that will be used to query the feature table.
                queryParams.WhereClause = " FTR_CDE = '" + _FTR_CDE + "' ";
                if (!FmsUtil.IsNull(_FTR_IDN))
                {
                    queryParams.WhereClause += " AND FTR_IDN = " + _FTR_IDN;
                }


                List <Feature> features;
                try
                {
                    // Query the feature table.
                    FeatureQueryResult queryResult = await _featureTable.QueryFeaturesAsync(queryParams);

                    // Cast the QueryResult to a List so the results can be interrogated.
                    features = queryResult.ToList();
                }
                catch (Exception)
                {
                    Messages.ShowErrMsgBox("보호된 메모리 접근 에러..");
                    return;
                }

                if (features.Any())
                {
                    // Create an envelope.
                    EnvelopeBuilder envBuilder = new EnvelopeBuilder(SpatialReferences.WebMercator);



                    // Loop over each feature from the query result.
                    foreach (Feature feature in features)
                    {
                        // Add the extent of each matching feature to the envelope.
                        //envBuilder.UnionOf(feature.Geometry.Extent); //복수의 피처영역 합치기

                        // Select each feature.
                        _featureLayer.SelectFeature(feature);
                        //해당피처로 이동
                        await mapView.SetViewpointCenterAsync(feature.Geometry.Extent.GetCenter(), 40000);
                    }

                    // Zoom to the extent of the selected feature(s).
                    //await mapView.SetViewpointGeometryAsync(envBuilder.ToGeometry(), 50);
                }
                else
                {
                    MessageBox.Show("해당 시설물 위치를 찾을 수 없습니다.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred.\n" + ex, "Sample error");
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Creates a frequency analysis file for the specified table.
        /// </summary>
        /// <param name="outputFile">the file to which to write the analysis</param>
        /// <param name="table">the table to analyse</param>
        /// <returns>did things go well?</returns>
        public async Task <bool> RunFrequencyAnalysis(string outputFile, GeodatabaseFeatureTable table)
        {
            bool allGood   = true;
            long totalRecs = table.NumberOfFeatures;
            Dictionary <string, Dictionary <string, uint> > freqs = new Dictionary <string, Dictionary <string, uint> >();
            string whereClause           = "1=1";
            string orderingName          = null;
            long   lastOID               = 0;
            int    lastBatchCount        = -1;
            long   totalRecordsProcessed = 0;
            int    recordsPerBatch       = 10000;

            foreach (Field aField in table.Fields)
            {
                if (aField.FieldType == FieldType.OID)
                {
                    orderingName = aField.Name;
                    whereClause  = aField.Name + " > " + lastOID + " order by " + aField.Name;
                    break;
                }
            }

            try
            {
                while (lastBatchCount != 0)
                {
                    QueryParameters queryParams = new QueryParameters();
                    queryParams.ReturnGeometry = true;
                    lastBatchCount             = 0;

                    if (orderingName == null)
                    {
                        queryParams.WhereClause = "1=1";
                    }
                    else
                    {
                        queryParams.WhereClause = orderingName + " > " + lastOID + " order by " + orderingName;
                    }

                    FeatureQueryResult result = await table.QueryFeaturesAsync(queryParams);

                    IEnumerator <Feature> features = result.GetEnumerator();
                    object attValue       = null;
                    string attStringValue = null;

                    //
                    // Collect the frequencies.
                    //
                    while (features.MoveNext())
                    {
                        Feature aFeature = features.Current;
                        totalRecordsProcessed++;
                        lastBatchCount++;

                        foreach (string attName in aFeature.Attributes.Keys)
                        {
                            attValue = aFeature.Attributes[attName];

                            if (attValue == null)
                            {
                                attStringValue = "";
                            }
                            else
                            {
                                attStringValue = attValue.ToString();
                            }

                            this.StoreFrequency(attName, attStringValue, freqs);

                            if (orderingName.Equals(attName))
                            {
                                lastOID = (long)attValue;
                            }
                        }

                        if (totalRecordsProcessed % 2500 == 0)
                        {
                            Trace.WriteLine("Processed " + totalRecordsProcessed + " out of " + table.NumberOfFeatures);
                        }

                        if (lastBatchCount == recordsPerBatch)
                        {
                            features.Dispose();
                            break;
                        }
                    }
                }

                //
                // Write out the frequencies.
                //
                using (StreamWriter writer = new StreamWriter(outputFile))
                {
                    foreach (string attributeName in freqs.Keys)
                    {
                        Dictionary <string, uint> attributeFreqs = freqs[attributeName];

                        if (attributeFreqs.Count > 200)
                        {
                            writer.Write("\"");
                            writer.Write(attributeName);
                            writer.Write("\"");
                            writer.Write(",");
                            writer.Write("\"");
                            writer.Write("<MANY VALUES>");
                            writer.Write("\"");
                            writer.Write(",");
                            writer.Write(table.NumberOfFeatures);
                            writer.Write("\n");
                        }
                        else
                        {
                            foreach (string attributeValue in attributeFreqs.Keys)
                            {
                                uint numVals = attributeFreqs[attributeValue];
                                writer.Write("\"");
                                writer.Write(attributeName);
                                writer.Write("\"");
                                writer.Write(",");
                                writer.Write("\"");
                                writer.Write(attributeValue);
                                writer.Write("\"");
                                writer.Write(",");
                                writer.Write(numVals);
                                writer.Write("\n");
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                allGood = false;
                string excString = "=====================\n";
                excString        = excString + e.Message + "\n";
                excString        = excString + e.StackTrace + "\n";
                this.LoggingText = excString;
            }

            return(allGood);
        }
        private async void GeoViewTapped(object sender, GeoViewInputEventArgs e)
        {
            // Disregard if not ready for edits
            if (_readyForEdits == EditState.NotReady)
            {
                return;
            }

            // If an edit is in process, finish it
            if (_readyForEdits == EditState.Editing)
            {
                // Hold a list of any selected features
                List <Feature> selectedFeatures = new List <Feature>();

                // Get all selected features then clear selection
                foreach (FeatureLayer layer in myMapView.Map.OperationalLayers)
                {
                    // Get the selected features
                    FeatureQueryResult layerFeatures = await layer.GetSelectedFeaturesAsync();

                    // FeatureQueryResult implements IEnumerable, so it can be treated as a collection of features
                    selectedFeatures.AddRange(layerFeatures);

                    // Clear the selection
                    layer.ClearSelection();
                }

                // Update all selected features' geometry
                foreach (Feature feature in selectedFeatures)
                {
                    // Get a reference to the correct feature table for the feature
                    GeodatabaseFeatureTable table = feature.FeatureTable as GeodatabaseFeatureTable;

                    // Ensure the geometry type of the table is point
                    if (table.GeometryType != GeometryType.Point)
                    {
                        continue;
                    }

                    // Set the new geometry
                    feature.Geometry = e.Location;

                    // Update the feature in the table
                    await table.UpdateFeatureAsync(feature);
                }

                // Update the edit state
                _readyForEdits = EditState.Ready;

                // Enable the sync button
                mySyncButton.Enabled = true;
            }
            // Otherwise, start an edit
            else
            {
                // Define a tolerance for use with identifying the feature
                double tolerance = 15 * myMapView.UnitsPerPixel;

                // Define the selection envelope
                Envelope selectionEnvelope = new Envelope(e.Location.X - tolerance, e.Location.Y - tolerance, e.Location.X + tolerance, e.Location.Y + tolerance);

                // Define query parameters for feature selection
                QueryParameters query = new QueryParameters()
                {
                    Geometry = selectionEnvelope
                };

                // Select the feature in all applicable tables
                foreach (FeatureLayer layer in myMapView.Map.OperationalLayers)
                {
                    await layer.SelectFeaturesAsync(query, SelectionMode.New);
                }

                // Set the edit state
                _readyForEdits = EditState.Editing;
            }
        }
        private async void sureBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FeatureLayer tempLayer = (FeatureLayer)myMapView.Map.OperationalLayers[index];
                Esri.ArcGISRuntime.Data.FeatureTable tempTable = tempLayer.FeatureTable;

                // 语句
                QueryParameters query = new QueryParameters();
                query.WhereClause = string.Format(inTxt.Text);

                FeatureQueryResult queryResult = await tempTable.QueryFeaturesAsync(query);

                IEnumerator <Feature> resultFeatures = queryResult.GetEnumerator();
                List <Feature>        features       = new List <Feature>();
                while (resultFeatures.MoveNext())
                {
                    features.Add(resultFeatures.Current);
                }

                MessageBox.Show(inTxt.Text + "\n" + features.Count + "\n" + query.WhereClause);

                //long row = tempTable.NumberOfFeatures;
                long          row        = features.Count;
                int           col        = tempTable.Fields.Count;
                List <String> fieldNames = new List <string>();
                for (int i = 0; i < col; i++)
                {
                    fieldNames.Add(tempTable.Fields[i] + "");
                }

                StackPanel  stackPanel = new StackPanel();
                WrapPanel[] wrapPanels = new WrapPanel[row];

                // 字段名
                WrapPanel wrapPanelField = new WrapPanel()
                {
                    Margin = new Thickness()
                    {
                        Left   = 10,
                        Top    = 1,
                        Right  = 10,
                        Bottom = 1
                    }
                };
                for (int i = 0; i < col; i++)
                {
                    Button button = new Button()
                    {
                        Content    = fieldNames[i],
                        ToolTip    = fieldNames[i],
                        Width      = 60,
                        Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 100, 183, 134))
                    };
                    wrapPanelField.Children.Add(button);
                }
                stackPanel.Children.Add(wrapPanelField);

                // 记录
                for (int i = 0; i < row; i++)
                {
                    wrapPanels[i] = new WrapPanel()
                    {
                        Margin = new Thickness()
                        {
                            Left   = 10,
                            Top    = 1,
                            Right  = 10,
                            Bottom = 1
                        }
                    };
                    for (int j = 0; j < col; j++)
                    {
                        Button button = new Button()
                        {
                            Width   = 60,
                            Content = features[i].GetAttributeValue(fieldNames[j]),
                            ToolTip = features[i].GetAttributeValue(fieldNames[j])
                        };
                        wrapPanels[i].Children.Add(button);
                    }
                    stackPanel.Children.Add(wrapPanels[i]);
                }

                var window = new Window();
                window.Content               = stackPanel;
                window.SizeToContent         = SizeToContent.WidthAndHeight;
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.Title = "属性查询结果";
                window.Show();
            }
            catch (Exception ex2)
            {
                MessageBox.Show("查询错误!\n" + ex2.Message + "\n");
            }
        }
Ejemplo n.º 23
0
        // 打开属性表
        private async void OpenFeatureTableWindow_Layers_CheckBox(object sender, RoutedEventArgs e)
        {
            MenuItem     menuItem  = sender as MenuItem;
            ContextMenu  cm        = menuItem.Parent as ContextMenu;
            int          index     = int.Parse(cm.Name.Substring(16));
            FeatureLayer tempLayer = (FeatureLayer)myMapView.Map.OperationalLayers[index];

            Esri.ArcGISRuntime.Data.FeatureTable tempTable = tempLayer.FeatureTable;

            QueryParameters query = new QueryParameters();

            query.WhereClause = string.Format("upper(FID) >= 0");
            FeatureQueryResult queryResult = await tempTable.QueryFeaturesAsync(query);

            IEnumerator <Feature> resultFeatures = queryResult.GetEnumerator();
            List <Feature>        features       = new List <Feature>();

            while (resultFeatures.MoveNext())
            {
                features.Add(resultFeatures.Current);
            }

            long          row        = tempTable.NumberOfFeatures;
            int           col        = tempTable.Fields.Count;
            List <String> fieldNames = new List <string>();

            for (int i = 0; i < col; i++)
            {
                fieldNames.Add(tempTable.Fields[i] + "");
            }

            StackPanel stackPanel = new StackPanel();

            WrapPanel[] wrapPanels = new WrapPanel[row];

            // 字段名
            WrapPanel wrapPanelField = new WrapPanel()
            {
                Margin = new Thickness()
                {
                    Left   = 10,
                    Top    = 1,
                    Right  = 10,
                    Bottom = 1
                }
            };

            for (int i = 0; i < col; i++)
            {
                Button button = new Button()
                {
                    Content    = fieldNames[i],
                    ToolTip    = fieldNames[i],
                    Width      = 60,
                    Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 100, 183, 134))
                };
                wrapPanelField.Children.Add(button);
            }
            stackPanel.Children.Add(wrapPanelField);

            // 记录
            for (int i = 0; i < row; i++)
            {
                wrapPanels[i] = new WrapPanel()
                {
                    Margin = new Thickness()
                    {
                        Left   = 10,
                        Top    = 1,
                        Right  = 10,
                        Bottom = 1
                    }
                };
                for (int j = 0; j < col; j++)
                {
                    Button button = new Button()
                    {
                        Width   = 60,
                        Content = features[i].GetAttributeValue(fieldNames[j]),
                        ToolTip = features[i].GetAttributeValue(fieldNames[j])
                    };
                    wrapPanels[i].Children.Add(button);
                }
                stackPanel.Children.Add(wrapPanels[i]);
            }

            ScrollViewer scrollViewer = new ScrollViewer();

            scrollViewer.VerticalScrollBarVisibility   = ScrollBarVisibility.Visible;
            scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
            scrollViewer.Content = stackPanel;

            var window = new Window();

            window.Content               = scrollViewer;
            window.SizeToContent         = SizeToContent.WidthAndHeight;
            window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            window.MaxHeight             = 700;
            window.MaxWidth              = 1000;

            window.Title = check[index].Content + "属性表";
            window.Show();
        }
Ejemplo n.º 24
0
        private async void CreateFeatureCollectionLayerFromNYTimesArticles()
        {
            // Read the NY Times data from the text file and get back a list of each article.
            // The format of each record/article will look like:
            // [Article summary]~[Article abstract]~[Country name]~[Url to the NY times article]~[Url to an image about the NY times article]~[Date of NY Times news article]
            // Ex:
            // Netanyahu not happy with Cohen~A spokesman for Prime Minister Benjamin Netanyahu disagrees with Roger Cohen’s “pessimism.”~Israel~https://www.nytimes.com/2018/01/02/opinion/israel-future.html~https://www.nytimes.com/images/2017/12/29/opinion/29cohenWeb/29cohenWeb-thumbLarge.jpg~20180102
            List <string> myNYTimesArticles = ReadTextFile3(_NEWSFILE);

            // Get the collection of all the layers in the map.
            var myMapAllLayers = MyMapView.Map.AllLayers;

            // Create a place holder for the world countries feature layer.
            FeatureLayer myFeatureLayer = null;

            // Loop through all of the layers.
            foreach (var myLayer in myMapAllLayers)
            {
                // Get the Id of the layer.
                string myLayerName = myLayer.Id;

                // If the layer id matches world countries set that to the feature layer.
                if (myLayerName == "WorldCountries")
                {
                    myFeatureLayer = (FeatureLayer)myLayer;
                }
            }

            // Get the feature table from the world countries shape file feature layer.
            FeatureTable myFeatureTable = myFeatureLayer.FeatureTable;

            // Create a new query parameters.
            QueryParameters myQueryParameters = new QueryParameters();

            // Define the where clause for the query parameters. It will select all the records in the world countries shape file feature table.
            myQueryParameters.WhereClause = "1 = 1";

            // Execute the feature query and get the results back. It will select all the records in the world countries shape file feature table.
            FeatureQueryResult myFeatureQueryResult = await myFeatureTable.QueryFeaturesAsync(myQueryParameters);

            // Create the schema for the polygon feature collection table.
            List <Field> myFeatureCollectionAttributeFields = new List <Field>();

            // Create a field for the feature collection layer. It will contain a text field called area name that is the county name.
            Field myAreaNameField = new Field(FieldType.Text, "AreaName", "Area Name", 50);

            // Add the country name field to the list of fields that will be added to the feature collection table.
            myFeatureCollectionAttributeFields.Add(myAreaNameField);

            // Create the feature collection table based on the list of attribute fields, a polygons feature type
            FeatureCollectionTable myFeatureCollectionTable = new FeatureCollectionTable(myFeatureCollectionAttributeFields, GeometryType.Polygon, SpatialReferences.Wgs84);

            // Create the outline symbol for the country fill symbol.
            SimpleLineSymbol mySimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.DarkBlue, 2);

            // Create the fill symbol for the country. Solid yellow, with dark blue outline.
            SimpleFillSymbol mySimpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Yellow, mySimpleLineSymbol);

            // Set the renderer of the feature collection table to be the simple fill symbol.
            myFeatureCollectionTable.Renderer = new SimpleRenderer(mySimpleFillSymbol);

            // Loop through each feature in the returned feature query results of the world countries shape file
            foreach (Feature myFeature in myFeatureQueryResult)
            {
                // Get the geometry (aka shape) for one feature.
                Geometry myGeometry = myFeature.Geometry;

                // Get the value (aka. the text for the record of a specific field).
                var myValue = (string)myFeature.Attributes["NAME"];

                // Loop through each NY Times article.
                foreach (string oneNYTimesArticle in myNYTimesArticles)
                {
                    // Remove an embedded double quotes that may be in or surrounding the country name in the NY Times data base.
                    char[] charsToTrim = { '"' };
                    string country     = oneNYTimesArticle.Split('~')[2].Trim(charsToTrim);

                    // Find a match from the shape file country feature and the NY Times country name in the article.
                    if ((string)myValue == country)
                    {
                        // Create a new polygon feature, provide geometry and attribute values.
                        Feature polyFeature = myFeatureCollectionTable.CreateFeature();
                        polyFeature.SetAttributeValue(myAreaNameField, country);
                        polyFeature.Geometry = myGeometry;

                        // Add the new features to the appropriate feature collection table.
                        await myFeatureCollectionTable.AddFeatureAsync(polyFeature);

                        // Once we have found a matching country in the subset news article file that matches a shape file record
                        // there is no need to find another one since we have just created a record in the FeatureCollectionTable.
                        break;
                    }
                }
            }

            // Create a feature collection and add the feature collection tables
            FeatureCollection myFeatureCollection = new FeatureCollection();

            myFeatureCollection.Tables.Add(myFeatureCollectionTable);

            // Create a FeatureCollectionLayer
            FeatureCollectionLayer myFeatureCollectionLayer = new FeatureCollectionLayer(myFeatureCollection);

            myFeatureCollectionLayer.Id   = "Joined"; // might not be needed
            myFeatureCollectionLayer.Name = "JoinedFCL";

            // When the layer loads, zoom the map centered on the feature collection
            await myFeatureCollectionLayer.LoadAsync();

            // Add the layer to the Map's Operational Layers collection
            MyMapView.Map.OperationalLayers.Add(myFeatureCollectionLayer);
        }
Ejemplo n.º 25
0
        private async void renderBtn_Click(object sender, RoutedEventArgs e)
        {
            // 随机
            Random rd = new Random();

            UniqueValueRenderer regionRenderer = new UniqueValueRenderer();

            // 需要找的field的字段名
            regionRenderer.FieldNames.Add(chooseField);
            // 获取值
            QueryParameters query = new QueryParameters();

            query.WhereClause = string.Format("upper(FID) >= 0");
            FeatureQueryResult queryResult = await featureTable.QueryFeaturesAsync(query);

            IEnumerator <Feature> resultFeatures = queryResult.GetEnumerator();
            List <Object>         featureValue   = new List <Object>();

            try
            {
                while (resultFeatures.MoveNext())
                {
                    featureValue.Add((resultFeatures.Current).GetAttributeValue(chooseField));
                }
                featureValue = featureValue.Distinct().ToList();
            }
            catch
            {
                return;
            }
            // 将值分组
            int count = featureValue.Count;

            if (layer.FeatureTable.GeometryType == Esri.ArcGISRuntime.Geometry.GeometryType.Point)
            {
                for (int i = 0; i < count; i++)
                {
                    int num = rd.Next(0, sort);
                    System.Drawing.Color tempColor       = colorList[num];
                    SimpleMarkerSymbol   tempPointSymbol = new SimpleMarkerSymbol()
                    {
                        Color = tempColor, Size = 6, Style = SimpleMarkerSymbolStyle.Circle
                    };
                    regionRenderer.UniqueValues.Add(new UniqueValue("null", "null", tempPointSymbol, featureValue[i]));
                }
                regionRenderer.DefaultSymbol = defaultPoint;
                regionRenderer.DefaultLabel  = "zero";
            }
            else if (layer.FeatureTable.GeometryType == Esri.ArcGISRuntime.Geometry.GeometryType.Polyline)
            {
                for (int i = 0; i < count; i++)
                {
                    int num = rd.Next(0, sort);
                    System.Drawing.Color tempColor      = colorList[num];
                    SimpleLineSymbol     tempLineSymbol = new SimpleLineSymbol()
                    {
                        Style = SimpleLineSymbolStyle.Solid, Width = 5, Color = tempColor
                    };
                    regionRenderer.UniqueValues.Add(new UniqueValue("null", "null", tempLineSymbol, featureValue[i]));
                }
                regionRenderer.DefaultSymbol = defaultLine;
                regionRenderer.DefaultLabel  = "zero";
            }
            else if (layer.FeatureTable.GeometryType == Esri.ArcGISRuntime.Geometry.GeometryType.Polygon)
            {
                SimpleLineSymbol outLineSymbol = new SimpleLineSymbol()
                {
                    Style = SimpleLineSymbolStyle.Solid, Width = 3, Color = System.Drawing.Color.Gray
                };
                for (int i = 0; i < count; i++)
                {
                    int num = rd.Next(0, sort);
                    System.Drawing.Color tempColor      = colorList[num];
                    SimpleFillSymbol     tempFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, tempColor, outLineSymbol);
                    regionRenderer.UniqueValues.Add(new UniqueValue("null", "null", tempFillSymbol, featureValue[i]));
                }
                regionRenderer.DefaultSymbol = defaultFill;
                regionRenderer.DefaultLabel  = "zero";
            }
            layer.Renderer = regionRenderer;
        }
        private async void SolveRoutesButton_Click(object sender, EventArgs e)
        {
            // Holds locations of hospitals around San Diego.
            List <Facility> facilities = new List <Facility>();

            // Holds locations of hospitals around San Diego.
            List <Incident> incidents = new List <Incident>();

            // Create query parameters to select all features.
            QueryParameters queryParams = new QueryParameters()
            {
                WhereClause = "1=1"
            };

            // Query all features in the facility table.
            FeatureQueryResult facilityResult = await _facilityTable.QueryFeaturesAsync(queryParams);

            // Add all of the query results to facilities as new Facility objects.
            facilities.AddRange(facilityResult.ToList().Select(feature => new Facility((MapPoint)feature.Geometry)));

            // Query all features in the incident table.
            FeatureQueryResult incidentResult = await _incidentTable.QueryFeaturesAsync(queryParams);

            // Add all of the query results to facilities as new Incident objects.
            incidents.AddRange(incidentResult.ToList().Select(feature => new Incident((MapPoint)feature.Geometry)));

            // Set facilities and incident in parameters.
            ClosestFacilityParameters closestFacilityParameters = await _task.CreateDefaultParametersAsync();

            closestFacilityParameters.SetFacilities(facilities);
            closestFacilityParameters.SetIncidents(incidents);

            try
            {
                // Use the task to solve for the closest facility.
                ClosestFacilityResult result = await _task.SolveClosestFacilityAsync(closestFacilityParameters);

                for (int i = 0; i < incidents.Count; i++)
                {
                    // Get the index of the closest facility to incident. (i) is the index of the incident, [0] is the index of the closest facility.
                    int closestFacility = result.GetRankedFacilityIndexes(i)[0];

                    // Get the route to the closest facility.
                    ClosestFacilityRoute route = result.GetRoute(closestFacility, i);

                    // Display the route on the graphics overlay.
                    _myMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(route.RouteGeometry, _routeSymbols[i % _routeSymbols.Count]));
                }

                // Disable the solve button.
                _solveRoutesButton.Enabled = false;
                _solveRoutesButton.SetTitleColor(UIColor.Gray, UIControlState.Disabled);

                // Enable the reset button.
                _resetButton.Enabled = true;
                _resetButton.SetTitleColor(UIColor.Blue, UIControlState.Normal);
            }
            catch (Esri.ArcGISRuntime.Http.ArcGISWebException exception)
            {
                CreateErrorDialog("An ArcGIS web exception occurred.\n" + exception.Message);
            }
        }
Ejemplo n.º 27
0
        private async void GeoViewTapped(object sender, Esri.ArcGISRuntime.UI.Controls.GeoViewInputEventArgs e)
        {
            try
            {
                // Disregard if not ready for edits.
                if (_readyForEdits == EditState.NotReady)
                {
                    return;
                }

                // If an edit is in process, finish it.
                if (_readyForEdits == EditState.Editing)
                {
                    // Hold a list of any selected features.
                    List <Feature> selectedFeatures = new List <Feature>();

                    // Get all selected features then clear selection.
                    foreach (FeatureLayer layer in MyMapView.Map.OperationalLayers)
                    {
                        // Get the selected features.
                        FeatureQueryResult layerFeatures = await layer.GetSelectedFeaturesAsync();

                        // FeatureQueryResult implements IEnumerable, so it can be treated as a collection of features.
                        selectedFeatures.AddRange(layerFeatures);

                        // Clear the selection.
                        layer.ClearSelection();
                    }

                    // Update all selected feature geometry.
                    foreach (Feature feature in selectedFeatures)
                    {
                        // Get a reference to the correct feature table for the feature.
                        GeodatabaseFeatureTable table = (GeodatabaseFeatureTable)feature.FeatureTable;

                        // Ensure the geometry type of the table is point.
                        if (table.GeometryType != GeometryType.Point)
                        {
                            continue;
                        }

                        // Set the new geometry.
                        feature.Geometry = e.Location;

                        try
                        {
                            // Update the feature in the table.
                            await table.UpdateFeatureAsync(feature);
                        }
                        catch (Esri.ArcGISRuntime.ArcGISException)
                        {
                            ShowStatusMessage("Feature must be within extent of geodatabase.");
                        }
                    }

                    // Update the edit state.
                    _readyForEdits = EditState.Ready;

                    // Enable the sync button.
                    SyncButton.IsEnabled = true;

                    // Update the help label.
                    MyHelpLabel.Text = "4. Click 'Sync' or edit more features";
                }
                // Otherwise, start an edit.
                else
                {
                    // Define a tolerance for use with identifying the feature.
                    double tolerance = 15 * MyMapView.UnitsPerPixel;

                    // Define the selection envelope.
                    Envelope selectionEnvelope = new Envelope(e.Location.X - tolerance, e.Location.Y - tolerance, e.Location.X + tolerance, e.Location.Y + tolerance);

                    // Define query parameters for feature selection.
                    QueryParameters query = new QueryParameters()
                    {
                        Geometry = selectionEnvelope
                    };

                    // Track whether any selections were made.
                    bool selectedFeature = false;

                    // Select the feature in all applicable tables.
                    foreach (FeatureLayer layer in MyMapView.Map.OperationalLayers)
                    {
                        FeatureQueryResult res = await layer.SelectFeaturesAsync(query, SelectionMode.New);

                        selectedFeature = selectedFeature || res.Any();
                    }

                    // Only update state if a feature was selected.
                    if (selectedFeature)
                    {
                        // Set the edit state.
                        _readyForEdits = EditState.Editing;

                        // Update the help label.
                        MyHelpLabel.Text = "3. Tap on the map to move the point";
                    }
                }
            }
            catch (Exception ex)
            {
                ShowStatusMessage(ex.ToString());
            }
        }
Ejemplo n.º 28
0
        private async void QuerySublayers_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // Clear selected features from the graphics overlay.
            _selectedFeaturesOverlay.Graphics.Clear();

            // If the population value entered is not numeric, warn the user and exit.
            double populationNumber = 0.0;

            if (!double.TryParse(PopulationTextBox.Text.Trim(), out populationNumber))
            {
                MessageBox.Show("The population value must be numeric.", "Query error");
                return;
            }

            // Get the USA map image layer (the first and only operational layer in the map).
            ArcGISMapImageLayer usaMapImageLayer = (ArcGISMapImageLayer)MyMapView.Map.OperationalLayers[0];

            try
            {
                // Use a utility method on the map image layer to load all the sublayers and tables.
                await usaMapImageLayer.LoadTablesAndLayersAsync();

                // Get the sublayers of interest (skip 'Highways' since it doesn't have the POP2000 field).
                ArcGISMapImageSublayer citiesSublayer   = (ArcGISMapImageSublayer)usaMapImageLayer.Sublayers[0];
                ArcGISMapImageSublayer statesSublayer   = (ArcGISMapImageSublayer)usaMapImageLayer.Sublayers[2];
                ArcGISMapImageSublayer countiesSublayer = (ArcGISMapImageSublayer)usaMapImageLayer.Sublayers[3];

                // Get the service feature table for each of the sublayers.
                ServiceFeatureTable citiesTable   = citiesSublayer.Table;
                ServiceFeatureTable statesTable   = statesSublayer.Table;
                ServiceFeatureTable countiesTable = countiesSublayer.Table;

                // Create the query parameters that will find features in the current extent with a population greater than the value entered.
                QueryParameters populationQuery = new QueryParameters
                {
                    WhereClause = "POP2000 > " + PopulationTextBox.Text,
                    Geometry    = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry
                };

                // Query each of the sublayers with the query parameters.
                FeatureQueryResult citiesQueryResult = await citiesTable.QueryFeaturesAsync(populationQuery);

                FeatureQueryResult statesQueryResult = await statesTable.QueryFeaturesAsync(populationQuery);

                FeatureQueryResult countiesQueryResult = await countiesTable.QueryFeaturesAsync(populationQuery);

                // Display the selected cities in the graphics overlay.
                SimpleMarkerSymbol citySymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Red, 16);
                foreach (Feature city in citiesQueryResult)
                {
                    Graphic cityGraphic = new Graphic(city.Geometry, citySymbol);

                    _selectedFeaturesOverlay.Graphics.Add(cityGraphic);
                }

                // Display the selected counties in the graphics overlay.
                SimpleLineSymbol countyLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.Cyan, 2);
                SimpleFillSymbol countySymbol     = new SimpleFillSymbol(SimpleFillSymbolStyle.DiagonalCross, Color.Cyan, countyLineSymbol);
                foreach (Feature county in countiesQueryResult)
                {
                    Graphic countyGraphic = new Graphic(county.Geometry, countySymbol);

                    _selectedFeaturesOverlay.Graphics.Add(countyGraphic);
                }

                // Display the selected states in the graphics overlay.
                SimpleLineSymbol stateLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.DarkCyan, 6);
                SimpleFillSymbol stateSymbol     = new SimpleFillSymbol(SimpleFillSymbolStyle.Null, Color.Cyan, stateLineSymbol);
                foreach (Feature state in statesQueryResult)
                {
                    Graphic stateGraphic = new Graphic(state.Geometry, stateSymbol);

                    _selectedFeaturesOverlay.Graphics.Add(stateGraphic);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error");
            }
        }
        private async void GeoViewTapped(object sender, GeoViewInputEventArgs e)
        {
            try
            {
                // Disregard if not ready for edits.
                if (_readyForEdits == EditState.NotReady)
                {
                    return;
                }

                // If an edit is in process, finish it.
                if (_readyForEdits == EditState.Editing)
                {
                    // Hold a list of any selected features.
                    List <Feature> selectedFeatures = new List <Feature>();

                    // Get all selected features then clear selection.
                    foreach (FeatureLayer layer in myMapView.Map.OperationalLayers)
                    {
                        // Get the selected features.
                        FeatureQueryResult layerFeatures = await layer.GetSelectedFeaturesAsync();

                        // FeatureQueryResult implements IEnumerable, so it can be treated as a collection of features.
                        selectedFeatures.AddRange(layerFeatures);

                        // Clear the selection.
                        layer.ClearSelection();
                    }

                    // Update all selected features' geometry.
                    foreach (Feature feature in selectedFeatures)
                    {
                        // Get a reference to the correct feature table for the feature.
                        GeodatabaseFeatureTable table = (GeodatabaseFeatureTable)feature.FeatureTable;

                        // Ensure the geometry type of the table is point.
                        if (table.GeometryType != GeometryType.Point)
                        {
                            continue;
                        }

                        // Set the new geometry.
                        feature.Geometry = e.Location;

                        // Update the feature in the table.
                        await table.UpdateFeatureAsync(feature);
                    }

                    // Update the edit state.
                    _readyForEdits = EditState.Ready;

                    // Enable the sync button.
                    mySyncButton.IsEnabled = true;

                    // Update the help label.
                    MyHelpLabel.Text = "4. Click 'Synchronize' or keep editing";
                }
                // Otherwise, start an edit.
                else
                {
                    // Define a tolerance for use with identifying the feature.
                    double tolerance = 15 * myMapView.UnitsPerPixel;

                    // Define the selection envelope.
                    Envelope selectionEnvelope = new Envelope(e.Location.X - tolerance, e.Location.Y - tolerance, e.Location.X + tolerance, e.Location.Y + tolerance);

                    // Define query parameters for feature selection.
                    QueryParameters query = new QueryParameters()
                    {
                        Geometry = selectionEnvelope
                    };

                    // Select the feature in all applicable tables.
                    foreach (FeatureLayer layer in myMapView.Map.OperationalLayers)
                    {
                        await layer.SelectFeaturesAsync(query, SelectionMode.New);
                    }

                    // Set the edit state.
                    _readyForEdits = EditState.Editing;

                    // Update the help label.
                    MyHelpLabel.Text = "3. Tap on the map to move the point";
                }
            }
            catch (Exception ex)
            {
                await((Page)Parent).DisplayAlert("Error", ex.ToString(), "OK");
            }
        }
Ejemplo n.º 30
0
        private async void OnMapViewTapped(object sender, GeoViewInputEventArgs evt)
        {
            try
            {
                // グラフィック オーバレイに追加したグラフィックを削除
                myGraphicsOverlay.Graphics.Clear();

                // シンボルの作成
                var incidentPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Colors.Red, 8);
                var outLineSymbol       = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(100, 255, 183, 51), 2);
                var bufferPolygonSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.FromArgb(75, 255, 183, 51), outLineSymbol);

                // クリック地点をマップに表示
                var point    = evt.Location;
                var location = new Graphic(point, incidentPointSymbol);

                myGraphicsOverlay.Graphics.Add(location);

                // クリック地点を解析のパラメーターに設定
                var incidentOneLocation = new MapPoint(evt.Location.X, evt.Location.Y, MyMapView.SpatialReference);
                var incidentOne         = new Incident(incidentOneLocation);

                var incidentList = new List <Incident>();
                incidentList.Add(incidentOne);

                closestFacilityParameters.SetIncidents(incidentList);

                // タップした地点から1000メートルのバッファーの円を作成し、グラフィックとして表示する
                var buffer  = GeometryEngine.Buffer(evt.Location, 1000);
                var graphic = new Graphic(buffer, null, bufferPolygonSymbol);

                myGraphicsOverlay.Graphics.Add(graphic);

                // フィーチャの検索用のパラメーターを作成
                var queryParams = new QueryParameters();
                // 検索範囲を作成したバファーの円に指定
                queryParams.Geometry = buffer;

                // 検索範囲とフィーチャの空間的な関係性を指定(バファーの円の中にフィーチャが含まれる)
                queryParams.SpatialRelationship = SpatialRelationship.Contains;
                // フィーチャの検索を実行
                FeatureQueryResult queryResult = await shelterLayer.FeatureTable.QueryFeaturesAsync(queryParams);

                // 検索結果のフィーチャのリストを取得
                var queryList  = queryResult.ToList();
                var facilities = new List <Facility>();

                for (int i = 0; i < queryList.Count; ++i)
                {
                    facilities.Add(new Facility((MapPoint)queryList[i].Geometry));
                }

                // パラメーターを設定し、最寄り施設検出解析を実行
                closestFacilityParameters.SetFacilities(facilities);
                closestFacility();
            }
            catch (Exception ex)
            {
                MessageBox.Show("解析の実行エラー " + ex.Message);
            }
        }