Skip To Content

Query for statistics (advanced)

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:esri="http://www.esri.com/2008/ags"
               pageTitle="Example - Query For Statistics Advanced">
    <!--
    Description:
    This sample demonstrates new capabilities at ArcGIS 10.1 for calculating statistics on the server.
    The sample is displaying statistics by U.S. Census blockgroup, the server is calculating a summation on
    the population 2000 field, and also calculating a count on the number of households field.

    Note:
    When your layer/table in a service reports in the Services Directory that "supportsStatistics" is true,
    you will be able to use the following classes and parameters to have the server generate statistics.
    Note:
    Using a geometry filter when calculating statistics requires ArcGIS 10.1 SP1 or later.
    Also note that the statistics query does not return geometry, another query using the buffer geometry
    is used to return the block group points.

    Documentation:
    For more information, see the API documentation.
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/FeatureSet.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/Graphic.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/events/GeometryServiceEvent.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/events/LocatorEvent.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/events/QueryEvent.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/geometry/MapPoint.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/geometry/Polygon.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/tasks/GeometryService.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/tasks/Locator.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/tasks/QueryTask.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/tasks/supportClasses/AddressCandidate.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/tasks/supportClasses/AddressToLocationsParameters.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/tasks/supportClasses/BufferParameters.html
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/tasks/supportClasses/Query.html#geometry
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/tasks/supportClasses/Query.html#outStatistics
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/tasks/supportClasses/Query.html#groupByFieldsForStatistics
    https://developers.arcgis.com/en/flex/api-reference/com/esri/ags/tasks/supportClasses/StatisticDefinition.html

    http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/formatters/NumberFormatter.html

    ArcGIS REST API documentation:
    http://resources.arcgis.com/en/help/rest/apiref/query.html
    -->

    <s:states>
        <s:State name="default"/>
        <s:State name="searchProcessing"/>
    </s:states>

    <fx:Script>
        <![CDATA[
            import com.esri.ags.FeatureSet;
            import com.esri.ags.Graphic;
            import com.esri.ags.events.GeometryServiceEvent;
            import com.esri.ags.events.LocatorEvent;
            import com.esri.ags.events.QueryEvent;
            import com.esri.ags.geometry.MapPoint;
            import com.esri.ags.geometry.Polygon;
            import com.esri.ags.tasks.supportClasses.AddressCandidate;
            import com.esri.ags.tasks.supportClasses.AddressToLocationsParameters;
            import com.esri.ags.tasks.supportClasses.BufferParameters;
            import com.esri.ags.tasks.supportClasses.Query;
            import com.esri.ags.tasks.supportClasses.StatisticDefinition;

            import mx.collections.ArrayCollection;
            import mx.controls.Alert;
            import mx.rpc.events.FaultEvent;

            private var bufferParameters:BufferParameters = new BufferParameters();
            private var distance:Number = 2.5;
            private var unit:Number = GeometryService.UNIT_STATUTE_MILE;

            private var statisticalQuery:Query = new Query();
            private var query:Query = new Query();

            protected function searchTextInput_searchHandler():void
            {
                if (searchTextInput.text.length > 2)
                {
                    map.defaultGraphicsLayer.clear();
                    bufferGraphicsLayer.clear();
                    bufferResultsGraphicsLayer.clear();
                    var params:AddressToLocationsParameters = new AddressToLocationsParameters();
                    var place:Object = { SingleLine: searchTextInput.text };
                    params.address = place;
                    params.outFields = [ 'Loc_name' ];
                    worldGeocodeLocator.addressToLocations(params);
                    currentState = 'searchProcessing';
                }
            }

            protected function placesLocator_addressToLocationsCompleteHandler(event:LocatorEvent):void
            {
                var placesResults:Array = event.addressCandidates as Array;
                if (placesResults[0])
                {
                    map.defaultGraphicsLayer.clear();
                    var placeCandidate:AddressCandidate = placesResults[0] as AddressCandidate;
                    var mapPoint:MapPoint = placeCandidate.location as MapPoint;
                    var graphic:Graphic = new Graphic(mapPoint, sms);
                    graphic.toolTip = placeCandidate.address as String;
                    map.defaultGraphicsLayer.add(graphic);
                    map.level = 12;
                    map.centerAt(mapPoint);
                    currentState = 'default';

                    bufferParameters.geometries = [ mapPoint ];
                    bufferParameters.distances = [ distance ];
                    bufferParameters.unit = unit;
                    bufferParameters.outSpatialReference = map.spatialReference;
                    geometryService.buffer(bufferParameters);
                }
                else
                {
                    Alert.show("Unable to locate address", "Search Results");
                    currentState = 'default';
                }
            }

            protected function geometryService_bufferCompleteHandler(event:GeometryServiceEvent):void
            {
                var bufferResultsArray:Array = event.result as Array;
                if (bufferResultsArray[0])
                {
                    var bufferPolygon:Polygon = bufferResultsArray[0] as Polygon;
                    map.zoomTo(bufferPolygon);
                    var bufferGraphic:Graphic = new Graphic(bufferPolygon, bufferSymbol);
                    bufferGraphicsLayer.add(bufferGraphic);

                    var statsDef1:StatisticDefinition = new StatisticDefinition();
                    statsDef1.onStatisticField = "POP2000";
                    statsDef1.outStatisticFieldName = "POP_SUM";
                    statsDef1.statisticType = StatisticDefinition.TYPE_SUMMATION;

                    var statsDef2:StatisticDefinition = new StatisticDefinition();
                    statsDef2.onStatisticField = "HOUSEHOLDS";
                    statsDef2.outStatisticFieldName = "HOUSEHOLDS_COUNT";
                    statsDef2.statisticType = StatisticDefinition.TYPE_COUNT;

                    statisticalQuery.geometry = bufferPolygon;
                    statisticalQuery.groupByFieldsForStatistics = [ "TRACT" ];
                    statisticalQuery.outStatistics = [ statsDef1, statsDef2 ];

                    query.geometry = bufferPolygon;
                    query.outSpatialReference = map.spatialReference;
                    query.returnGeometry = true;

                    queryTask.execute(query);
                    statsQueryTask.execute(statisticalQuery);
                }
            }

            protected function esriService_faultHandler(event:FaultEvent):void
            {
                Alert.show("Error: " + event.fault.faultString, "Error code: " + event.fault.faultCode);
                currentState = 'default';
            }

            protected function queryTask_executeCompleteHandler(event:QueryEvent):void
            {
                var featureSet:FeatureSet = event.featureSet;
                if (featureSet)
                {
                    var featuresArray:Array = featureSet.features;
                    for (var i:int = 0; i < featuresArray.length; i++)
                    {
                        bufferResultsGraphicsLayer.add(featuresArray[i]);
                    }
                }
            }

            protected function statsQueryTask_executeCompleteHandler(event:QueryEvent):void
            {
                if (event.featureSet)
                {
                    var attributes:Array = event.featureSet.attributes;
                    dg.dataProvider = new ArrayCollection(attributes);
                    dg.visible = true;
                }
            }

            protected function esri_faultHandler(event:FaultEvent):void
            {
                Alert.show("Error: " + event.fault.faultString, "Error code: " + event.fault.faultCode);
            }

            protected function sumLabelFunction(item:Object, column:GridColumn):String
            {
                return numberFormatter.format(item["POP_SUM"]);
            }
        ]]>
    </fx:Script>

    <fx:Declarations>
        <esri:Locator id="worldGeocodeLocator"
                      addressToLocationsComplete="placesLocator_addressToLocationsCompleteHandler(event)"
                      fault="esriService_faultHandler(event)"
                      outSpatialReference="{map.spatialReference}"
                      url="http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"/>

        <esri:GeometryService id="geometryService"
                              bufferComplete="geometryService_bufferCompleteHandler(event)"
                              fault="esri_faultHandler(event)"
                              showBusyCursor="true"
                              url="http://sampleserver6.arcgisonline.com/arcgis/rest/services/Utilities/Geometry/GeometryServer"/>

        <esri:QueryTask id="queryTask"
                        executeComplete="queryTask_executeCompleteHandler(event)"
                        fault="esri_faultHandler(event)"
                        url="http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/0"/>

        <esri:QueryTask id="statsQueryTask"
                        executeComplete="statsQueryTask_executeCompleteHandler(event)"
                        fault="esri_faultHandler(event)"
                        url="http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/0"
                        useAMF="false"/>

        <!-- Initial Extent -->
        <esri:Extent id="startExtent"
                     xmin="-13945651" ymin="3066859" xmax="-7390412" ymax="6501022">
            <esri:SpatialReference wkid="102100"/>
        </esri:Extent>
        <!-- Symbols -->
        <esri:SimpleLineSymbol id="sfsOutline"
                               width="2"
                               color="0x1C272C"/>

        <esri:SimpleMarkerSymbol id="sms"
                                 alpha="0.7"
                                 color="0xD3D1D1"
                                 size="10"
                                 style="circle">
            <esri:SimpleLineSymbol width="2" color="0xBA0022"/>
        </esri:SimpleMarkerSymbol>

        <esri:SimpleFillSymbol id="bufferSymbol"
                               alpha="0.4"
                               color="0xFFFF66"
                               style="solid">
            <esri:SimpleLineSymbol width="2" color="0xE0CB44"/>
        </esri:SimpleFillSymbol>

        <esri:SimpleMarkerSymbol id="bufferResultsSymbol"
                                 alpha="0.4"
                                 color="0xFF0000"
                                 outline="{sfsOutline}"
                                 size="4"
                                 style="circle"/>

        <s:NumberFormatter id="numberFormatter" trailingZeros="false"/>
    </fx:Declarations>

    <s:controlBarLayout>
        <s:VerticalLayout gap="10"
                          paddingBottom="7"
                          paddingLeft="10"
                          paddingRight="10"
                          paddingTop="7"/>
    </s:controlBarLayout>
    <s:controlBarContent>
        <s:RichText width="100%">
            This sample demonstrates new capabilities at ArcGIS 10.1 for calculating statistics on the server.
            The sample is displaying statistics by U.S. Census blockgroup, the server is calculating a summation on
            the population 2000 field, and also calculating a count on the number of households field.
            Enter a U.S address to begin.
        </s:RichText>
        <s:Group id="searchGroup">
            <s:Rect width="100%" height="100%"
                    radiusX="10"
                    radiusY="10">
                <s:fill>
                    <s:SolidColor color="0xD3D1D1"/>
                </s:fill>
            </s:Rect>
            <s:Rect width="100%" height="100%"
                    left="2" right="2" top="2" bottom="2"
                    radiusX="10"
                    radiusY="10">
                <s:fill>
                    <s:SolidColor color="0xEEEEEE"/>
                </s:fill>
            </s:Rect>
            <s:HGroup width="385"
                      paddingBottom="4"
                      paddingLeft="10"
                      paddingRight="10"
                      paddingTop="4"
                      verticalAlign="baseline">

                <s:Label width="18%" text="Search"/>
                <s:TextInput id="searchTextInput"
                             width="64%"
                             borderAlpha="0.2"
                             click="{searchTextInput.selectAll()}"
                             enter="searchTextInput_searchHandler()"
                             prompt="Where do you want to go?"
                             text.searchProcessing="Search in progress...."/>
                <s:Button width="18%"
                          click="searchTextInput_searchHandler()"
                          cornerRadius="10"
                          label="Go"/>
            </s:HGroup>
        </s:Group>
    </s:controlBarContent>

    <esri:Map id="map" extent="{startExtent}">
        <esri:ArcGISTiledMapServiceLayer url="http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer"/>
        <esri:ArcGISDynamicMapServiceLayer id="demographicsLayer" url="http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer">
            <esri:visibleLayers>
                <s:ArrayList>
                    <!-- Only show the block group layer -->
                    <fx:Number>1</fx:Number>
                </s:ArrayList>
            </esri:visibleLayers>
            <esri:layerDrawingOptions>
                <esri:LayerDrawingOptions layerId="1" showLabels="true">
                    <esri:renderer>
                        <esri:SimpleRenderer>
                            <esri:SimpleFillSymbol alpha="0">
                                <esri:SimpleLineSymbol width="2"
                                                       alpha="0.7"
                                                       color="0x1C272C"/>
                            </esri:SimpleFillSymbol>
                        </esri:SimpleRenderer>
                    </esri:renderer>
                    <esri:labelClasses>
                        <esri:LabelClass id="myLabelClass1"
                                         labelExpression="[TRACT]"
                                         labelPlacement="esriServerPolygonPlacementAlwaysHorizontal">
                            <esri:LabelOptions alpha="1"
                                               backgroundAlpha="0"
                                               backgroundColor="0x000000"
                                               borderLineAlpha="0"
                                               borderLineColor="0x666666"
                                               borderLineSize="1"
                                               color="0x333333"
                                               fontDecoration="none"
                                               fontFamily="Arial"
                                               fontSize="12"
                                               fontStyle="normal"
                                               fontWeight="bold"
                                               haloAlpha="0.5"
                                               haloColor="0x999999"
                                               haloSize="1"
                                               horizontalAlignment="center"
                                               kerning="true"
                                               rightToLeft="false"
                                               verticalAlignment="baseline"
                                               xoffset="0"
                                               yoffset="0"/>
                        </esri:LabelClass>
                    </esri:labelClasses>
                </esri:LayerDrawingOptions>
            </esri:layerDrawingOptions>
        </esri:ArcGISDynamicMapServiceLayer>
        <esri:GraphicsLayer id="bufferResultsGraphicsLayer" symbol="{bufferResultsSymbol}"/>
        <esri:GraphicsLayer id="bufferGraphicsLayer"/>
    </esri:Map>
    <s:DataGrid id="dg"
                width="280"
                right="20" top="20"
                visible="false">
        <s:columns>
            <s:ArrayList>
                <s:GridColumn width="80"
                              dataField="TRACT"
                              headerText="Tract"/>
                <s:GridColumn width="80"
                              dataField="POP_SUM"
                              headerText="Population"
                              labelFunction="sumLabelFunction"/>
                <s:GridColumn dataField="HOUSEHOLDS_COUNT" headerText="Households"/>
            </s:ArrayList>
        </s:columns>
    </s:DataGrid>
</s:Application>