Put a map on it.

Learning basic JavaScript though the use of popular map JS API

Popular Map APIs out there

  • Google Maps API
  • Leaflet
  • MapBox
  • ArcGIS API for JavaScript

JavaScript

is the common denominator 

all configured a bit different

this is from a MapTime event

read more here

JavaScript

JavaScript are scripts - sets of instructions

Tell the HTML

You still need to tell the HTML where to find these scripts and how to interpret them. 

You can include the script in the HTML

or in separate files

These API map libraries

  • So you do not need to re-write all the CSS - use theirs!
  • Still require CSS calls
  • Different tutorials within the same API may look different!

A few rules about JavaScript

  • statements (instructions!) end with a semicolon;
  • curly braces indicate start and end of a code block {   }
  • JavaScript is case sensitive
  • Each statement should start on a new line and end with a ; (makes it easier for human to read code)

More tips for writing JavaScript

  • Leave lots of comments to explain what your code does 
  • /* for multiple lines of comments or // in the same line as the code

tips

  • create js folder and files to house scripts
    • remember to call that file path
  •  Then you can call these scripts into an HTML page
  • JavaScript runs where it is found in the HTML

Variables

  • declare a variable
  • assign a value
  • data types =
    • String ('Hi, Class!')
    • Boolean (true)
    • Numeric (0.98)

Rules for Variables

  1. All variables are case sensitive (do not name two variables same name with different cases!)
  2. Do not use keywords or reserved words (example var is  a keyword for variable)
  3. variables must start with letter, $, or underscore, NOT a number
  4. You can't use a dash - or . period in a var name
  5. Use a name that describes the kind of info the variable stores
  6. if you need to use more than one word, capitalize letter after first word (ie. lastName)

JavaScript:

Objects and Methods

  • object is the thing
  • method tells it what to do
  • parameters of the method tell it specifically what to do

Leaflet 

  • open source javascript library
  • renders in the browser
  • small files - light weight
  • renders quickly

Leaflet is pretty much owned by MapBox

  • need an API key

Add Data

overlay

Add a geoJSON file to the server

and add a link to it

 

Now let's follow Britta's tutorial 

That is based on this tutorial

 

Now add style! Lots of it. See my example and leaflet example. 

File too big?

  • Convert Geojson to TopoJson to reduce size of file
  • https://mygeodata.cloud/converter/geojson-to-topojson

Blank Leaflet Map


<!DOCTYPE html>
<html lang="en">
<head>
	<base target="_top">
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	
	<title>Title</title>
	
	<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>

	<style>
		html, body {
			height: 100%;
			margin: 0;
		}
		.leaflet-container {
			height: 400px;
			width: 600px;
			max-width: 100%;
			max-height: 100%;
		}
	</style>

	<style>#map { width: 800px; height: 500px; }
.info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .info h4 { margin: 0 0 5px; color: #777; }
.legend { text-align: left; line-height: 18px; color: #555; } .legend i { width: 18px; height: 18px; float: left; margin-right: 8px; opacity: 0.7; }</style>
</head>
<body>
<h2>
<b>Leaflet<b> This is an example of a leaflet map
</h2>
<div id='map'></div>


<script type="text/javascript" src="SDG15v3.js"></script>

<script type="text/javascript">

	const map = L.map('map').setView([10, 10], 2);

//call the basemap you want to use
	const tiles = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
		maxZoom: 19,
		attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
	}).addTo(map);



</script>



</body>
</html>

Open in your local browser 

What do you see? 

Add your JS file

with geometry and Attribute Data

Add we need to add labels and style

We will change the following

1. Color - use color brewer

2. Class breaks

3. Labels

 

Modify my code


<!DOCTYPE html>
<html lang="en">
<head>
	<base target="_top">
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	
	<title>SDG Map with Leaflet</title>
	
	<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>

	<style>
		html, body {
			height: 100%;
			margin: 0;
		}
		.leaflet-container {
			height: 400px;
			width: 600px;
			max-width: 100%;
			max-height: 100%;
		}
	</style>

	<style>#map { width: 800px; height: 500px; }
.info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255,255,255,0.8); box-shadow: 0 0 15px rgba(0,0,0,0.2); border-radius: 5px; } .info h4 { margin: 0 0 5px; color: #777; }
.legend { text-align: left; line-height: 18px; color: #555; } .legend i { width: 18px; height: 18px; float: left; margin-right: 8px; opacity: 0.7; }</style>
</head>
<body>
<h2>
<b>SDG 15<b> Protect, restore and promote sustainable use of terrestrial ecosystems, sustainably manage forests, combat desertification, and halt and reverse land degradation and halt biodiversity loss. <br><br> <b>SDG Target 15.1 <b>By 2020, ensure the conservation, restoration and sustainable use of terrestrial and inland freshwater ecosystems and their services, in particular forests, wetlands, mountains and drylands, in line with obligations under international agreements
</h2>
<div id='map'></div>

	//here is the geojson file that is called - make sure the path is correct and the file name and case

<script type="text/javascript" src="SDG15v3.js"></script>

<script type="text/javascript">

	const map = L.map('map').setView([10, 10], 2);

//call the basemap you want to use
	const tiles = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
		maxZoom: 19,
		attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
	}).addTo(map);

	// control that shows attribute info on hover
	const info = L.control();

	info.onAdd = function (map) {
		this._div = L.DomUtil.create('div', 'info');
		this.update();
		return this._div;
	};

		//UPDATE to call your own data - the name after "props" is the attribute name - look in your js file to find the attribute to call
	info.update = function (props) {
		const contents = props ? `<b>${props.NAME_LONG}</b><br />${props.whole2} % of total land that is forest` : 'Hover over a state';
		this._div.innerHTML = `<h4>15.1.1 Forest area as a proportion of total land area</h4>${contents}`;
	};

	info.addTo(map);


	// get color depending on population density value //UPDATE for our own legend
	function getColor(d) {
		return d > 100 ? '#005a32' :
			d > 100  ? '#238b45' :
			d > 80  ? '#41ab5d' :
			d > 60  ? '#74c476' :
			d > 40   ? '#a1d99b' :
			d > 10   ? '#c7e9c0' :
			d > 0   ? '#e5f5e0' : '#f7fcf5';
	}

//update the fill color to your variable 
	function style(feature) {
		return {
			weight: 2,
			opacity: 1,
			color: 'white',
			dashArray: '3',
			fillOpacity: 0.7,
			fillColor: getColor(feature.properties.whole2)
		};
	}

	function highlightFeature(e) {
		const layer = e.target;

		layer.setStyle({
			weight: 5,
			color: '#666',
			dashArray: '',
			fillOpacity: 0.7
		});

		layer.bringToFront();

		info.update(layer.feature.properties);
	}

	/* global statesData */ //UPDATE nationData
	const geojson = L.geoJson(nationData, {
		style,
		onEachFeature
	}).addTo(map);

	function resetHighlight(e) {
		geojson.resetStyle(e.target);
		info.update();
	}

	function zoomToFeature(e) {
		map.fitBounds(e.target.getBounds());
	}

	function onEachFeature(feature, layer) {
		layer.on({
			mouseover: highlightFeature,
			mouseout: resetHighlight,
			click: zoomToFeature
		});
	}

	map.attributionControl.addAttribution('SDG data &copy; <a href="https://unstats-undesa.opendata.arcgis.com/">UN SDG DataHub</a>');


	//UPDATE legend to match the classes you coded

	const legend = L.control({position: 'bottomright'});

	legend.onAdd = function (map) {

		const div = L.DomUtil.create('div', 'info legend');
		const grades = [0, 10, 20, 40, 60, 80, 100];
		const labels = [];
		let from, to;

		for (let i = 0; i < grades.length; i++) {
			from = grades[i];
			to = grades[i + 1];

			labels.push(`<i style="background:${getColor(from + 1)}"></i> ${from}${to ? `&ndash;${to}` : '+'}`);
		}

		labels.push(`<i style="background:#FFFFFF"></i>  No Data`);

		div.innerHTML = labels.join('<br>');
		return div;
	};

	legend.addTo(map);

</script>



</body>
</html>

Great!

 

Now let's put our website online!

You are done for today- tomorrow - we will put it all online

Github

Github.io

Made with Slides.com