Skip to content

Commit

Permalink
Uploaded first public version of the code
Browse files Browse the repository at this point in the history
  • Loading branch information
jogemu authored Jun 11, 2023
1 parent fa18967 commit c731cc4
Show file tree
Hide file tree
Showing 3 changed files with 226 additions and 0 deletions.
87 changes: 87 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# D3OrthoZoom

This implements `d3.zoom()` for the `d3.geoOrthographic()` projection while preserving a cardinal direction that can only be reversed. Transformations are carried out through rotations, which, with the addition of scaling, also enables interactive projections that can be viewed from all sides.

In existing implementations, whether or not with [d3.js](https://d3js.org/), either the position under the cursor moves or the projection is rotated in all three axes, resulting in a loss of northing. There are limitations in preventing these unwanted effects, but this implementation copes with those limitations by embracing them. Simply put, every time this implementation encounters an undefined position it scales up the projection above what `d3.zoom()` asked for.

## Getting started

After installing [Node.js](https://nodejs.org) you can use npm to add d3orthozoom in your project folder.

```
npm install d3orthozoom
```

Import and use d3orthozoom like this.

```
import * as d3 from 'd3'
import { orthoZoom } from 'd3orthozoom'
const projection = d3.geoOrthographic()
const svg = d3.select('#svg')
const globe = d3.select('#globe')
// structure <svg id="svg"><g id="globe"></g></svg>
// <g> will prevent call of zoom outside globe
// add projected data only to #globe
function render() {
// will be called after scaling and rotation is done
}
const zoom = orthoZoom(projection, svg.node, render)
// zoom.scale(2)
d3.select('#globe').call(zoom).on('mousewheel.zoom', null)
```

## Calculation

The vector `v` is introduced with the pointer's absolute (`v.x`, `v.y`) and relative (`v.xr`, `v.yr`) distance from the center of the projection. Relative values are 0 at the center and absolute 1 at radius. `lon` and `lat` are determined by inverse projection of the pointer position at zoom start.

Reach is the maximum longitude/latitude possible divided by 90. Both are symmetrical. For the longitude the pole is mentally rotated in the center, then the distance of the latitude is just the cosine.

The Pythagorean theorem is used for the latitude. Since v.xr is already in the unit circle, one moves v.xr to the right, then up until the circle is reached. Going back to the start (center) has the length of the radius (hypotenuse = 1).

These variables remain relevant until the end.

```
reach.lon = cosd(abs(lat))
reach.lat = Math.sqrt(1 - (v.xr) ** 2)
```

The projection is increased above user input if necessary.

```
projection.scale(max(
k * event.transform.k, // user input
v.norm, // to prevent leaving globe
abs(v.x) / reach.lon // to prevent pole too far
))
```

The asind will go from [-180, 180] depending on how close the relative x value is to the maximum x value (pole too far). Fortunately, this also puts it on a vertical line with the cursor.

```
r0 = asind(v.xr / reach.lon) - lon
```

Next the latitude of a point is calculated that is on the same height as the pointer and on the centered line that goes south from the north pole.

A second step calculates the latitude of the pointer and adds or subtracts the previous value based on the hemisphere. Both steps must take into account the limitations imposed by the reach.

```
r1 = -90 + asind(cosd(lat) * cosd(lon + r0) / reach.lat)
r1 = -asind(v.yr / reach.lat) + r1 * sign(lat)
```

## Intuitive interaction

For flat projections, it is common that the point under the cursor remains under it during the zooming. For pinch-to-zoom (multi-touch) this point is in the center of the touch events. Ideally, the points under the fingers follow the fingers as if the fingers were physically pulling them apart or squeezing them. For the latter, it is particularly unintuitive if points increasingly deviate from their expected positions.

However, the best thing to do is to just try it out. Write down anything that catches your eye and seems unintuitive. Especially when comparing it to a different map, the differences should be obvious.

## Room for improvement

If the pointer is very close or on the axis of the cardinal direction then not even greatly exaggerated zoom can correct a movement. Let me know about your thoughts on what the tolerances should be. Is shifting the axis intuitive or is it better to simply ignore movements that cannot be performed?

When zooming out, it is unintuitive that the projection stops getting smaller, if the point would be too far from the pole. Direct feedback is missing, especially if the zooming starts already at the limit. An animation that briefly enlarges the projection and then reduces it could give visual feedback. This is not included because this might interfere with your d3 code. On the other hand, repeated/continuous zooming could just translate the projection.
112 changes: 112 additions & 0 deletions main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { zoom, pointers } from 'd3'

const vec = {
minus: (a, b) => a.map((c, i) => c - b[i]),
norm: v => Math.sqrt(v.reduce((p, c) => p + c * c, 0)),
}
const arv = v => Object.assign(v, {
norm: vec.norm(v),
x: v[0],
y: v[1],
})

const sind = deg => Math.sin(deg / 180 * Math.PI)
const cosd = deg => Math.cos(deg / 180 * Math.PI)
const asind = v => Math.asin(v) / Math.PI * 180
const abs = Math.abs, max = Math.max, sign = Math.sign, sqrt = Math.sqrt
const mod = (a, n) => (a % n + n) % n

// Scale and rotate (translate) orthographic projection while preserving a cardinal direction
//
// projection undefined behavior if not d3.geoOrthographic()
// svg provide a function that returns a dom node (d3.select('#svg').node is a function)
// render provide a function that updates all objects affected by projection change
// fallback provide a function and return false if you want to handle the fallback yourself
//
// returns a zoom() result with listeners attached (use d3.select('#globe').call( ))
export function orthoZoom(projection, svg, render, fallback = () => true) {
const pointer = event => pointers(event, svg())[0]
const e2c = event => arv(vec.minus(pointer(event), projection.translate()))
const scalemin = min => projection.scale(max(min, projection.scale()))

let start, k, reach0
return zoom()
.on('start', event => {
let [lon, lat] = start = projection.invert(pointer(event))
k = projection.scale() / event.transform.k

// if start on different side than center flip
let [r0, r1, r2] = projection.rotate()
if (abs(mod(lon + r0 + 180, 360) - 180) > 90) {
projection.rotate([r0, r1, r2 + 180])
}

// The pole is mentally rotated in the center, then the distance of the latitude
// is just the cosine.
reach0 = cosd(abs(lat))
})
.on('zoom', event => {
// Leaves globe if distance from pointer to projection center exceeds
// scaling (globe radius). Increase scaling to ensure inverse projection.
let v = e2c(event)

// The scaling is increased beyond the user input if necessary
projection.scale(max(
k * event.transform.k, // user input
v.norm * 1.00001, // to prevent leaving globe
))

let r2 = projection.rotate()[2]
v.x = v.x * cosd(r2) - v.y * sind(r2)
if (reach0 < 1e-6) {
if (fallback()) {
console.error('The pointer was too close to a pole.')
let [x, y] = projection(start)
let [cx, cy] = projection.translate()
v = e2c(event)
projection.translate([2 * cx + v.x - x, 2 * cy + v.y - y])
render()
}
return
}
// Preserving the northline demands that the point's horizontal distance
// from the center cannot exceed the distance to the closest pole.
// Thus increase scaling if necessary
else scalemin(abs(v.x) / reach0 * 1.00001)


let R = projection.scale()
v = e2c(event)
Object.assign(v, { // rotate if not northed
x: v.x * cosd(r2) - v.y * sind(r2),
y: v.x * sind(r2) + v.y * cosd(r2),
})
Object.assign(v, { // relative cooridnates
xr: v.x / R,
yr: v.y / R,
})

// The asind will go from [-180, 180] depending on how close the relative x value
// is to the maximum x value (pole too far). Fortunately, this also puts it on a
// vertical line with the cursor.
let r0 = asind(v.xr / reach0) - start[0]

let londiff = start[0] + r0
// Since v.xr is already in the unit circle, one moves v.xr to the right, then up
// until the circle is reached. Going back to the start (center) has the length
// of the radius (hypotenuse = 1).
let reach1 = sqrt(1 - (v.xr) ** 2)

// Latitude of a point is calculated that is on the same height as the pointer and
// on the centered line that goes south from the north pole.
let r1 = -90 + asind(cosd(start[1]) * cosd(londiff) / reach1)
// Calculates the latitude of the pointer and adds or subtracts the previous value
// based on the hemisphere.
r1 = -asind(v.yr / reach1) + r1 * sign(start[1])

if (isNaN(r0) || isNaN(r1)) return console.error('NaN during rotation', r0, r1)
projection.rotate([r0, r1, r2])

render()
})
}
27 changes: 27 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "d3orthozoom",
"version": "0.1.0",
"description": "Scale and rotate orthographic projection while preserving a cardinal direction",
"main": "main.js",
"repository": {
"type": "git",
"url": "git+https://github.com/jogemu/d3orthozoom.git"
},
"keywords": [
"d3.js",
"orthographic",
"globe",
"zoom",
"interactive",
"svg"
],
"author": "jogemu",
"license": "UNLICENSED",
"bugs": {
"url": "https://github.com/jogemu/d3orthozoom/issues"
},
"homepage": "https://github.com/jogemu/d3orthozoom#readme",
"dependencies": {
"d3": "^7.8.5"
}
}

0 comments on commit c731cc4

Please sign in to comment.