Search code examples
javascriptjsonheatmapesriarcgis-js-api

Looping JSON objects and plot to map


I am trying to loop through returned JSON objects and plot a heatmap based on the x and y coordinates. Here is how I set up my heatmap:

function getHeatMap() {
heatLayer = new HeatmapLayer({
    config: {
        "useLocalMaximum": true,
        "radius": 40,
        "gradient": {
            0.45: "rgb(000,000,255)",
            0.55: "rgb(000,255,255)",
            0.65: "rgb(000,255,000)",
            0.95: "rgb(255,255,000)",
            1.00: "rgb(255,000,000)"
        }
    },
    "map": map,
    "domNodeId": "heatLayer",
    "opacity": 0.85
});

$.ajax({
    url: "index.aspx/getBusCommuter",
    type: "POST",
    data: "",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        var parsed = JSON.parse(data.d);
        var data = [];
        $.each(parsed, function (i, jsondata) {
            var coordXicon = jsondata.BusStopX;
            var coordYicon = jsondata.BusStopY;

            data = [
                {
                    attributes: {},
                    geometry: {
                        spatialReference: { wkid: 102100 },
                        type: "point",
                        x: coordXicon,
                        y: coordYicon
                    }
                }
           ];
        });
        heatLayer.setData(data);
        map.addLayer(heatLayer);
    },
    error: function (request, state, errors) {
    }
});

}

Basically the JSON object will just loop to the last set of JSON objects and plot out only the last set instead of all. I wonder which part of my logic was wrong.

Thanks in advance.


Solution

  • The issue is here:

    data = [
        {
            attributes: {},
            geometry: {
                spatialReference: {
                    wkid: 102100
                },
                type: "point",
                x: coordXicon,
                y: coordYicon
            }
        }
    ];
    

    You are setting the entire data array for each item (overwriting all the old data) when you probably just want to push a new element onto the end. Try this instead:

    data.push({ ... });