[GIS] ArcGIS JS Api: Getting information by location from multiple layers

arcgis-10.1arcgis-javascript-api

I have two layers published in my ArcGIS Server 10.1 server. One is a polygon layer representing the World map by country and the other is a point layer depicting cities.

Please, note that cities layer does NOT contain the information of the country they belong to, it is contained in the other world countries layer.

What I would like to do is creating a sample interface written in ESRI Javascript API to display those Feature Layers, so the user can click on a point representing a city and it appears a popup (or another widget) with the two features associated to this city: name of the city AND name of the country the city belongs to. But, if the user clicks on an area with no cities, only the name of the country should be displayed.

I know that it is a quite basic example, but I am not sure on how to tackle this problem: I see examples on retrieving information from a unique layer, but not about how to distinguish between information required from different layers and integrate it all together in a single widget.

EDIT: Of course, the problem is not building the JS interface but how to retrieve and integrate the information coming from different layers just having the coordinates where the user clicked.

Please, can anyone provide some information/concepts/ideas/links to tutorials about that?

Thanks for your help!

Best Answer

When using the Javascript api, a good way to pull off what you're asking is to query the cities layer, and in the callback for the cities query, query the countries layer using the same geometry. To do that, you'll either need to store the clicked geometry and the results, or nest the queries. Here's an example of the nested query:

dojo.connect(map, "onClick", function (evt) {
  var cityQuery = new esri.tasks.QueryTask("http://mymaps.com/arcgis/rest/services/world/MapService/0");
  var cityParams = new esri.tasks.Query();

  //...set parameters
  cityParams.geometry = evt.mapPoint;

  cityQuery.execute(cityParams, function (cityResults) {
     // function runs when browser receives query results from city layer.

     var countryQuery = esri.tasks.QueryTask("http://mymaps.com/arcgis/rest/services/world/MapService/1");
     var countryParams = new esri.tasks.Query();

     // ... set country query parameters
     countryParams.geometry = evt.mapPoint; //from the previous click

     countryQuery.execute(countryParams, function (countryResults) {

       // this function runs when browser receives query results from country layer
       var allAttributes = {};

       if (cityResults.features.length > 0) {
         // add city results if there are any
       }

       if (countryResults.features.length > 0) {
         // add country results if there are any
       }

       // show results here
     });
   });
 });