Having trouble creating a polygon from JSON in ESRI ArcGIS Javascript framework?

Can anyone assist with understanding the issue of trying to draw a polygon using the ESRI ArcGIS Javascript API? The image, JSON string, and code snippets provided below outline the code, console output, and expected behavior. Any help would be greatly appreciated!

Here is the JSON String:

{"geometry":{"rings":[[[-91.89013671874848,38.03029444608522],[-91.653930664061,38.00865683368494],[-91.64843749999851,38.00432854459864],[-91.5935058593735,37.93070854451552],[-91.577026367186,37.88303274722063],[-91.577026367186,37.79192956603227],[-91.631958007811,37.73982010276601],[-91.70886230468598,37.73547599031287],[-91.763793945311,37.76587942393493],[-91.85168457031098,37.85701474874939],[-91.88464355468598,37.9956711998967],[-91.89013671874848,38.03029444608522]]],"spatialReference":{"wkid":4326}},"symbol":{"color":[0,0,0,64],"outline":{"color":[0,0,0,255],"width":1,"type":"esriSLS","style":"esriSLSSolid"},"type":"esriSFS","style":"esriSFSSolid"}}

Below is the Code snippet used to add Shape to Map:

    function createFromJSON(JSONText){
      console.log("In Create Function");
      dojo.disconnect(handle);

      var jsontext = JSON.parse(JSONText);
      var polygon = new esri.geometry.Polygon(jsontext);
      console.log("Here is the polygon object:");
      console.log(polygon);
      console.log("Now drawing polygon");
       map.graphics.add(new Graphic(polygon, new SimpleFillSymbol()));
      console.log("Polygon should be there");
    }

https://i.stack.imgur.com/s3sK8.jpg

Answer №1

What you see in the JSON string displayed is specific to the Graphic object, not a representation of geometry. It includes both geometry and symbol. If you use it with Graphic, it will function properly.

map.graphics.add(new Graphic(jsontext));

If your goal is to extract just the polygon, consider writing your code like this:

var polygon = new esri.geometry.Polygon(jsontext.geometry);

Make sure you do not mix legacy and AMD styles together.

Answer №2

According to T Kambi, the string provided is meant for graphics and not geometry. However, I will demonstrate some approaches for converting between json and esriGeometry.

To convert json into esri.Geometry, you can utilize any of the following methods:

  • JsonUtils (esri/geometry/jsonUtils)
  • or the esri.geometry.fromJson method.

Here is an example code snippet for each method:

METHOD ONE (USING JsonUtils)

require(
    ["esri/map", "esri/geometry/jsonUtils", "esri/config", "dojo/domReady!"],
    function (Map, JsonUtils, esriConfig) {

    var jsonGeometry = {"x":10,"y":20,"spatialReference":{"wkid":3857}};

    //Note: Avoid using JsonUtils.fromJson(JSON.stringify(jsonGeometry))
    var geometry = JsonUtils.fromJson(jsonGeometry);
    var graphic = new esri.Graphic(geometry);
});

METHOD TWO (Using geometry.fromJson method)

var jsonGeometry = {"x":10,"y":20,"spatialReference":{"wkid":3857}};
var geometry = esri.geometry.fromJson(jsonGeometry);
var graphic = new esri.Graphic(geometry);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having issues with creating a poll command for my Discord bot as it keeps throwing the error message: "Oops! TypeError: Cannot read property 'push' of undefined."

Can anyone assist me with my question? I am using discord v11.5.1 Below is the code: exports.run = async (bot, message) => { const options = [" ...

Utilizing the json_encode() function in PHP and JSON.parse() method in JavaScript for handling file data interchange

Utilizing json_encode() in PHP to store an array in a file, then leveraging JSON.parse() in JavaScript on the client side to read the json encoded file and pass it as an array to a sorting algorithm: The result of my json_encode() operation in the ...

Is it possible to use ref in React to reference various elements based on specific actions?

I'm having trouble targeting the clicked button using a ref as I always get the second one. Any ideas on how to solve this issue? Also, if I have a native select element with two optgroups, is it possible to determine from which optgroup the selection ...

Find similarities between 2 observable arrays and store them in a new array using knockout data binding

There are three observable arrays set up as follows: a [1,3] b [ {"ID": 1, "Val": "Value1"}, {"ID":2, "Val":"Value2"}, {"ID":3, "Val":"Value3"}] c [] The goal is to compare array a with the IDs of elements in array b and then push the entire value of arr ...

What is the process of obtaining User properties through a URL and utilizing them as variables in JavaScript?

I need to retrieve the city properties: 918 using req.params.userMosque from the URL '/shalat/:userMosque'. I want to assign it to the variable city for customizing my API url request. However, it seems like it's not working as expected. I h ...

Generating Data into JSON Array/Object

I have some JSON data here, { "cleaning" : [ { "MOPS" : [ { "id" : "123", "name" : "best mops", "price" : "123" }, { ...

Waiting for a response from an API with the help of nodejs

I'm new to exploring Node.js and I'm interested in making API calls where the result is awaited before proceeding with any further actions. // defining endpoint function function getListMarket() { var deferred = Q.defer(); deferred.resolve(Q ...

Check if an array includes a specific value, and then either update it if found, or create it

I'm currently working with a Cart object in Javascript and I need to check if a specific item is present in the cart. Here's my approach: If the item is already in the cart, update its quantity. If it's not in the cart, add it to the items ...

Posting JSON data in MVC4 to upload a large amount of data into the database

When I upload Bulk Entries in my Database using JSON, I encounter a problem with the last table column as it is showing null entries. Below are my controller model and JSON data. What could be wrong with this code? This is my Controller public void ESBul ...

Dealing with Superagent and Fetch promises - Tips for managing them

Apologies for posing a question that may be simple for more seasoned JS programmers. I've been delving into superagent and fetch to make REST calls, as I successfully implemented odata but now need REST functionality. However, I'm facing confusio ...

How can we prevent MOXy from displaying the data type in JSON output when marshalling a List<?>?

Is there a way to prevent the type from being displayed when marshalling a List<?>? For example, when marshalling a List<?>, the result is [{"type" : "person","id":"1"},{"type" : "person","id":"2"}] }, and it also includes the type="Person" in ...

difficulty encountered when attempting to input multiple values into a single text field

There are four boxes containing values. When clicking on a box, the value should appear in a text field separated by commas if multiple boxes are selected. <li><a href="javascript:void(0)" onclick="check_stalls('A-14')" id="A-14">A-1 ...

Troubleshooting API password issues when fetching a Json from an API using VBA in Excel

I'm facing challenges with an API that provides natural gas data. The documentation for this API can be found at . It allows me to access Json-formatted data by inputting a URL into my internet browser. However, in order to download the Json data, I n ...

Show information on a pop-up window using Ajax without having to open a new browser tab

I am currently working on a project that uses the Struts framework. In this project, I need to revamp the UI design. The existing project has a menu tab, and when each menu is clicked, a JSP page opens in a new browser window. However, I want these pages t ...

Update the numerical data within a td element using jQuery

Is there a way to use jquery to increase numerical values in a <td> element? I've attempted the following method without success. My goal is to update the value of the td cell by clicking a button with the ID "#increaseNum". Here is the HTML st ...

Properties of a child class are unable to be set from the constructor of the parent class

In my current Next.js project, I am utilizing the following code snippet and experiencing an issue where only n1 is logged: class A { // A: Model constructor(source){ Object.keys(source) .forEach(key => { if(!this[key]){ ...

Dynamically change the state based on intricate layers of objects and arrays

Here is the issue I am facing I am attempting to update the state of an object named singleCarers I have the index of the roster in the rosters array that I need to update However, the key monday: needs to be dynamic, as well as the keys start: and fini ...

"Encountered npm error: JSON input ended unexpectedly" while trying to install express-mysql-session"

I'm currently developing a nodejs project that uses passportjs for user authentication and mysql as the database. I'm now looking to incorporate session storage by utilizing the ""express-mysql-session" package. However, when attemptin ...

The Angular $http.jsonp() function can only be executed one time

Upon the first response being successful (alert->done), any subsequent hits will result in an 'error' response. I attempted to resolve this issue by adding some config parameters with 'cache: false', but it still only works the first t ...

Just-In-Time Compilation: The most efficient method for converting data to JSON format

I am working on generating a custom JSON for the jit library. I am contemplating whether to incorporate additional C# logic or find a way to extend the JsonSerializer. The structure of the desired JSON is shown below: var json = { "children": [ { ...