Quick Tip - fromJSON() in ArcGIS JS API

Quick Tip - fromJSON() in ArcGIS JS API

Rene Rubalcava | August 9, 2015

I just wanted to give you a quick tip on a new little feature in the ArcGIS API for JavaScript 4.beta1 that may have gone unnoticed if you haven't gotten too deep into the beta.

That would be the fromJSON method that you'll find sprinkled throughout the API. Any modules that has a fromJSON method can simply take a JSON representation of that module and create a new one. This isn't exactly the same as constructor, but it is a bit of a shortcut to work into your development. Now, are some jsonUtils in the 3.xx API, like for geometry or renderers. But now they are part of the actual modules.

Let's look over the samples real quick. If you look at the 2D Overview sample, you may notice in that viewPoint is simply passed as an object to the SceneView.

view3d = new SceneView({
  container: "view3dDiv",
  map: map3d,
  viewpoint: {
    center: [7, 46],
    scale: 200000,
    heading: 35,
    tilt: 60

Although, ViewPoint is a module. In this particular case it is taking advantage Accessors, where the viewpoint behavior is defined via the Accessor. But this is part of a larger effort to simplify the API for developers.

The examples also show how a Camera uses a fromJSON method to create the Camera. This even works on symbols.

Easy GeoJSON parsing

So maybe you've used something like Terraformer to parse and display GeoJSON data in your ArcGIS JS apps. What would you say if I told you you can do this directly in the ArcGIS 4.0beta1? (Watch your language). This isn't some complicated process, nor do I need to worry about using webMercatorUtils. I just need to create the Graphic. Why? Because if we look at the Point geometry, you may notice that it has properties for latitude, longitude, x, y and has a note: "The blah blah of the point if the spatial reference is Web Mercator (wkid: 3857) or WGS-84 (wkid: 4326)." This means you can just pass the GeoJSON properties in the correct format directly to the Graphic.

That would look something like this.

  geometry: {
    x: coordinates[0],
    y: coordinates[1],
    spatialReference: { wkid: 4326 }
  symbol: markerSymbol,
  attributes: x.properties

Look at that. Look at it! No fuss, GeoJSON in your ArcGIS API apps.

You can see a demo of this application here. Basic 3D map - 4.0 beta 1 on jsbin.com

The fromJSON method sprinkled throughout the API provide even more flexibility to you as a developer to simplify it's use for your everyday work. So JSON the hell out of your code!