Skip to content

Instantly share code, notes, and snippets.

@IagoLast
Created March 9, 2018 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IagoLast/b4e814e54e13469e36a3ff43c4737f90 to your computer and use it in GitHub Desktop.
Save IagoLast/b4e814e54e13469e36a3ff43c4737f90 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Mercator projection example</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
touch-action: none;
}
canvas {
border: 1px solid black;
display: block;
margin: auto;
}
;
</style>
</head>
<body>
<script>
// Used to generate colors
let i = 0;
// Adjust the map size to the window size
const MAP_SIZE = Math.min(window.parent.window.innerHeight, window.parent.window.innerWidth);
// Set the projection Radius, force the diameter to be equal to map size.
const R = MAP_SIZE / (2 * Math.PI);
// Diameter of the globe
const D = R * 2 * Math.PI;
// Create a canvas element
const canvas = document.createElement('canvas');
// Set canvas size
canvas.width = MAP_SIZE;
canvas.height = MAP_SIZE;
// Add the canvas to the DOM
document.body.appendChild(canvas);
// Save a drawing context into the map variable
const map = canvas.getContext('2d');
Z = 1;
let delta = {
x: 0,
y: 0
}
let center = [-8, 43];
let c = _project(center);
// fetch('https://raw.githubusercontent.com/codeforamerica/click_that_hood/master/public/data/spain-provinces.geojson')
// fetch('https://raw.githubusercontent.com/openlayers/openlayers/master/examples/data/geojson/roads-seoul.geojson')
fetch('world.json')
.then(response => response.json())
.then(data => {
window.data = data;
drawGeoJson(data);
getUserInput(canvas, (dx, dy, dz) => {
if (dz > 0) {
if (Z !== 20) {
Z++;
}
}
if (dz < 0) {
if (Z !== 1) {
Z--;
}
}
if (dz === 0) {
delta.x = fit(delta.x - dx);
delta.y = fit(delta.y - dy);
}
console.log(c);
drawGeoJson(data);
})
});
function fit(delta) {
return Math.max(Math.min(delta, D * Z), -D * Z);
}
/**
* Draw a geoJson object, it only supports polygons and MultiPolygons
*/
function drawGeoJson(geoJsonData) {
// let c = _project(center);
map.setTransform(1, 0, 0, 1, 0, 0);
map.scale(Math.pow(2, Z), Math.pow(2, Z));
map.fillStyle = 'aliceblue';
map.fillRect(0, 0, canvas.width, canvas.height);
geoJsonData.features.forEach(feature => {
if (feature.geometry.type === 'Polygon') {
drawPolygon(map, feature.geometry.coordinates[0]);
}
if (feature.geometry.type === 'MultiPolygon') {
feature.geometry.coordinates.forEach(coords => drawPolygon(map, coords[0]));
}
if (feature.geometry.type === 'LineString') {
drawLine(map, feature.geometry.coordinates);
}
});
}
/**
* Given a list of coordinates, draw into a rendering context a polygon.
*/
function drawPolygon(ctx, coords) {
const coordinates = coords.map(x => x);
const initialPoint = project(coordinates.shift());
ctx.fillStyle = getColor();
ctx.beginPath();
ctx.moveTo(initialPoint.x, initialPoint.y);
coordinates.map(project).forEach(point => ctx.lineTo(point.x, point.y));
ctx.closePath();
ctx.fill();
}
/**
* Given a list of coordinates, draw into a rendering context a polygon.
*/
function drawLine(ctx, coords) {
const coordinates = coords.map(x => x);
ctx.strokeStyle = 'black';
ctx.beginPath();
const initialPoint = project(coordinates.shift());
ctx.moveTo(initialPoint.x, initialPoint.y);
coordinates.map(project).forEach(point => ctx.lineTo(point.x, point.y));
ctx.stroke();
}
// PROYECCION EN PIXELES
function project(point) {
const p = _project(point);
cx = c.x - (c.x / Math.pow(2, Z));
cy = c.y - (c.y / Math.pow(2, Z));
return {
x: (p.x - cx) - delta.x / Math.pow(2, Z),
y: (p.y - cy) - delta.y / Math.pow(2, Z)
}
}
/**
* Webmercator projection.
* Since D === MAP_SIZE this function already returns pixel coordinates in the canvas.
*/
function _project([lon, lat]) {
const sinlat = Math.sin(lat * Math.PI / 180.0);
const x = D * lon / 360.0;
const y = R / 2 * Math.log((1 + sinlat) / (1 - sinlat));
return { x: (D / 2 + x), y: (D - (D / 2 + y)) }
}
/**
* Generate a color
*/
function getColor() {
return 'mediumseagreen'; //`rgb(${i++ % 255}, ${180}, ${255})`;
}
function getUserInput(canvas, callback) {
var dragging = false;
var xo, yo;
canvas.addEventListener('mousedown', e => {
dragging = true
xo = e.clientX
yo = e.clientY
}, { passive: false });
canvas.addEventListener('mouseup', () => {
dragging = false;
}, { passive: false });
canvas.addEventListener('mousemove', e => {
if (dragging) {
let [dx, dy] = [e.clientX - xo, e.clientY - yo]
callback(dx, dy, 0)
xo = e.clientX
yo = e.clientY
}
return false;
}, { passive: false });
canvas.addEventListener('wheel', e => {
dragging = false;
e.preventDefault();
if (Math.abs(e.deltaY) < 2) {
return;
}
callback(0, 0, e.deltaY > 0 ? 1 : -1)
}, { passive: false });
canvas.addEventListener('dblclick', () => {
dragging = false;
callback(0, 0, 1)
}, { passive: false });
}
</script>
</body>
</html>
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment