Search code examples
javascriptarcgis

zooming to selected features


I'm attempting to select a feature and have the map zoom to that selected feature using the ArcGIS javascript api.

I've checked to make sure that the query returns actual results so there should be data being retrieved. I'm basing the script on the Intro to FeatureLayer - 4.11. Code is below.

<script>
  require([
    "esri/Map",
    "esri/views/MapView",
    "esri/layers/FeatureLayer"
  ], function(Map, MapView, FeatureLayer) {
    var map = new Map({
      basemap: "hybrid"
    });

    var view = new MapView({
      container: "viewDiv",
      map: map,

      extent: {
        // autocasts as new Extent()
        xmin: -9177811,
        ymin: 4247000,
        xmax: -9176791,
        ymax: 4247784,
        spatialReference: 102100
      }
    });

    /********************
     * Add feature layer
     ********************/

    // Carbon storage of trees in Warren Wilson College.
    var featureLayer = new FeatureLayer({
      url:
        "http://someURL/FeatureServer/45"
    });

    map.add(featureLayer);

    const query = new Query();
    query.where = "LASTNAME = 'GLOVER'";
    query.outSpatialReference = { wkid: 102100 };
    query.returnGeometry = true;
    query.outFields = [ "LASTNAME" ];

    featureLayer.queryFeatures(query).then(function(results){
      var newextent = esri.graphicsExtent(results.features);
      map.setExtent(newextent,true);

    });

  });
</script>

I would have expected the map to zoom to the extent of the selected polygon, but it does not. No error messages appear - the map just displays with the original extent.

Hope someone can point me in the right direction.


Solution

  • Replace your line const query = new Query(); with const query = featureLayer.createQuery(); because you didn't declare Query in require, for example :

    require([
      "esri/Map",
      "esri/views/MapView",
      "esri/layers/FeatureLayer",
      "esri/tasks/support/Query"
    ], function(Map, MapView, FeatureLayer, Query) {
    

    Since the version 4.* of ArcGIS Javascript API, you can create Queries from featureLayer : https://developers.arcgis.com/javascript/latest/api-reference/esri-layers-FeatureLayer.html#createQuery and you control the view with MapView https://developers.arcgis.com/javascript/latest/api-reference/esri-views-MapView.html#goTo :

    featureLayer.queryFeatures(query).then(function(results){
      const features = results.features;
      view.goTo(features[0].geometry);
    });