8.2 Census Map: Adding an onclick event to the map

Let’s prepare a maproom that allows a user to click on it, and get the location back as a latitude/longitude point.

First, start with the following basic maproom. This maproom has the following features:

  • Find an address that uses Google’s geocode function
  • Census tract boundaries from ArcGIS Server (on by default)
  • jQuery UI menu

Adding a “click” event listener

Notice that there is an empty DIV container in the BODY section with the id “charts”. This will eventually be the place where census data charts will be displayed, but let’s use this DIV to display the latitude and longitude coordinates of the location that a user clicks on the map.

Add the following event listener code to the “initialize” function:

The “listener” detects when a user clicks on the map, and displays the latitude and longitude coordinates in the “charts” DIV using jQuery’s .prepend function (“prepend” works the same way “append” works, only, it adds the content before, not after). The latitude and longitude values are defined by these variables:

  • event.latLng.lat()
  • event.latLng.lng()
displaying click latitude and longitude

displaying click latitude and longitude

Using the listener to add a marker

First, create a variable in the global space for a marker:

Now, let’s take this a step further. Create a new function that takes the click latitude and longitude values and displays a marker. The starter code already has a “geocodemarker” variable, so let’s use that to display a marker every time a user clicks on the map. Because this function will eventually make a call to your ArcGIS Server map, let’s name this new function getAGSData.

Add to the map click listener a call to the new function you will create, feeding it the latitude and longitude values:

Then, create the function that will draw a marker on the map based on the latitude and longitude values provided:

Note that there is a check to see whether or not geocodemarker exists, and if so, to delete it. This makes sure that there is never more than one marker on the map at any given time. Also notice a few bells and whistles to the marker: a nice animation feature to make the marker bounce, and designating it as a “draggable” marker!

Leave a Reply