summaryrefslogtreecommitdiffhomepage
path: root/gui/src/renderer/components/SvgMap.tsx
blob: 4884e5786155a6f93784f3f25dfb60d75d53e765 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import { geoTimes } from 'd3-geo-projection';
import rbush from 'rbush';
import * as React from 'react';
import {
  ComposableMap,
  Geographies,
  Geography,
  Marker,
  Markers,
  ZoomableGroup,
} from 'react-simple-maps';

import geographyData from '../../../assets/geo/geometry.json';
import statesProvincesLinesData from '../../../assets/geo/states-provinces-lines.json';

import geometryTreeData from '../../../assets/geo/geometry.rbush.json';
import statesProvincesLinesTreeData from '../../../assets/geo/states-provinces-lines.rbush.json';

// Infer the GeoProjection type from the `geoTimes()` return value
type GeoProjection = ReturnType<typeof geoTimes>;

interface IGeometryLeaf extends rbush.BBox {
  id: string;
}

interface IProvinceAndStateLineLeaf extends rbush.BBox {
  id: string;
}

const geometryTree = rbush<IGeometryLeaf>().fromJSON(geometryTreeData);
const provincesStatesLinesTree = rbush<IProvinceAndStateLineLeaf>().fromJSON(
  statesProvincesLinesTreeData,
);

type BBox = [number, number, number, number];

export interface IProps {
  width: number;
  height: number;
  center: [number, number]; // longitude, latitude
  offset: [number, number]; // [x, y] in points
  zoomLevel: number;
  showMarker: boolean;
  markerImagePath: string;
}

interface IState {
  zoomCenter: [number, number];
  zoomLevel: number;
  visibleGeometry: IGeometryLeaf[];
  visibleStatesProvincesLines: IProvinceAndStateLineLeaf[];
  viewportBbox: BBox;
}

const MOVE_SPEED = 2000;

// @TODO: Calculate zoom level based on (center + span) (aka MKCoordinateSpan)
export default class SvgMap extends React.Component<IProps, IState> {
  public state: IState = {
    zoomCenter: [0, 0],
    zoomLevel: 1,
    visibleGeometry: [],
    visibleStatesProvincesLines: [],
    viewportBbox: [0, 0, 0, 0],
  };

  private projectionConfig = {
    scale: 160,
  };

  constructor(props: IProps) {
    super(props);

    this.state = this.getNextState(null, props);
  }

  public UNSAFE_componentWillReceiveProps(nextProps: IProps) {
    if (this.shouldInvalidateState(nextProps)) {
      this.setState((prevState) => this.getNextState(prevState, nextProps));
    }
  }

  public shouldComponentUpdate(nextProps: IProps, nextState: IState) {
    return (
      this.props.width !== nextProps.width ||
      this.props.height !== nextProps.height ||
      this.props.center[0] !== nextProps.center[0] ||
      this.props.center[1] !== nextProps.center[1] ||
      this.props.offset[0] !== nextProps.offset[0] ||
      this.props.offset[1] !== nextProps.offset[1] ||
      this.props.zoomLevel !== nextProps.zoomLevel ||
      this.props.showMarker !== nextProps.showMarker ||
      this.props.markerImagePath !== nextProps.markerImagePath ||
      this.state.zoomCenter !== nextState.zoomCenter ||
      this.state.zoomLevel !== nextState.zoomLevel
    );
  }

  public render() {
    const mapStyle = {
      width: '100%',
      height: '100%',
      backgroundColor: '#192e45',
    };

    const zoomableGroupStyle = {
      transition: `transform ${MOVE_SPEED}ms ease-in-out`,
    };

    const geographyStyle = this.mergeRsmStyle({
      default: {
        fill: '#294d73',
        stroke: '#192e45',
        strokeWidth: `${1 / this.state.zoomLevel}`,
      },
    });

    const stateProvinceLineStyle = this.mergeRsmStyle({
      default: {
        fill: 'transparent',
        stroke: '#192e45',
        strokeWidth: `${1 / this.state.zoomLevel}`,
      },
    });

    const markerStyle = this.mergeRsmStyle({
      default: {
        transition: `transform ${MOVE_SPEED}ms ease-in-out`,
      },
    });

    // disable CSS transition when moving between locations
    // by using the different "key"
    const userMarker = this.props.showMarker && (
      <Marker
        key={`user-location-${this.props.center.join('-')}`}
        marker={{ coordinates: this.props.center }}
        style={markerStyle}>
        <image x="-30" y="-30" xlinkHref={this.props.markerImagePath} />
      </Marker>
    );

    return (
      <ComposableMap
        width={this.props.width}
        height={this.props.height}
        style={mapStyle}
        projection={this.getProjection}
        projectionConfig={this.projectionConfig}>
        <ZoomableGroup
          center={this.state.zoomCenter}
          zoom={this.state.zoomLevel}
          disablePanning={false}
          style={zoomableGroupStyle}>
          <Geographies geography={geographyData} disableOptimization={true}>
            {(geographies, projection) => {
              return this.state.visibleGeometry.map(({ id }) => (
                <Geography
                  key={id}
                  geography={geographies[parseInt(id, 10)]}
                  projection={projection}
                  style={geographyStyle}
                />
              ));
            }}
          </Geographies>
          <Geographies geography={statesProvincesLinesData} disableOptimization={true}>
            {(geographies, projection) => {
              return this.state.visibleStatesProvincesLines.map(({ id }) => (
                <Geography
                  key={id}
                  geography={geographies[parseInt(id, 10)]}
                  projection={projection}
                  style={stateProvinceLineStyle}
                />
              ));
            }}
          </Geographies>
          <Markers>{[userMarker]}</Markers>
        </ZoomableGroup>
      </ComposableMap>
    );
  }

  private mergeRsmStyle(style: {
    default?: React.CSSProperties;
    hover?: React.CSSProperties;
    pressed?: React.CSSProperties;
  }) {
    const defaultStyle = style.default || {};
    return {
      default: defaultStyle,
      hover: style.hover || defaultStyle,
      pressed: style.pressed || defaultStyle,
    };
  }

  private getProjection(
    width: number,
    height: number,
    config: {
      scale?: number;
      xOffset?: number;
      yOffset?: number;
      rotation?: [number, number, number];
      precision?: number;
    },
  ) {
    const scale = config.scale || 160;
    const xOffset = config.xOffset || 0;
    const yOffset = config.yOffset || 0;
    const rotation = config.rotation || [0, 0, 0];
    const precision = config.precision || 0.1;

    return geoTimes()
      .scale(scale)
      .translate([xOffset + width / 2, yOffset + height / 2])
      .rotate(rotation)
      .precision(precision);
  }

  private getZoomCenter(
    center: [number, number],
    offset: [number, number],
    projection: GeoProjection,
    zoom: number,
  ): [number, number] {
    const pos = projection(center)!;
    return projection.invert!([pos[0] + offset[0] / zoom, pos[1] + offset[1] / zoom])!;
  }

  private getViewportGeoBoundingBox(
    centerCoordinate: [number, number],
    width: number,
    height: number,
    projection: GeoProjection,
    zoom: number,
  ): BBox {
    const center = projection(centerCoordinate)!;
    const halfWidth = (width * 0.5) / zoom;
    const halfHeight = (height * 0.5) / zoom;

    const northWest = projection.invert!([center[0] - halfWidth, center[1] - halfHeight])!;
    const southEast = projection.invert!([center[0] + halfWidth, center[1] + halfHeight])!;

    // normalize to [minX, minY, maxX, maxY]
    return [
      Math.min(northWest[0], southEast[0]),
      Math.min(northWest[1], southEast[1]),
      Math.max(northWest[0], southEast[0]),
      Math.max(northWest[1], southEast[1]),
    ];
  }

  private shouldInvalidateState(nextProps: IProps) {
    const oldProps = this.props;
    return (
      oldProps.width !== nextProps.width ||
      oldProps.height !== nextProps.height ||
      oldProps.center[0] !== nextProps.center[0] ||
      oldProps.center[1] !== nextProps.center[1] ||
      oldProps.offset[0] !== nextProps.offset[0] ||
      oldProps.offset[1] !== nextProps.offset[1] ||
      oldProps.zoomLevel !== nextProps.zoomLevel
    );
  }

  private getNextState(prevState: IState | null, nextProps: IProps): IState {
    const { width, height, center, offset, zoomLevel } = nextProps;

    const projection = this.getProjection(width, height, this.projectionConfig);
    const zoomCenter = this.getZoomCenter(center, offset, projection, zoomLevel);
    const viewportBbox = this.getViewportGeoBoundingBox(
      zoomCenter,
      width,
      height,
      projection,
      zoomLevel,
    );

    // combine previous and current viewports to get the rough area of transition
    const combinedViewportBboxMatch = prevState
      ? {
          minX: Math.min(viewportBbox[0], prevState.viewportBbox[0]),
          minY: Math.min(viewportBbox[1], prevState.viewportBbox[1]),
          maxX: Math.max(viewportBbox[2], prevState.viewportBbox[2]),
          maxY: Math.max(viewportBbox[3], prevState.viewportBbox[3]),
        }
      : {
          minX: viewportBbox[0],
          minY: viewportBbox[1],
          maxX: viewportBbox[2],
          maxY: viewportBbox[3],
        };

    const visibleGeometry = geometryTree.search(combinedViewportBboxMatch);
    const visibleStatesProvincesLines = provincesStatesLinesTree.search(combinedViewportBboxMatch);

    return {
      zoomCenter,
      zoomLevel,
      visibleGeometry,
      visibleStatesProvincesLines,
      viewportBbox,
    };
  }
}