Building a Game with the ArcGIS API for JavaScript
By: Chris Andrews
Tags: GIS, JavaScript, Esri, Arcgis, Simulation

Creating a game with the ArcGIS JavaScript API is an excellent exercise to explore complex geospatial processing workflows in a browser

Yes, I’m a Product Manager. Now that that’s out there, I confess that I’m not necessarily one of those Product Managers who likes to code or is necessarily good at coding. No, I’d say that I’m one of those who needs to code to keep my sanity.

About once a year, I end up stumbling into an interesting project and this year, after banning my son from Fortnite and having a deep conversation about creativity and the accessibility of modern coding and game creation, I decided to put my fingers where my mouth was.

What better way to follow through than by testing out some of Esri’s capabilities, getting my hands dirty in code, and demonstrating to my son that, yes, a lame dad like me who bans kids from Fortnite can create a game in a few hours.

What I wanted to test

Based upon some work conversations and my past interests, I was specifically interested in exploring the following three concepts:

Querying Scene Layers — Scene layers are Esri’s open standard for sharing extremely large, heterogeneous datasets of 3D geospatial content. Scene Layers are making their way from being visualization tools to enablying query, analysis, and update workflows.

— Scene layers are Esri’s open standard for sharing extremely large, heterogeneous datasets of 3D geospatial content. Scene Layers are making their way from being visualization tools to enablying query, analysis, and update workflows. Client-side geoprocessing — Geoprocessing, using spatial calculations to derive analyses and reports from mapping data, is an important tool in many Esri users’ portfolios, allowing them to do more than just make pretty maps. Much of the programming work that I did in my MS and undergrad could be considered client-side geoprocessing, but running in an EXE written in Pascal, VB, or C++ and working against files or a database. What does that kind of processing look like on the client side (maybe with a little help from the server) in a browser?

— Geoprocessing, using spatial calculations to derive analyses and reports from mapping data, is an important tool in many Esri users’ portfolios, allowing them to do more than just make pretty maps. Much of the programming work that I did in my MS and undergrad could be considered client-side geoprocessing, but running in an EXE written in Pascal, VB, or C++ and working against files or a database. What does that kind of processing look like on the client side (maybe with a little help from the server) in a browser? JavaScript mapping web app customization circa 2019 — Forget all the fancy stuff. I’ve been using JavaScript since 1997 when it was a way to pass parameters into a Java applet embedded in a browser. I just wanted to find out for myself how hard it is to create an interesting web app with Esri’s JavaScript tools.

The initial idea

There have been a few repeat ideas that I have coded over and over. One of these is John Horton Conway’s Game of Life, a grid-based interactive experience in which you define the initial state of cells in a grid and the game then uses spatial-based ‘reproduction’ rules to iterate out subsequent states of all the cells in the grid. My high school math teacher, Richard Remenih, got me interested in Fractals and Chaos theory in the late 80’s and the Game of Life was a frequent starter example for introducing students to the concept of iterative models. This later became essential to my MS work and other simulation modeling work I completed in college including my first GIS analytical projects.

From The Game of Life on Wikipedia: A single Gosper’s glider gun creating “gliders”

Real world geospatial problem sets are a bit more messy than the virtual world that Conway conceived as they don’t typically occur on nice grids. The 3D buildings in many cities kind of look like cells on a grid, so that was somewhere to start. From that starting point, I needed a scenario to translate the ‘reproduction’ in the grid-based game into a more natural geospatial context.

The scenario

It’s 2.2.2022 and you are a junior scientist at the Parasol Corporation. Your company (secretly a defense contractor) has been tasked with coming up with a biological vector (groundhog) to spread a microscopic genetic engineering agent (virulent modified virus) throughout a small town. Your job is to design the virus’ properties, determine where to release one or more groundhogs on day 0, then to sit back and watch the action. As a good scientist, of course, you’ll collect some statistics on your results and compare between trials… I mean… simulated test runs.

Because you’re junior and a digital native, you’d really rather do all of this on your phone…

The game

After about 30 hours of brushing up on rusty skills, rediscovering that I still like to grow my own libraries, and testing by a 12 year old who breaks things pretty well, I came up with the Groundhog City Simulation game. You can try it here: http://bit.ly/GroundhogCity

The game mechanics are pretty simple.

Set parameters that determine the properties of your virus. Pick some buildings on a map that indicate where you’re going to free your rabid groundhogs. Push Play. At the ‘end,’ you get a score based on a cost curve determined by how successful your groundhogs were and how far your virus departed from a minimum effect starting point.

With a little trial and error, you should be able to see something like this.

Most of the app mechanics happen on the client side. The server requests essentially are constrained to the initial set up, requests to retrieve map data for visualization, and two different query requests against the Scene Layer which lives as a service in ArcGIS Online. The rest is just customization-by-Chris.

The app includes a lot of essential functionality that I didn’t have to create. There are some basic out-of-the-box map interactions that are standard to Esri’s 3D WebGL experience such as using your mousewheel, or pinch and pull on touch screens, to zoom in and out. Loading a scene layer and querying it was straightforward. I was also able to selectively choose and customize controls provided by ArcGIS, such as the fullscreen control (the only default control I kept).

Aside from the fact that creating this satisfied some latent coding urges, I even discovered that I could somewhat emulate some of Conway’s Game effects, such as repeating patterns of infection:

Repeating patterns in the simulation of infectious happiness in a small town

Some things I learned along the way

Regarding the main topics I wanted to investigate, I managed to dive into all three in the project.

Querying Scene Layers — Scene layers (specifically 3D Object and 3D Point Scene Layers) are now queryable and I was able to demonstrate that using both attribute queries against feature ObjectIDs and through spatial intersection queries. It’s possible to do some querying against a client-side view of Scene Layers, but for what I wanted to do, it was necessary to query against the source data on in the cloud.

Scene layers (specifically 3D Object and 3D Point Scene Layers) are now queryable and I was able to demonstrate that using both attribute queries against feature ObjectIDs and through spatial intersection queries. It’s possible to do some querying against a client-side view of Scene Layers, but for what I wanted to do, it was necessary to query against the source data on in the cloud. Client-side geoprocessing — For my purposes, I was able to explore the JavaScript geometry engine, play with map graphics, and string together a series of analytical operations in a way that allowed me to create a model of an effect propagation throughout a geospatial system. The model could have been more sophisticated, but that would have been up to me. Reasonably complex operations can be combined through standard programming tools in geoprocessing workflows even in a web browser.

— For my purposes, I was able to explore the JavaScript geometry engine, play with map graphics, and string together a series of analytical operations in a way that allowed me to create a model of an effect propagation throughout a geospatial system. The model could have been more sophisticated, but that would have been up to me. Reasonably complex operations can be combined through standard programming tools in geoprocessing workflows even in a web browser. JavaScript mapping apps — This turned out to be the easy part. To be honest, I have created a few hacks of ArcGIS sample apps in the past, but this time I wanted to build something a bit more complete. Once I got the feel for the ArcGIS for JavaScript API, the ArcGIS stuff was out of my way and I was able to focus on making my game actually work.

There were a few other lessons learned that I shared with the team:

Promises architecture — Promises have been introduced in the last few years to provide a better interface to asynchronous coding in JavaScript than the roll-your-own AJAX libraries that people like me used to make. For a complex workflow, such as an iterative multistep game, Promises can be a bit convoluted and I resorted to using async/await to streamline my code. I also don’t like burying a lot of code in the .then() pattern that Promises require. This did come with a cost. I lost some interactivity (the map freezes during iterations) and I may want to undo this at some point in the future. That will be a moderately complicated task because I’ll have to code a state manager that essentially arbitrates the execution of the simulation as asynchronous calls complete. For many geoprocessing workflows, async/await may actually be preferrable.

— Promises have been introduced in the last few years to provide a better interface to asynchronous coding in JavaScript than the roll-your-own AJAX libraries that people like me used to make. For a complex workflow, such as an iterative multistep game, Promises can be a bit convoluted and I resorted to using async/await to streamline my code. I also don’t like burying a lot of code in the .then() pattern that Promises require. This did come with a cost. I lost some interactivity (the map freezes during iterations) and I may want to undo this at some point in the future. That will be a moderately complicated task because I’ll have to code a state manager that essentially arbitrates the execution of the simulation as asynchronous calls complete. For many geoprocessing workflows, async/await may actually be preferrable. Client-side attributes — One of the interesting things about simulation games such as what I created or the more true-to-life ant population simulations I did in my Master’s is that you’re often calculating ephemeral feature attributes that you want to use as temporary states in your model. To accomplish this with my app, I’m maintaining separate arrays of values dissassociated from the Scene Layer, which is effectively the database table with my source data. I’d prefer to be able to create some kind of virtual client-side column dynamically added to that dataset and that would work with calculations and with renderers for map symbology.

— One of the interesting things about simulation games such as what I created or the more true-to-life ant population simulations I did in my Master’s is that you’re often calculating ephemeral feature attributes that you want to use as temporary states in your model. To accomplish this with my app, I’m maintaining separate arrays of values dissassociated from the Scene Layer, which is effectively the database table with my source data. I’d prefer to be able to create some kind of virtual client-side column dynamically added to that dataset and that would work with calculations and with renderers for map symbology. It works on the phone — One of the absolute coolest out-of-the-box aspects of the ArcGIS API for JavaScript is that the team has put much effort into making sure that it works on mobile devices. With some intelligent interface design, it was fairly easy to make an experience that can be used on the phone.

A trial Groundhog City run on my Android phone

1000’s of people could run this at once — One of the most incredible realizations is that this isn’t some EXE running on a high-end lab computer. Conceivably 1000’s of users could be running this simulation at once, each using the power of their local device with a relatively few hits against cloud processing to query the data set. The next thing I’ll have to do is to create a leaderboard!

Take aways for anyone who loves coding and maps

The experiment so far has been successful. Anyone who knows a bit of JavaScript coding can create a fairly sophisticated web experience that uses cloud-hosted data to perform client-side geoprocessing tasks. When needed, the workflow can even tap into more sophisticated cloud-based geoprocessing tools that I didn’t even try to engage.

The example I created is completely free and anyone can create something similar. I’m using a publicly available JavaScript library. I’m querying publicly shared data, a modified open data set that I simplified for purposes of my experiment. There are 1000s more open data sets in ArcGIS Online. It’s really easy to get started by trying the samples on the ArcGIS developer pages. And then you can always take a look at my scripts on GitHub. Even better, check out Ralucca’s incredible examples.

If you’re curious, try it. Anyone can and we’d love to see your examples and even answer your questions on our GeoNet pages for the ArcGIS API for JavaScript.

So what about Fortnite?

Fortnite is still banned until further notice, but this has been a great teachable moment. My son figured out from the simulation that geographic features, such as roads, can form unexpected barriers to propagating effects. He also learned that intersection with geometry is a precise affair, even in a web browser. And, of course, he thought it was pretty cool that I could create the game in the first place.

All in all, this turned into a great diversion and experiment in which I could demonstrate that it’s possible even for a rusty coder like myself to create some pretty incredible apps with the ArcGIS API for JavaScript. I hope to see lots of great examples from our users in the developer community.

Acknowledgements

Thanks to the City of Bellingham, WA, for sharing some great open data that they probably never thought would serve as the foundation for a groundhog invasion.

Big thanks to the hard work of the Esri JavaScript team who did 99% of the work that made my few hours of coding fruitful.

If anyone at Capcom happened to notice the similarities to a certain recurring evil video game plot, please pardon the borrowing done in the spirit of education.

Fortnite is a registered trademarks of Epic Games, Inc. in the United States of America and elsewhere.