Set initial extent of map with FeatureLayer

3031
2
Jump to solution
04-14-2016 06:39 AM
RobertoOliveira
New Contributor III

Trying to set the initial extent of map with same extent of a existing Feature Layer.

Code:

var featureLayer = new FeatureLayer("http://server/arcgis/rest/services/MyService/0", {

  mode: FeatureLayer.MODE_ONDEMAND,

  outFields: ["*"]

});

featureLayer.on("load", function(e) {

  var initialExtent = featureLayer.fullExtent;

  map = new Map('map-view', {

    basemap: "streets",

    extent: initialExtent

  });

}

This don't work, and I have the following error on console:

Map: Geometry (wkid: 31982) cannot be converted to spatial reference of the map (wkid: 102100)

The Feature Layer was using the Spatial Reference wkid 31982.

Why the map have the Spatial Reference wkid 102100?

This is the only feature layer existing on code, and I "loaded" the Feature Layer before initialize the map, so, until I initialize the map, map = null

What I need to do for the map start up with the same extent of the feature layer?

0 Kudos
1 Solution

Accepted Solutions
KenBuja
MVP Honored Contributor

You can use a GeometryService to project the extent of your service into the Web Mercator projection of the map.

View solution in original post

2 Replies
KenBuja
MVP Honored Contributor

You can use a GeometryService to project the extent of your service into the Web Mercator projection of the map.

View solution in original post

RobertoOliveira
New Contributor III

Thanks Ken Buja

I have made the following code if anybody need (can be optimized):

// Geometry Service

var gs = new GeometryService("https://server/arcgis/rest/services/Utilities/Geometry/GeometryServer");

// wkid of map and feature layer

var map_wkid = map.extent.spatialReference.wkid;

var feature_wkid = featureLayer.fullExtent.spatialReference.wkid;

// if wkid of map and feature layer is different, project

if (map_wkid != feature_wkid) {

  // get the map spatialReference

  var sr = new SpatialReference(map_wkid);

  // project

  var project = gs.project([featureLayer.fullExtent], sr);

  // anonymous functions (success and error)

  // success

  project.then(function(result) {

    // if a map exist, destroy first

    if (map) {

      map.destroy();

      // create a new map with extent of feature layer

      map = new Map("map-view", {

        extent: result[0],

        basemap: "topo",

      });

    

      // add the feature layer

      map.addLayers([featureLayer]);

    }

  // error

  }, function(err) {

    console.log('error');

    console.log(err);

  });

}