Convert collection of graphics in graphic layer to JSON format

335
3
Jump to solution
02-09-2023 03:16 AM
Aeseir
by
Occasional Contributor

As per subject i have a graphics layer that contains set of graphics.

I want to be able to convert this collection of graphics to JSON format for local storage, with intent of recreating it later.

 

Anyone have advice with this?

0 Kudos
1 Solution

Accepted Solutions
UndralBatsukh
Esri Regular Contributor

HI there, 

You can use Graphic.toJSON() and Graphic.fromJSON() methods to achieve what you are describing. 

You can call GraphicsLayerView.queryGraphics() method to get all graphics in the GraphicsLayer then get the json graphics. 

This simple codepen shows how to get an array of Graphic json objects by calling Graphic.toJSON() then how to add the json graphic objects to the GraphicsLayer by calling Graphic.fromJSON: https://codepen.io/U_B_U/pen/rNrEyqg?editors=100

 

View solution in original post

0 Kudos
3 Replies
nevvo
by
New Contributor II

I've been trying to do the very same thing and found that when using the stringify method on the graphics the type was being lost so I had to recreate a new object and save that out so that it would then be able to be drawn again later.

I could well be missing some simple OOB method, so maybe someone else will have a better answer but this works for me:

 

 

const result = [];

this.graphicsLayer.graphics.forEach((item) => {
    // for some reason the stringify method on the graphic drops off the type of geometry (polygon, polyline etc.)
    // from the object so when we try to use the saved value to  draw it, it fails as the type isn't there.
    // so here we take the geometry of the item and them parse it into a new object, add the missing property
    // and pass that to the stringify method so that we have all of the expected properties at the other end.
    var geometry = JSON.parse(JSON.stringify(item.geometry));
    geometry.type = item.geometry.type;

    // add the newly constructed geometry to the result
    result.push(JSON.stringify(geometry));
});

return JSON.stringify(result);

 

This only applies to the geometry as that was all I was interested in keeping but similar should work if you need the other propeties.

Cheers

0 Kudos
UndralBatsukh
Esri Regular Contributor

HI there, 

You can use Graphic.toJSON() and Graphic.fromJSON() methods to achieve what you are describing. 

You can call GraphicsLayerView.queryGraphics() method to get all graphics in the GraphicsLayer then get the json graphics. 

This simple codepen shows how to get an array of Graphic json objects by calling Graphic.toJSON() then how to add the json graphic objects to the GraphicsLayer by calling Graphic.fromJSON: https://codepen.io/U_B_U/pen/rNrEyqg?editors=100

 

0 Kudos
Aeseir
by
Occasional Contributor

This is great, additionally is there any way to apply this to MapNotesLayer considering its a collection of graphics layers?

0 Kudos