Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. import React, { useState, useEffect } from "react";
  2. import styles from "./styles.scss";
  3. import { feature } from "topojson";
  4.  
  5. const d3 = Object.assign({}, require("d3-geo"));
  6.  
  7. /**
  8. * OK this is some documentation
  9. * @param {*} props
  10. */
  11. const GeoMap = React.memo(props => {
  12. let projection;
  13. let path;
  14. // Set up component props
  15. const {
  16. width = 800,
  17. height = 600,
  18. mapFileLocation = __webpack_public_path__ + "topo/australia.json",
  19. focusPoint = [133.15399233370441, -24.656909465155994],
  20. margin = 64,
  21. fill = "#ddd",
  22. ...restProps
  23. } = props;
  24.  
  25. // Set up component state
  26. const [geo, setGeo] = useState(null);
  27.  
  28. // Component did mount?
  29. const componentDidMount = () => {
  30. return componentDidUnmount;
  31. };
  32.  
  33. // Component did unmount?
  34. const componentDidUnmount = () => {};
  35.  
  36. // Side effect after first mount
  37. useEffect(componentDidMount, []);
  38.  
  39. // Used to rotate the projection
  40. const invertLongLat = longlat => {
  41. return [-longlat[0], -longlat[1]];
  42. };
  43.  
  44. const loadJson = async fileLocation => {
  45. const data = await fetch(fileLocation);
  46. const topo = await data.json();
  47. const objects = Object.values(topo.objects); // Get array of objects so we don't need the name
  48. const geoJsonObject = feature(topo, objects[0]);
  49.  
  50. setGeo(geoJsonObject);
  51. };
  52.  
  53. // Load map file if not already loaded
  54. if (!geo) loadJson(mapFileLocation);
  55. else {
  56. projection = d3
  57. .geoMercator()
  58. .rotate(invertLongLat(focusPoint))
  59. .fitExtent(
  60. // Auto zoom
  61. [[margin, margin], [width - margin, height - margin]],
  62. geo
  63. );
  64.  
  65. path = d3.geoPath().projection(projection);
  66. }
  67.  
  68. return (
  69. <div className={styles.root}>
  70. <svg className={styles.svg} width={width} height={height}>
  71. {geo && (
  72. <g className={styles.group}>
  73. {geo.features.map((data, iteration) => (
  74. <path
  75. key={`path-${iteration}`}
  76. d={path(data)}
  77. className={styles.feature}
  78. fill={fill}
  79. stroke="white"
  80. strokeWidth={0.5}
  81. />
  82. ))}
  83. </g>
  84. )}
  85. </svg>
  86. </div>
  87. );
  88. });
  89.  
  90. export default GeoMap;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement