Interacting with Other Elements

A powerful and relatively easy way to create interactive mapping applications is to create a map that displays dynamic information as the user interacts with the map.

The example below will display chart data using "Chart.js", a freely available library. When the user clicks in each county, the information for that county is displayed.

Example (this map can take a while to load as the county data is extensive).

The Code

Below is the code for updating the chart when the user clicks on an area. This code can be inserted just before you call "StartMap()'. You'll also need to add an additional canvas element for the chart.

Layer_Countries.MouseDown=function(TheView,RefX,RefY) 	
{
	var Used=false; // flag to indicate if we have used the event
	
	// if this layer was clicked with the INFO tool then update the chart
	
	if ((this.GetVisible())&&(TheView.GetTool()==TOOL_INFO)) 		
	{	
		// get the feature selected, if any						
		var FeatureIndex=this.In(TheView,RefX,RefY); 						
		if (FeatureIndex!=-1) // -1 indicates no feature selected			
		{				
			// get the feature from the GeoJSON object
			var TheFeatures=this.TheData.features;
			var TheFeature=TheFeatures[FeatureIndex];
		
			// update the DIV tag over the chart to contain the name of the selected county
			var TheCountyInfo=document.getElementById("CountyInfo");
			
			TheCountyInfo.innerHTML="County: "+TheFeature.properties["Areaname"];
			
			// Setup the labels and "buckets" for the chart
			
			var Labels=["AGE010180D","AGE010190D","AGE010200D","AGE010180D","AGE010210D","AGE030200D"];
			
			var Buckets=[]; // the buckets (values) for each cateogory
			
			for (var i=0;i<Labels.length;i++) 
			{
				var TheLabel=Labels[i];
				Buckets[i]=TheFeature.properties[TheLabel];
			}
			// Setup the data for the chart library
			
			var Color="rgba(20,20,20,1)";
			
			var TheBarChartData={
				labels : Labels,
				datasets : [
					{
						fillColor : Color,
						strokeColor : Color,
						highlightFill: Color,
						highlightStroke: Color,
						data : Buckets
					}
				]
			}
			
			Chart.defaults.global.animation=false; // comment this out to see animated charts
			
			// Get the canvas element for the chart and set its data
			
			var TheCanvas=document.getElementById("TheCanvas"); // canvas
			var TheContext=TheCanvas.getContext("2d");
			var BarChart=new Chart(TheContext).Bar(TheBarChartData, 
			{
			//					responsive : true // add other properties if desired
			});
			
			// for some reason the chart gets larger with each call so we have to reset it's position
			
			CMUtilities.AbsolutePosition(TheCanvas,800,60,300,300);
			
			Used=true; // let the caller know we've used the event so no one else uses it
		}
	}
	return(Used);
};