// Prepare the data source for editing
        public void WillBeginTableEditing(UITableView tableView)
        {
            // See if the table already has a placeholder row for the "Add New" button
            StatisticDefinition existingItem = _statisticDefinitions.Find(itm => itm.OnFieldName == AddNewStatFieldName);

            // Return if there is already a placeholder row
            if (existingItem != null)
            {
                return;
            }

            // Begin updating the table
            tableView.BeginUpdates();

            // Create an index path for the last row in the table
            NSIndexPath lastRowIndex = NSIndexPath.FromRowSection(tableView.NumberOfRowsInSection(0), 0);

            // Add the insert placeholder row at the end of table display
            tableView.InsertRows(new NSIndexPath[] { lastRowIndex }, UITableViewRowAnimation.Fade);

            // Create a new StatisticDefinition and add it to the underlying data
            _statisticDefinitions.Add(new StatisticDefinition(AddNewStatFieldName, StatisticType.Count, ""));

            // Apply the table edits
            tableView.EndUpdates();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Adds a statistic definition against an overlay
        /// </summary>
        /// <param name="overlay">The overlay</param>
        /// <param name="statistic">The statistic definition</param>
        public void AddOverlayStatistic
        (
            GraphicOverlay overlay,
            StatisticDefinition statistic
        )
        {
            Validate.IsNotNull(overlay);
            Validate.IsNotNull(statistic);

            var overlayId = overlay.OverlayId;
            var entry     = this.OverlayStatistics[overlayId];

            var statisticAlreadyAdded = entry.Exists
                                        (
                s => s.ComponentId == statistic.ComponentId
                                        );

            if (statisticAlreadyAdded)
            {
                throw new InvalidOperationException
                      (
                          $"'{statistic.Name}' has already been added to the overlay."
                      );
            }
            else
            {
                entry.Add(statistic);
            }
        }
        // Constructor that takes a picker for defining new statistics.
        public ChooseStatisticOverlay(CGRect frame, nfloat transparency, UIColor color, UIPickerView statPicker) : base(frame)
        {
            // Store the statistics picker.
            var statisticPicker = statPicker;

            // Create a semi-transparent overlay with the specified background color.
            BackgroundColor = color;
            Alpha           = transparency;

            // Set the total height and width of the control set.
            nfloat totalHeight = 400;
            nfloat totalWidth  = 320;

            // Find the bottom x and y of the view.
            nfloat centerX = Frame.Width / 2;
            nfloat centerY = Frame.Bottom - 40;

            // Find the start x and y for the control layout (aligned to the bottom of the view).
            nfloat controlX = centerX - totalWidth / 2;
            nfloat controlY = centerY - totalHeight;

            // Toolbar with "Add" and "Done" buttons.
            UIToolbar toolbar = new UIToolbar
            {
                BarStyle    = UIBarStyle.Black,
                Translucent = false
            };

            toolbar.SizeToFit();

            // Add Button (add the new stat and don't dismiss the UI).
            UIBarButtonItem addButton = new UIBarButtonItem("Add", UIBarButtonItemStyle.Done, (s, e) =>
            {
                // Get the selected StatisticDefinition.
                StatDefinitionModel statPickerModel   = statisticPicker.Model as StatDefinitionModel;
                StatisticDefinition newStatDefinition = statPickerModel.SelectedStatDefinition;
                if (newStatDefinition != null)
                {
                    // Fire the OnMapInfoEntered event and provide the statistic definition.
                    OnStatisticDefined?.Invoke(this, newStatDefinition);
                }
            });

            // Done Button (dismiss the UI, don't use the selected statistic).
            UIBarButtonItem doneButton = new UIBarButtonItem("Done", UIBarButtonItemStyle.Plain, (s, e) => { OnCanceled.Invoke(this, null); });

            // Add the buttons to the toolbar.
            toolbar.SetItems(new[] { addButton, doneButton }, true);

            // Define the location of the statistic picker.
            controlY = controlY + 200;
            statisticPicker.Frame = new CGRect(controlX, controlY, totalWidth, 200);

            // Set the location for the toolbar.
            controlY      = controlY + 220;
            toolbar.Frame = new CGRect(controlX, controlY, totalWidth, 30);

            // Add the controls.
            AddSubviews(toolbar, statisticPicker);
        }
        private async void ExecuteStatisticsQuery(object sender, EventArgs e)
        {
            // Remove the placeholder "Add statistic" row (if it exists)
            StatisticDefinition placeholderRow = _statisticDefinitions.LastOrDefault();

            if (placeholderRow != null && placeholderRow.OutputAlias == "")
            {
                _statisticDefinitions.Remove(placeholderRow);
            }

            // Verify that there is at least one statistic definition
            if (_statisticDefinitions.Count() == 0)
            {
                ShowAlert("Statistical Query", "Please define at least one statistic for the query.");
                return;
            }

            // Create the statistics query parameters, pass in the list of statistic definitions
            StatisticsQueryParameters statQueryParams = new StatisticsQueryParameters(_statisticDefinitions);

            // Specify the selected group fields (if any)
            if (_groupByFields != null)
            {
                foreach (KeyValuePair <string, bool> groupField in _groupByFields.Where(field => field.Value == true))
                {
                    statQueryParams.GroupByFieldNames.Add(groupField.Key);
                }
            }

            // Specify the fields to order by (if any)
            if (_orderByFields != null)
            {
                foreach (OrderFieldOption orderBy in _orderByFields)
                {
                    statQueryParams.OrderByFields.Add(orderBy.OrderInfo);
                }
            }

            // Execute the statistical query with these parameters and await the results
            StatisticsQueryResult statQueryResult = await _usStatesTable.QueryStatisticsAsync(statQueryParams);

            // Get results formatted as a dictionary (group names and their associated dictionary of results)
            Dictionary <string, IReadOnlyDictionary <string, object> > resultsLookup = statQueryResult.ToDictionary(result => string.Join(", ", result.Group.Values), result => result.Statistics);

            // Create an instance of a custom data source to display the results
            StatisticQueryResultsDataSource statResultsDataSource = new StatisticQueryResultsDataSource(resultsLookup);

            // Create a new table with a grouped style for displaying rows
            UITableViewController statResultsTable = new UITableViewController(UITableViewStyle.Grouped);

            // Set the table view data source
            statResultsTable.TableView.Source = statResultsDataSource;

            // Show the table view
            this.NavigationController.PushViewController(statResultsTable, true);
        }
        // Handle supported edits to the data source (inserts and deletes).
        public override void CommitEditingStyle(UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
        {
            // Respond to the user's edit request: Insert a new statistic definition, or delete an existing one.
            if (editingStyle == UITableViewCellEditingStyle.Insert)
            {
                // Create an overlay UI that lets the user choose a field and statistic type to add.
                _chooseStatOverlay = new ChooseStatisticOverlay(_statPicker);

                // Handle the OnStatisticDefined event to get the info entered by the user.
                _chooseStatOverlay.OnStatisticDefined += (s, statDef) =>
                {
                    // Verify the selected statistic doesn't exist in the collection (check for an alias with the same value).
                    StatisticDefinition existingItem = _statisticDefinitions.Find(itm => itm.OutputAlias == statDef.OutputAlias);
                    if (existingItem != null)
                    {
                        return;
                    }

                    // Make updates to the table (add the chosen statistic).
                    tableView.BeginUpdates();

                    // Insert a new row at the top of table display.
                    tableView.InsertRows(new[] { NSIndexPath.FromRowSection(0, 0) }, UITableViewRowAnimation.Fade);

                    // Insert the chosen statistic in the underlying collection.
                    _statisticDefinitions.Insert(0, statDef);

                    // Apply table edits.
                    tableView.EndUpdates();
                };

                // Handle when the user chooses to close the dialog.
                _chooseStatOverlay.OnCanceled += (s, e) =>
                {
                    // Remove the item input UI.
                    _chooseStatOverlay.Hide();
                    _chooseStatOverlay = null;
                };

                // Add the picker UI view (will display semi-transparent over the table view).
                tableView.AddSubview(_chooseStatOverlay);

                _chooseStatOverlay.TranslatesAutoresizingMaskIntoConstraints = false;
                _chooseStatOverlay.LeadingAnchor.ConstraintEqualTo(tableView.SafeAreaLayoutGuide.LeadingAnchor).Active =
                    true;
                _chooseStatOverlay.TrailingAnchor.ConstraintEqualTo(tableView.SafeAreaLayoutGuide.TrailingAnchor)
                .Active = true;
                _chooseStatOverlay.BottomAnchor.ConstraintEqualTo(tableView.SafeAreaLayoutGuide.BottomAnchor).Active = true;
            }
            else if (editingStyle == UITableViewCellEditingStyle.Delete)
            {
                // Remove the selected row from the table and the underlying collection of statistic definitions.
                _statisticDefinitions.RemoveAt(indexPath.Row);
                tableView.DeleteRows(new[] { indexPath }, UITableViewRowAnimation.Fade);
            }
        }
        private async void OnExecuteStatisticsQueryClicked(object sender, EventArgs e)
        {
            // Create definitions for each statistic to calculate
            StatisticDefinition statDefinitionAvgPop    = new StatisticDefinition("POP", StatisticType.Average, "");
            StatisticDefinition statDefinitionMinPop    = new StatisticDefinition("POP", StatisticType.Minimum, "");
            StatisticDefinition statDefinitionMaxPop    = new StatisticDefinition("POP", StatisticType.Maximum, "");
            StatisticDefinition statDefinitionSumPop    = new StatisticDefinition("POP", StatisticType.Sum, "");
            StatisticDefinition statDefinitionStdDevPop = new StatisticDefinition("POP", StatisticType.StandardDeviation, "");
            StatisticDefinition statDefinitionVarPop    = new StatisticDefinition("POP", StatisticType.Variance, "");

            // Create a definition for count that includes an alias for the output
            StatisticDefinition statDefinitionCount = new StatisticDefinition("POP", StatisticType.Count, "CityCount");

            // Add the statistics definitions to a list
            List <StatisticDefinition> statDefinitions = new List <StatisticDefinition>
            {
                statDefinitionAvgPop,
                statDefinitionCount,
                statDefinitionMinPop,
                statDefinitionMaxPop,
                statDefinitionSumPop,
                statDefinitionStdDevPop,
                statDefinitionVarPop
            };

            // Create the statistics query parameters, pass in the list of definitions
            StatisticsQueryParameters statQueryParams = new StatisticsQueryParameters(statDefinitions);

            // If only using features in the current extent, set up the spatial filter for the statistics query parameters
            if (_onlyInExtentSwitch.Checked)
            {
                // Get the current extent (envelope) from the map view
                Envelope currentExtent = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry as Envelope;

                // Set the statistics query parameters geometry with the envelope
                statQueryParams.Geometry = currentExtent;

                // Set the spatial relationship to Intersects (which is the default)
                statQueryParams.SpatialRelationship = SpatialRelationship.Intersects;
            }

            // If only evaluating the largest cities (over 5 million in population), set up an attribute filter
            if (_onlyBigCitiesSwitch.Checked)
            {
                // Set a where clause to get the largest cities (could also use "POP_CLASS = '5,000,000 and greater'")
                statQueryParams.WhereClause = "POP_RANK = 1";
            }

            // Execute the statistical query with these parameters and await the results
            StatisticsQueryResult statQueryResult = await _worldCitiesTable.QueryStatisticsAsync(statQueryParams);

            // Display results in a list in a dialog
            List <KeyValuePair <string, object> > statsList = statQueryResult.First().Statistics.ToList();

            ShowStatsList(statsList);
        }
        // Handle supported edits to the data source (inserts and deletes)
        public override void CommitEditingStyle(UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
        {
            // Respond to the user's edit request: Insert a new statistic definition, or delete an existing one
            if (editingStyle == UITableViewCellEditingStyle.Insert)
            {
                // Get the bounds of the table
                CGRect ovBounds = tableView.Bounds;
                ovBounds.Height = ovBounds.Height + 60;

                // Create an overlay UI that lets the user choose a field and statistic type to add
                _chooseStatOverlay = new ChooseStatisticOverlay(ovBounds, 0.70f, UIColor.White, _statPicker);

                // Handle the OnStatisticDefined event to get the info entered by the user
                _chooseStatOverlay.OnStatisticDefined += (s, statDef) =>
                {
                    // Verify the selected statistic doesn't exist in the collection (check for an alias with the same value)
                    StatisticDefinition existingItem = _statisticDefinitions.Find(itm => itm.OutputAlias == statDef.OutputAlias);
                    if (existingItem != null)
                    {
                        return;
                    }

                    // Make updates to the table (add the chosen statistic)
                    tableView.BeginUpdates();

                    // Insert a new row at the top of table display
                    tableView.InsertRows(new NSIndexPath[] { NSIndexPath.FromRowSection(0, 0) }, UITableViewRowAnimation.Fade);

                    // Insert the chosen statistic in the underlying collection
                    _statisticDefinitions.Insert(0, statDef);

                    // Apply table edits
                    tableView.EndUpdates();
                };

                // Handle when the user chooses to close the dialog
                _chooseStatOverlay.OnCanceled += (s, e) =>
                {
                    // Remove the item input UI
                    _chooseStatOverlay.Hide();
                    _chooseStatOverlay = null;
                };

                // Add the picker UI view (will display semi-transparent over the table view)
                tableView.Add(_chooseStatOverlay);
            }
            else if (editingStyle == UITableViewCellEditingStyle.Delete)
            {
                // Remove the selected row from the table and the underlying collection of statistic definitions
                _statisticDefinitions.RemoveAt(indexPath.Row);
                tableView.DeleteRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade);
            }
        }
        // Remove the selected statistic definition from the list
        private void RemoveStatisticClicked(object sender, RoutedEventArgs e)
        {
            // Verify that there is a selected statistic definition
            if (StatFieldsListBox.SelectedItem == null)
            {
                return;
            }

            // Get the selected statistic definition and remove it from the collection
            StatisticDefinition selectedStat = StatFieldsListBox.SelectedItem as StatisticDefinition;

            _statDefinitions.Remove(selectedStat);
        }
        // Handle the selection event for the picker to create a statistic definition with the values chosen
        public override void Selected(UIPickerView pickerView, nint row, nint component)
        {
            // Get the field name
            string onFieldName = _fieldNames[pickerView.SelectedRowInComponent(0)];

            // Get the statistic type
            StatisticType statType = (StatisticType)_statTypes.GetValue(pickerView.SelectedRowInComponent(1));

            // Create an output field alias by concatenating the field name and statistic type
            string outAlias = onFieldName + "_" + statType.ToString();

            // Create a new statistic definition (available from the SelectedStatDefinition public property)
            _selectedStatDefinition = new StatisticDefinition(onFieldName, statType, outAlias);
        }
        // Handler for the AddStatisticDefinitionButton click event
        private void AddStatisticDefinition(object sender, EventArgs e)
        {
            // Get the selected field name in the dialog
            string fieldName = _fieldSpinner.SelectedItem.ToString();

            // Get the selected statistic type name in the dialog and get the corresponding enum value
            string        statTypeName = _statSpinner.SelectedItem.ToString();
            StatisticType statType     = (StatisticType)Enum.Parse(typeof(StatisticType), statTypeName);

            // Build a field alias for the statistic results that use the field name and statistic type
            string alias = fieldName + "_" + statTypeName;

            // Create a new StatisticDefinition with the field name, statistic type, and output field alias
            StatisticDefinition statisticDefinition = new StatisticDefinition(fieldName, statType, alias);

            // Call a function in the custom list adapter that will add the new statistic definition (and update the data in the list view)
            ((StatDefinitionListAdapter)_statDefListView.Adapter).AddStatisticDefinition(statisticDefinition);
        }
        // Constructor that takes a picker for defining new statistics.
        public ChooseStatisticOverlay(UIPickerView statPicker)
        {
            this.TranslatesAutoresizingMaskIntoConstraints = false;
            // Toolbar with "Add" and "Done" buttons.
            UIToolbar toolbar = new UIToolbar();

            toolbar.TranslatesAutoresizingMaskIntoConstraints = false;

            statPicker.TranslatesAutoresizingMaskIntoConstraints = false;

            // Add Button (add the new stat and don't dismiss the UI).
            UIBarButtonItem addButton = new UIBarButtonItem("Add", UIBarButtonItemStyle.Plain, (s, e) =>
            {
                // Get the selected StatisticDefinition.
                StatDefinitionModel statPickerModel   = (StatDefinitionModel)statPicker.Model;
                StatisticDefinition newStatDefinition = statPickerModel.SelectedStatDefinition;
                if (newStatDefinition != null)
                {
                    // Fire the OnMapInfoEntered event and provide the statistic definition.
                    OnStatisticDefined?.Invoke(this, newStatDefinition);
                }
            });

            // Done Button (dismiss the UI, don't use the selected statistic).
            UIBarButtonItem doneButton = new UIBarButtonItem("Done", UIBarButtonItemStyle.Done,
                                                             (s, e) => { OnCanceled?.Invoke(this, null); });

            // Add the buttons to the toolbar.
            toolbar.Items = new[] { addButton, doneButton };

            statPicker.BackgroundColor = UIColor.White;

            // Add the controls.
            AddSubviews(toolbar, statPicker);

            toolbar.BottomAnchor.ConstraintEqualTo(BottomAnchor).Active     = true;
            toolbar.LeadingAnchor.ConstraintEqualTo(LeadingAnchor).Active   = true;
            toolbar.TrailingAnchor.ConstraintEqualTo(TrailingAnchor).Active = true;

            statPicker.TopAnchor.ConstraintEqualTo(TopAnchor).Active            = true;
            statPicker.LeadingAnchor.ConstraintEqualTo(LeadingAnchor).Active    = true;
            statPicker.TrailingAnchor.ConstraintEqualTo(TrailingAnchor).Active  = true;
            statPicker.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor).Active = true;
        }
        // This is called each time a cell needs to be created in the table
        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            // Create a new cell with a main and detail label style
            UITableViewCell cell = new UITableViewCell(UITableViewCellStyle.Subtitle, null);

            // Get the corresponding StatisticDefinition for this row
            StatisticDefinition definition = _statisticDefinitions[indexPath.Row] as StatisticDefinition;

            // Set the cell text with the field name
            cell.TextLabel.Text = definition.OnFieldName;

            // If this is not the placeholder (insert) row, set the detail text with the statistic type
            if (definition.OnFieldName != AddNewStatFieldName)
            {
                cell.DetailTextLabel.Text = definition.StatisticType.ToString();
            }

            // Return the new cell
            return(cell);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Removes a statistic definition for an overlay
        /// </summary>
        /// <param name="overlay">The overlay</param>
        /// <param name="statistic">The statistic definition</param>
        public void RemoveOverlayStatistic
        (
            GraphicOverlay overlay,
            StatisticDefinition statistic
        )
        {
            Validate.IsNotNull(overlay);
            Validate.IsNotNull(statistic);

            var overlayId = overlay.OverlayId;

            var entryFound = this.OverlayStatistics.ContainsKey
                             (
                overlayId
                             );

            if (false == entryFound)
            {
                throw new KeyNotFoundException
                      (
                          "The overlay specified was not found."
                      );
            }
            else
            {
                var entry = this.OverlayStatistics[overlayId];

                if (false == entry.Contains(statistic))
                {
                    throw new InvalidOperationException
                          (
                              $"'{statistic.Name}' has not been added to the overlay."
                          );
                }
                else
                {
                    entry.Remove(statistic);
                }
            }
        }
        // Create a statistic definition and add it to the collection based on the user selection in the combo boxes
        private void AddStatisticClicked(object sender, RoutedEventArgs e)
        {
            // Verify that a field name and statistic type has been selected
            if (FieldsComboBox.SelectedValue == null || StatTypeComboBox.SelectedValue == null)
            {
                return;
            }

            // Get the chosen field name and statistic type from the combo boxes
            string        fieldName = FieldsComboBox.SelectedValue.ToString();
            StatisticType statType  = (StatisticType)StatTypeComboBox.SelectedValue;

            // Check if this statistic definition has already be created (same field name and statistic type)
            StatisticDefinition existingStatDefinition = _statDefinitions.FirstOrDefault(def => def.OnFieldName == fieldName && def.StatisticType == statType);

            // If it doesn't exist, create it and add it to the collection (use the field name and statistic type to build the output alias)
            if (existingStatDefinition == null)
            {
                StatisticDefinition statDefinition = new StatisticDefinition(fieldName, statType, fieldName + "_" + statType.ToString());
                _statDefinitions.Add(statDefinition);
            }
        }
Exemplo n.º 15
0
        private async void OnExecuteStatisticsQueryClicked(object sender, EventArgs e)
        {
            // Create definitions for each statistic to calculate
            StatisticDefinition statDefinitionAvgPop    = new StatisticDefinition("POP", StatisticType.Average, "");
            StatisticDefinition statDefinitionMinPop    = new StatisticDefinition("POP", StatisticType.Minimum, "");
            StatisticDefinition statDefinitionMaxPop    = new StatisticDefinition("POP", StatisticType.Maximum, "");
            StatisticDefinition statDefinitionSumPop    = new StatisticDefinition("POP", StatisticType.Sum, "");
            StatisticDefinition statDefinitionStdDevPop = new StatisticDefinition("POP", StatisticType.StandardDeviation, "");
            StatisticDefinition statDefinitionVarPop    = new StatisticDefinition("POP", StatisticType.Variance, "");

            // Create a definition for count that includes an alias for the output
            StatisticDefinition statDefinitionCount = new StatisticDefinition("POP", StatisticType.Count, "CityCount");

            // Add the statistics definitions to a list
            List <StatisticDefinition> statDefinitions = new List <StatisticDefinition>
            {
                statDefinitionAvgPop,
                statDefinitionCount,
                statDefinitionMinPop,
                statDefinitionMaxPop,
                statDefinitionSumPop,
                statDefinitionStdDevPop,
                statDefinitionVarPop
            };

            // Create the statistics query parameters, pass in the list of definitions
            StatisticsQueryParameters statQueryParams = new StatisticsQueryParameters(statDefinitions);

            // If only using features in the current extent, set up the spatial filter for the statistics query parameters
            if (_onlyInExtentSwitch.On)
            {
                // Get the current extent (envelope) from the map view
                Envelope currentExtent = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry as Envelope;

                // Set the statistics query parameters geometry with the envelope
                statQueryParams.Geometry = currentExtent;

                // Set the spatial relationship to Intersects (which is the default)
                statQueryParams.SpatialRelationship = SpatialRelationship.Intersects;
            }

            // If only evaluating the largest cities (over 5 million in population), set up an attribute filter
            if (_onlyBigCitiesSwitch.On)
            {
                // Set a where clause to get the largest cities (could also use "POP_CLASS = '5,000,000 and greater'")
                statQueryParams.WhereClause = "POP_RANK = 1";
            }

            // Execute the statistical query with these parameters and await the results
            StatisticsQueryResult statQueryResult = await _worldCitiesTable.QueryStatisticsAsync(statQueryParams);

            // Get the first (only) StatisticRecord in the results
            StatisticRecord record = statQueryResult.FirstOrDefault();

            // Make sure a record was returned
            if (record == null || record.Statistics.Count == 0)
            {
                // Notify the user that no results were returned
                UIAlertView alert = new UIAlertView();
                alert.Message = "No results were returned";
                alert.Title   = "Statistical Query";
                alert.Show();
                return;
            }

            // Display results
            IReadOnlyDictionary <string, object> statistics = record.Statistics;

            ShowStatsList(statistics);
        }
Exemplo n.º 16
0
        private async void OnExecuteStatisticsQueryClicked(object sender, EventArgs e)
        {
            // Create definitions for each statistic to calculate
            StatisticDefinition statDefinitionAvgPop    = new StatisticDefinition("POP", StatisticType.Average, "");
            StatisticDefinition statDefinitionMinPop    = new StatisticDefinition("POP", StatisticType.Minimum, "");
            StatisticDefinition statDefinitionMaxPop    = new StatisticDefinition("POP", StatisticType.Maximum, "");
            StatisticDefinition statDefinitionSumPop    = new StatisticDefinition("POP", StatisticType.Sum, "");
            StatisticDefinition statDefinitionStdDevPop = new StatisticDefinition("POP", StatisticType.StandardDeviation, "");
            StatisticDefinition statDefinitionVarPop    = new StatisticDefinition("POP", StatisticType.Variance, "");

            // Create a definition for count that includes an alias for the output
            StatisticDefinition statDefinitionCount = new StatisticDefinition("POP", StatisticType.Count, "CityCount");

            // Add the statistics definitions to a list
            List <StatisticDefinition> statDefinitions = new List <StatisticDefinition>
            {
                statDefinitionAvgPop,
                statDefinitionCount,
                statDefinitionMinPop,
                statDefinitionMaxPop,
                statDefinitionSumPop,
                statDefinitionStdDevPop,
                statDefinitionVarPop
            };

            // Create the statistics query parameters, pass in the list of definitions
            StatisticsQueryParameters statQueryParams = new StatisticsQueryParameters(statDefinitions);

            // If only using features in the current extent, set up the spatial filter for the statistics query parameters
            if (OnlyInExtentSwitch.IsToggled)
            {
                // Get the current extent (envelope) from the map view
                Envelope currentExtent = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry as Envelope;

                // Set the statistics query parameters geometry with the envelope
                statQueryParams.Geometry = currentExtent;

                // Set the spatial relationship to Intersects (which is the default)
                statQueryParams.SpatialRelationship = SpatialRelationship.Intersects;
            }

            // If only evaluating the largest cities (over 5 million in population), set up an attribute filter
            if (OnlyBigCitiesSwitch.IsToggled)
            {
                // Set a where clause to get the largest cities (could also use "POP_CLASS = '5,000,000 and greater'")
                statQueryParams.WhereClause = "POP_RANK = 1";
            }

            try
            {
                // Execute the statistical query with these parameters and await the results
                StatisticsQueryResult statQueryResult = await _worldCitiesTable.QueryStatisticsAsync(statQueryParams);

                // Display results in the list box
                StatResultsList.ItemsSource = statQueryResult.First().Statistics.Select(m => $"{m.Key}:{m.Value}").ToList();
                ResultsGrid.IsVisible       = true;
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
            }
        }
Exemplo n.º 17
0
        private async void QueryStatistics(bool onlyInExtent, bool onlyLargePop)
        {
            // Create definitions for each statistic to calculate.
            StatisticDefinition statDefinitionAvgPop    = new StatisticDefinition("POP", StatisticType.Average, "");
            StatisticDefinition statDefinitionMinPop    = new StatisticDefinition("POP", StatisticType.Minimum, "");
            StatisticDefinition statDefinitionMaxPop    = new StatisticDefinition("POP", StatisticType.Maximum, "");
            StatisticDefinition statDefinitionSumPop    = new StatisticDefinition("POP", StatisticType.Sum, "");
            StatisticDefinition statDefinitionStdDevPop = new StatisticDefinition("POP", StatisticType.StandardDeviation, "");
            StatisticDefinition statDefinitionVarPop    = new StatisticDefinition("POP", StatisticType.Variance, "");

            // Create a definition for count that includes an alias for the output.
            StatisticDefinition statDefinitionCount = new StatisticDefinition("POP", StatisticType.Count, "CityCount");

            // Add the statistics definitions to a list.
            List <StatisticDefinition> statDefinitions = new List <StatisticDefinition>
            {
                statDefinitionAvgPop,
                statDefinitionCount,
                statDefinitionMinPop,
                statDefinitionMaxPop,
                statDefinitionSumPop,
                statDefinitionStdDevPop,
                statDefinitionVarPop
            };

            // Create the statistics query parameters, pass in the list of definitions.
            StatisticsQueryParameters statQueryParams = new StatisticsQueryParameters(statDefinitions);

            // If only using features in the current extent, set up the spatial filter for the statistics query parameters.
            if (onlyInExtent)
            {
                // Get the current extent (envelope) from the map view.
                Envelope currentExtent = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry as Envelope;

                // Set the statistics query parameters geometry with the current extent.
                statQueryParams.Geometry = currentExtent;

                // Set the spatial relationship to Intersects (which is the default).
                statQueryParams.SpatialRelationship = SpatialRelationship.Intersects;
            }

            // If only evaluating the largest cities (over 5 million in population), set up an attribute filter.
            if (onlyLargePop)
            {
                // Set a where clause to get the largest cities (could also use "POP_CLASS = '5,000,000 and greater'").
                statQueryParams.WhereClause = "POP_RANK = 1";
            }

            try
            {
                // Execute the statistical query with these parameters and await the results.
                StatisticsQueryResult statQueryResult = await _worldCitiesTable.QueryStatisticsAsync(statQueryParams);

                // Get the first (only) StatisticRecord in the results.
                StatisticRecord record = statQueryResult.FirstOrDefault();

                // Make sure a record was returned.
                if (record == null || record.Statistics.Count == 0)
                {
                    ShowMessage("No result", "No results were returned.");
                    return;
                }

                // Display results.
                ShowStatsList(record.Statistics);
            }
            catch (ArcGISWebException exception)
            {
                ShowMessage("There was a problem running the query.", exception.ToString());
            }
        }