Displaying a map

Without any charting library, using just standard JavaScript, you can load a JSON file and draw a world map using Canvas. The data is a special JSON format that stores geographical shapes: GeoJSON. Its general structure is as follows:

{"type":"FeatureCollection",
"features":[
{"type":"Feature",id":"AFG","properties":{"name":"Afghanistan"},
"geometry":{"type":"Polygon","coordinates":[[[61.210817,35.650072],...]]
},{"type":"Feature", "id":"AGO", "properties":{"name":"Angola"},
"geometry":{"type":"MultiPolygon","coordinates":[[[[16.326528,-5.87747,...]]
},
// many other lines
]
}

Using JavaScript, you can load this file, parse it, and access each longitude and latitude pair. Then you can scale the values so that they fit into the coordinate system of your Canvas, and draw each shape using Canvas path commands. This is done in the following code (Examples/example-17.html):

<canvas id="map" width="1000" height="500"></canvas>
<script>
var canvas = document.getElementById("map");
var ctx = canvas.getContext("2d");

// Map ocean background
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);

// countries border and background
ctx.lineWidth = .25;
ctx.strokeStyle = 'white';
ctx.fillStyle = 'rgb(50,100,150)';

// load and draw map
fetch('Data/world.geojson')
.then(response => response.text())
.then((jsonData) => {
let object = JSON.parse(jsonData);
drawMap(object.features);
});
function scaleX(coord) {
return canvas.width * (180 + coord) / 360;
}
function scaleY(coord) {
return canvas.height * (90 - coord) / 180;
}
function drawPolygon(coords) {
ctx.beginPath();
for(let i = 0; i < coords.length; i++ ) {
let latitude = coords[i][1];
let longitude = coords[i][0];
if(i == 0) {
ctx.moveTo(scaleX(longitude), scaleY(latitude));
} else {
ctx.lineTo(scaleX(longitude), scaleY(latitude));
}
}
ctx.stroke();
ctx.fill();
}
function drawMap(data) {
data.forEach(obj => {
if(obj.geometry.type == 'MultiPolygon') {
obj.geometry.coordinates.forEach(poly => drawPolygon(poly[0]));
} else if(obj.geometry.type == 'Polygon') {
obj.geometry.coordinates.forEach(poly => drawPolygon(poly));
}
});
}
</script>

The result is shown as follows:

A world map created using GeoJSON, JavaScript, and Canvas code
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset