Select to view content in your preferred language

How to zoom to selected record on Data Grid result

4102
12
08-13-2010 12:11 PM
MayJeff
Deactivated User
Can someone show me how to zoom to selected record on data grid table instead of hightlighting the record only?  I am try to figure out using this example:
http://resources.esri.com/help//9.3/arcgisserver/apis/flex/samples/index.html?sample=QueryTask_ZoomI...

Thank you.
Tags (2)
0 Kudos
12 Replies
KenBuja
MVP Esteemed Contributor
Here's the code I use, where the function is the click method of the Datagrid. If you're selecting a point, you'll have to alter the extent so it's not dimensionless.

private function sfDataGrid_Click():void
{
    var obj:Object = sfDatagrid.selectedItem;
    if (obj != null)
    {
        var polyExtent:Extent = new Extent(obj["XMIN"],obj["YMIN"],obj["XMAX"],obj["YMAX"]);
        
        lastIdentifyResultGraphic = null;

// this section will highlight the feature selected        
        sfQuery.where = "Name = '" + obj["Name"] + "'"
        sfPolygonQueryTask.execute(sfQuery, new AsyncResponder(onResult, onFault));
        
        function onResult(featureSet:FeatureSet, token:Object = null):void
        {
            lastIdentifyResultGraphic = featureSet.features[0];
            lastIdentifyResultGraphic.symbol = sfsOutline;    
        }

        function onFault(info:Object, token:Object = null):void
        {
            Alert.show(info.toString(), "Query Problem");
        }        
        
        MainMap.extent = polyExtent;
        if (!MainMap.extent.containsExtent(polyExtent)) MainMap.level--;
    }
}
0 Kudos
MayJeff
Deactivated User
I got error messages when added the code you mentioned about.  Please see the message below and show me how to change the code in order to zoom to selected record on datagrid table.

Thank you.

TypeError: Error #1034: Type Coercion failed: cannot convert com.esri.ags::Graphic@5c8a0b1 to com.esri.ags.layers.GraphicsLayer.
at testing/private:sfDataGrid_Click/onResult()
at mx.rpc::AsyncResponder/result()
at com.esri.ags.tasks::QueryTask/handleDecodedObject()
at Function/http://adobe.com/AS3/2006/builtin::call()
at com.esri.ags.tasks::BaseTask/handleResult()
at <anonymous>()
at mx.rpc::Responder/result()
at mx.rpc::AsyncToken/http://www.adobe.com/2006/flex/mx/internal::applyResult()
at mx.rpc.events::ResultEvent/http://www.adobe.com/2006/flex/mx/internal::callTokenResponders()
at HTTPOperation/http://www.adobe.com/2006/flex/mx/internal::dispatchRpcEvent()
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::resultHandler()
at mx.rpc::Responder/result()
at mx.rpc::AsyncRequest/acknowledge()
at DirectHTTPMessageResponder/completeHandler()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()


<?xml version="1.0" encoding="utf-8"?>
<mx:Application
    xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:esri="http://www.esri.com/2008/ags"
    pageTitle="Query, then zoom to results"
    styleName="plain">

    <mx:Script>
        <![CDATA[
            import com.esri.ags.Graphic;
            import com.esri.ags.geometry.Polygon;
            import com.esri.ags.tasks.FeatureSet;
            import mx.controls.Alert;
            import mx.rpc.AsyncResponder;

            private function doQuery():void
            {
                queryTask.execute(query, new AsyncResponder(onResult, onFault));
                function onResult(featureSet:FeatureSet, token:Object = null):void
                {
                    // clear the graphics layer
                    myGraphicsLayer.clear();

                    if (featureSet.features.length == 0)
                    {
                        Alert.show("No States found. Please try again.");
                    }
                    else
                    {
                        var unionExtent:Extent;
                        var myFirstGraphic:Graphic = featureSet.features[0];
                        unionExtent = Polygon(myFirstGraphic.geometry).extent;

                        for each (var myGraphic1:Graphic in featureSet.features)
                        {
                            myGraphicsLayer.add(myGraphic1);
                            unionExtent = unionExtent.union(Polygon(myGraphic1.geometry).extent);
                        }

                        MainMap.extent = unionExtent;
                    }
                }
                function onFault(info:Object, token:Object = null):void
                {
                    Alert.show(info.toString());
                }
            }
           
            private function sfDataGrid_Click():void
   {
       var obj:Object = sfDatagrid.selectedItem;
       if (obj != null)
       {
           var polyExtent:Extent = new Extent(obj["XMIN"],obj["YMIN"],obj["XMAX"],obj["YMAX"]);
          
            myGraphicsLayer = null;
  
   // this section will highlight the feature selected       
           query.where = "STATE_NAME = '" + obj["STATE_NAME"] + "'"
           queryTask.execute(query, new AsyncResponder(onResult, onFault));
          
           function onResult(featureSet:FeatureSet, token:Object = null):void
           {
                myGraphicsLayer = featureSet.features[0];
                myGraphicsLayer.symbol = sfs;   
           }
  
           function onFault(info:Object, token:Object = null):void
           {
               Alert.show(info.toString(), "Query Problem");
           }       
          
           MainMap.extent = polyExtent;
           if (!MainMap.extent.containsExtent(polyExtent)) MainMap.level--;
       }
   }

           
        ]]>
    </mx:Script>

    <!-- Start Declarations -->
        <!-- Symbol for Query Result as Polygon -->
        <esri:SimpleFillSymbol id="sfs" alpha="0.7" color="0xFF0000"/>
   
        <!-- Layer with US States -->
        <esri:QueryTask id="queryTask"
            url="http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5"/>
   
        <esri:Query id="query" text="{fText.text}" returnGeometry="true" outSpatialReference="{MainMap.spatialReference}">
            <esri:outFields>
                <mx:String>MED_AGE</mx:String>
                <mx:String>POP2007</mx:String>
            </esri:outFields>
        </esri:Query>
    <!-- End Declarations -->

    <mx:HBox width="100%" height="40" backgroundColor="0xDDDDFF" paddingTop="10" horizontalAlign="center">
        <mx:Text text="Search for U.S. States:"/>
        <mx:TextInput id="fText" enter="doQuery()" text="Ca"/>
        <mx:Button label="Query" click="doQuery()"/>
    </mx:HBox>
    <mx:Text id="resultSummary" height="15"/>
    <mx:VDividedBox height="100%" width="100%">
        <esri:Map id="MainMap">
            <esri:extent>
                <esri:Extent xmin="-126" ymin="24" xmax="-67" ymax="50">
                    <esri:SpatialReference wkid="4326"/>
                </esri:Extent>
            </esri:extent>
            <esri:ArcGISDynamicMapServiceLayer
                url="http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer"/>
            <esri:GraphicsLayer id="myGraphicsLayer" symbol="{sfs}"/>
        </esri:Map>
        <mx:DataGrid id="sfDatagrid"
         click="sfDataGrid_Click()"
            dataProvider="{queryTask.executeLastResult.attributes}"
            scroll="true" width="100%" height="40%"/>
    </mx:VDividedBox>
</mx:Application>
0 Kudos
KenBuja
MVP Esteemed Contributor
This will work instead

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
    xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:esri="http://www.esri.com/2008/ags"
    pageTitle="Query, then zoom to results"
    styleName="plain">

    <mx:Script>
        <![CDATA[
            import com.esri.ags.geometry.Extent;
            import com.esri.ags.Graphic;
            import com.esri.ags.geometry.Polygon;
            import com.esri.ags.tasks.FeatureSet;
            import mx.controls.Alert;
            import mx.rpc.AsyncResponder;

            [Bindable] private var lastIdentifyResultGraphic:Graphic;

            private function doQuery():void
            {
                query.text = fText.text
                query.where = ""
                queryTask.execute(query, new AsyncResponder(onResult, onFault));
                function onResult(featureSet:FeatureSet, token:Object = null):void
                {
                    // clear the graphics layer
                    myGraphicsLayer.clear();

                    if (featureSet.features.length == 0)
                    {
                        Alert.show("No States found. Please try again.");
                    }
                    else
                    {
                        var unionExtent:Extent;
                        var myFirstGraphic:Graphic = featureSet.features[0];
                        unionExtent = Polygon(myFirstGraphic.geometry).extent;

                        for each (var myGraphic1:Graphic in featureSet.features)
                        {
                            myGraphicsLayer.add(myGraphic1);
                            unionExtent = unionExtent.union(Polygon(myGraphic1.geometry).extent);
                        }

                        MainMap.extent = unionExtent;
                    }
                }
                function onFault(info:Object, token:Object = null):void
                {
                    Alert.show(info.toString());
                }
            }
            
            private function sfDataGrid_Click():void
            {
                var obj:Object = sfDataGrid.selectedItem;
                if (obj != null)
                {
                    lastIdentifyResultGraphic = null;
                    
                    query.where = "STATE_NAME = '" + obj["STATE_NAME"] + "'"
                    queryTaskZoom.execute(query, new AsyncResponder(onResult, onFault));
                    function onResult(featureSet:FeatureSet, token:Object = null):void
                    {
                        lastIdentifyResultGraphic = featureSet.features[0];
                        lastIdentifyResultGraphic.symbol = sfs;
                        MainMap.extent = new Extent(lastIdentifyResultGraphic.geometry.extent.xmin,lastIdentifyResultGraphic.geometry.extent.ymin,lastIdentifyResultGraphic.geometry.extent.xmax,lastIdentifyResultGraphic.geometry.extent.ymax);
                    }
                    function onFault(info:Object, token:Object = null):void
                    {
                        Alert.show(info.toString(), "Query Problem");
                    }
                }
            }
        ]]>
    </mx:Script>

    <!-- Start Declarations -->
        <!-- Symbol for Query Result as Polygon -->
        <esri:SimpleFillSymbol id="sfs" alpha="0.7" color="0xFF0000"/>
    
        <!-- Layer with US States -->
        <esri:QueryTask id="queryTask"
            url="http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5"/>
        <esri:QueryTask id="queryTaskZoom"
            url="http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5"/>

    
        <esri:Query id="query" text="{fText.text}" returnGeometry="true" outSpatialReference="{MainMap.spatialReference}">
            <esri:outFields>
                <mx:String>MED_AGE</mx:String>
                <mx:String>POP2007</mx:String>
            </esri:outFields>
        </esri:Query>
    <!-- End Declarations -->

    <mx:HBox width="100%" height="40" backgroundColor="0xDDDDFF" paddingTop="10" horizontalAlign="center">
        <mx:Text text="Search for U.S. States:"/>
        <mx:TextInput id="fText" enter="doQuery()" text="Ca"/>
        <mx:Button label="Query" click="doQuery()"/>
    </mx:HBox>
    <mx:Text id="resultSummary" height="15"/>
    <mx:VDividedBox height="100%" width="100%">
        <esri:Map id="MainMap">
            <esri:extent>
                <esri:Extent xmin="-126" ymin="24" xmax="-67" ymax="50">
                    <esri:SpatialReference wkid="4326"/>
                </esri:Extent>
            </esri:extent>
            <esri:ArcGISDynamicMapServiceLayer
                url="http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer"/>
            <esri:GraphicsLayer id="myGraphicsLayer" symbol="{sfs}" graphicProvider="{lastIdentifyResultGraphic}"/>
        </esri:Map>
        <mx:DataGrid id="sfDataGrid" click="sfDataGrid_Click()"
            dataProvider="{queryTask.executeLastResult.attributes}"
            scroll="true" width="100%" height="40%"/>
    </mx:VDividedBox>
</mx:Application>
0 Kudos
MayJeff
Deactivated User
Thank you very much.  It works 🙂
0 Kudos
varnavarna
Emerging Contributor
Hello,

Thank you for this solution of the problem with zoom in the DataGrid. I was searching for a solution for a long time.

Аlthough I have a question. The query, that I use the code in, is searching for names of people owning some property. There are many names that have more than one property. And if, lets say, a person has 3 parcels on the map and they show up on the map and DataGrid, when I click on the first parcel it zooms to one of three. If I click on the second one it zooms on the same one again, same with the third and so on. In other words - it finds multiple parcels but it zooms only on one of them. Do you know a way to work around this problem?

Thank you
0 Kudos
DanJensen
Deactivated User
This code assumes the user has already selected multiple features (thus highlighting them on the map by adding them to the maps graphic layer) and has clicked a specific feature in the datagrid.  All features remain highlighted, but the one highlighted in the data grid has an alternate and obviously different highlight symbol. 

In this code map1 is my <esri:Map>.  The code is triggered on the itemClick event of the datagrid rather than the click event, which allows you to use the ListEvent data type for the event variable of the selectRow function.  This allows me to access the data in the row clicked through the itemRenderer property of the event.  I then compare these atttributes to the attributes of the graphics already added to the graphics layer.  I zoom to the extent of the graphic whose attributes match the selected row as well as change the symbol.

-Dan

private function selectRow(event:ListEvent):void
   {
    var selectedGraphic:Graphic;
        var attr:Object = event.itemRenderer.data;
        var i:int=0;
        
 for each (var graphic:Graphic in graphicsLayer.graphicProvider)
        { 
         graphic.symbol=symbol1;
             i++;
             if (graphic.attributes == attr){
              selectedGraphic=graphic;
              selectedGraphic.symbol=selSymbol;
              graphicsLayer.moveToTop(selectedGraphic);
              zoomToRow(selectedGraphic);
             }
        }
   }

private function zoomToRow(graphic:Graphic):void            
   {                
    var offset:int=3000;
        var graphicsExtent:Extent;
        if (graphic){
         graphicsExtent = graphic.geometry.extent;
             graphicsExtent.xmax=graphicsExtent.xmax+offset;
             graphicsExtent.xmin=graphicsExtent.xmin-offset;
             graphicsExtent.ymax=graphicsExtent.ymax+offset;
             graphicsExtent.ymin=graphicsExtent.ymin-offset;
             map1.extent = graphicsExtent;
             
  // make sure the whole extent is visible
  if (!map1.extent.containsExtent(graphicsExtent)){
   map1.level--;
  }         
 }
   }
0 Kudos
varnavarna
Emerging Contributor
This addition worked perfectly, thank you very much! It now zooms to the correct parcels.

I wanted to ask - what the two additional symbols "selSymbol" and "symbol1" do? Because I used different colors to describe them but didn't see them to show up somewhere in the working application. I am relatevly new to Flex and stil figuring out most of the stuff

Best Regards

Deyan
0 Kudos
DanJensen
Deactivated User
I am new too and not sure why the different colors did not show up in your working application.  It sounds like you defined them in the declarations section of your code.  If so, assigning these symbols to the selected parcels should work.  Here is how I defined my symbols in the declarations section.

<esri:SimpleFillSymbol id="symbol1"
 style="solid"
 color="0xFF0000"
 alpha="0.3">

   <esri:outline>
 <esri:SimpleLineSymbol style="solid" color="0x000000" width="2" />
   </esri:outline>
</esri:SimpleFillSymbol>
  

<esri:SimpleFillSymbol id="selSymbol"
 style="solid"
 color="0x22BB99"
 alpha="1">
</esri:SimpleFillSymbol>


-Dan
0 Kudos
varnavarna
Emerging Contributor
Yes, they are assigned exactly like that ( only different colors :). This is not a problem, one color is even better. I was just interested what's the idea of the additional symbols.

Best Regards
0 Kudos