Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nommuna2
Last active January 8, 2020 17:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nommuna2/d42ffb576a0288106e1fbd57a0cf6536 to your computer and use it in GitHub Desktop.
Save nommuna2/d42ffb576a0288106e1fbd57a0cf6536 to your computer and use it in GitHub Desktop.
(ArcGIS API for JavaScript) Sample of using chart.js with the Esri 4.7 API
html, body, #viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Feature Layer</title>
<link rel="stylesheet" href="https://js.arcgis.com/4.7/esri/css/main.css">
<link rel="stylesheet" href="indexstylesheet.css">
<script>
const options = {
// tell Dojo where to load other packages
dojoConfig: {
async: true,
packages: [
{
location: 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js',
name: 'Chart'
}
]
}
};
</script>
<script src="https://js.arcgis.com/4.7/"></script>
</head>
<body>
<div id="viewDiv"></div>
</body>
<script src="index.js"></script>
</html>
//Please go to the following jsbin for a working sample: https://jsbin.com/nejolahicu/1/edit?html,js,output
//Depending on server load, it may take awhile for the feature layer to load and be displayed on the map.
require([
"esri/Map",
"esri/views/MapView",
"esri/PopupTemplate",
"esri/layers/FeatureLayer",
"esri/widgets/Popup",
"esri/tasks/support/Query",
"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js",
"dojo/domReady!"
],
function (Map, MapView, PopupTemplate, FeatureLayer, Popup, Query, Chart) {
var featureLayerRenderer = {
type: "simple",
symbol: {
type: "simple-fill",
style: "solid",
color: "white",
}
};
var featureLayer = new FeatureLayer({
url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/2",
definitionExpression: "STATE_NAME = 'California'",
renderer: featureLayerRenderer,
visible: true
});
var map = new Map({
basemap: "dark-gray",
layers: [featureLayer]
});
var view = new MapView({
container: "viewDiv",
map: map,
center: [-117.1825, 34.0556],
zoom: 5,
popup: {
dockEnabled: true,
visible: false,
dockOptions: {
buttonEnabled: true,
breakpoint: false,
position: "auto"
}
}
});
// Create a query to get data from the feature layer
var query = new Query();
query.returnGeometry = true;
query.outFields = ["STATE_NAME", "WHITE", "BLACK", "ASIAN", "HAWN_PI", "OTHER", "HISPANIC"];
query.where = "1=1";
query.num = 50;
// On view click, query the feature layer and pass the results to setContentInfo function.
view.on("click", (e) => {
query.geometry = e.mapPoint;
featureLayer.queryFeatures(query).then((results) =>{
if(results.features[0].attributes.STATE_NAME === "California"){
view.popup.visible = true;
view.popup.open({
title: "Doughnut Graph Example",
content: setContentInfo(results.features[0].attributes)
});
}
});
});
// Using the data from the feature layer, create a doughnut graph.
function setContentInfo(results){
// Create a new canvas element, this is where the graph will be placed.
var canvas = document.createElement('canvas');
canvas.id = "myChart";
// Create a data object, this will include the data from the feature layer and other information like color or labels.
var data = {
datasets:[{
data: [results.ASIAN, results.BLACK, results.HAWN_PI, results.HISPANIC, results.OTHER, results.WHITE],
backgroundColor: ["#4286f4", "#41f4be", "#8b41f4", "#e241f4", "#f44185", "#f4cd41"]
}],
labels: [
'Asian',
'Black',
'Hawaiian',
'Hispanic',
'Other',
'White'
]
};
// Create a new Chart and hook it to the canvas and then return the canvas.
var myPieChart = new Chart(canvas,{
type: 'doughnut',
data: data
});
return canvas;
}
});
@nommuna2
Copy link
Author

nommuna2 commented May 11, 2018

Using Third Party Graphing Libraries With The 4.x JavaScript API

Introduction

This is a quick blog post to show how easy it is to integrate beautiful graphs into your JavaScript application using the 4.x API. If you are new to the ArcGIS API for JavaScript, we provide an easy way to get started making web mapping applications. Head over to the ArcGIS API for JavaScript site to get started. For this sample we will be using a third party library called Chart.js. Chart.js is a simple yet flexible JavaScript charting library which makes it easy to make simple graphs for your data.

Load in the Chart.js library into your JavaScript application

In order to use Chart.js in our application we need to load it in as a module. This is because Dojo uses Asynchronous Module Definition (AMD) format to load in modules as supposed to loading in a file using a script tag. To achieve this we can use dojoConfig to load in our custom JS package as a module.

<script>
        const options = {
            // tell Dojo where to load other packages
            dojoConfig: {
                async: true,
            packages: [
                {
                    location: 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js',
                    name: 'Chart'
                }
            ]
            }
        };
</script>
<script src="https://js.arcgis.com/4.7/"></script>

As you can see from the sample code above, we are going to tell dojo to load in a module from a Content Delivery Network (CDN). In this case we are using the CDN's that Chart.js provides for us. You can also install the files through a package manager like npm or Bower. You can learn the different ways of installing Chart.js through their Installation documentation. To avoid any potential errors, ensure the dojoConfig is declared before the ArcGIS for JavaScript API.

Integrating Chart.js in your JavaScript application

Once you have completed the above steps, we can now use Chart.js in our JavaScript file...

require([
    "esri/Map",
    "esri/views/MapView",
    "esri/PopupTemplate",
    "esri/layers/FeatureLayer",
    "esri/widgets/Popup",
    "esri/tasks/support/Query",
    "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js",
    "dojo/domReady!"
  ],
  function (Map, MapView, PopupTemplate, FeatureLayer, Popup, Query, Chart)

In the require array we put in the CDN link to the library. We then name the module Chart so that we can create a new instance of it later on in our code.

Querying data from a Feature Layer

In this example I am using a Feature Layer of California from ArcGIS online . Each time I click on a county, I want a pop up to show information about the demographics of the area. For this we can use a Query, which will allow us to get information from our Feature Layer and spatially query the layer to only show data where we clicked. Once the promise has resolved, we will call the view's PopUp and send the data to setContentInfo. This is a function that will create the chart for us. The setContentInfo function will be explained more in detail on the next section. Here is the code snippet that shows this.

   var query = new Query();

    query.returnGeometry = true;
    query.outFields = ["STATE_NAME", "WHITE", "BLACK", "ASIAN", "HAWN_PI", "OTHER", "HISPANIC"];
    query.where = "1=1";
    query.num = 50;

    // On view click, query the feature layer and pass the results to setContentInfo function.
    view.on("click", (e) => {
      query.geometry = e.mapPoint;
      featureLayer.queryFeatures(query).then((results) =>{
        if(results.features[0].attributes.STATE_NAME === "California"){
          view.popup.visible = true;
          view.popup.open({
              title: "Doughnut Graph Example",
              content: setContentInfo(results.features[0].attributes)
          });
        }
      });
    });

Create a graph using Chart.js

We now get to include the Chart module that we instantiated awhile ago. In the previous code we set the content parameter to a function called setContentInfo and passed in the data. In the next code snippet, we are going to create this function and use it to initialize our charts inside the pop up. To start off we are going to create a new canvas element and give it the id of myChart.

var canvas = document.createElement('canvas');
canvas.id = "myChart";

Then we are going to set up the Data Structure object with our own data. In this particular case we are using a doughnut graph which would have a different Data Structure than a line graph. For more information about the different types of charts you can use, please see the following documentation on the Chart.js website. For a doughnut graph the object would look like the following code snippet below.

var data = {
      datasets:[{
        data: [results.ASIAN, results.BLACK, results.HAWN_PI, results.HISPANIC, 
                 results.OTHER, results.WHITE],
        backgroundColor: ["#4286f4", "#41f4be", "#8b41f4", "#e241f4", "#f44185", "#f4cd41"]
      }],
      labels: [
        'Asian',
        'Black',
        'Hawaiian',
        'Hispanic',
        'Other',
        'White'
      ]
    };

You can see that in the data array, we are setting the results that we got from our feature layer. Each result will represent one piece of the doughnut graph, the backgroundColor is also set for each result value. Additionally, the labels attribute is set for each item in the data array.

Finally, our last step is to create a new Chart object with the data and type properties. Then we return the Chart object.

var myPieChart = new Chart(canvas,{
      type: 'doughnut',
      data: data
  });
return canvas;

Once the object is return we should get a chart inside our pop up showing demographic information each time we click on a county. You can also create this sample using TypeScript. Here is a link to the sample, if you are wondering how it would look in TypeScript.

Tip: On the graph, click on the labels to hide/show a particular field.

Conclusion

The ArcGIS API for JavaScript makes it super simple to integrate beautiful graphs from third party libraries like Chart.js. There are many more libraries that you can integrate into your Javascript application like this that allows you to make powerful maps with additional functionality. Feel free to head over to the GitHub Gist page for the full sample.

@rhodul
Copy link

rhodul commented Jan 8, 2020

This is exactly the problem I'm trying to solve, except my code is in TypeScript and when compiled it does not insert the URL into a define injection section.
This TS import:
import * as jsPDF from 'jspdf';
Compiles to:
define(["require", "exports", "jspdf"]

and then the loader goes and looks for jspdf.js at arcgis.com.

I tried everything, when I import from URL TS complains.
I even tried to wrap jspdf in plain DoJo module, but that too I can't import to TS.

Is there a TS example of your snippet?

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment