Mapbox.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import React from "react";
  2. import ReactMapboxGl, {
  3. Layer,
  4. Feature,
  5. ZoomControl,
  6. ScaleControl,
  7. RotationControl,
  8. } from 'react-mapbox-gl';
  9. import mapboxToken from './config/mapboxToken.js';
  10. import {calcDistance} from './helpers/distance';
  11. import {longitude, latitude, mapWidth, mapHeight} from "./config/variables";
  12. import {Button} from "reactstrap";
  13. const Map = ReactMapboxGl({ accessToken: mapboxToken });
  14. export default class Mapbox extends React.Component{
  15. state = {
  16. latitude: latitude,
  17. longitude: longitude,
  18. zoom: [15],
  19. path: [[longitude, latitude]],
  20. distance: 0,
  21. center: [longitude, latitude]
  22. }
  23. addMarker = (event, click) => {
  24. const lng = click.lngLat.lng
  25. const lat = click.lngLat.lat
  26. console.log("Clicked at", lat, "/", lng)
  27. let pathCopy = this.state.path.slice();
  28. pathCopy.push([lng, lat]);
  29. this.setState({path: pathCopy})
  30. this.getDistance()
  31. }
  32. updateMarker = (idx, event) => {
  33. const lng = event.lngLat.lng
  34. const lat = event.lngLat.lat
  35. console.log(lat, lng, idx)
  36. let pathCopy = this.state.path.slice();
  37. pathCopy[idx] = [lng, lat]
  38. this.setState({path: pathCopy})
  39. this.getDistance()
  40. }
  41. getDistance = () => {
  42. let dst = calcDistance(this.state.path)
  43. this.setState({distance: dst})
  44. }
  45. clearPath = () => {
  46. this.setState({path: [], distance: 0})
  47. }
  48. render() {
  49. const position = [this.state.longitude, this.state.latitude]
  50. return (
  51. <div>
  52. <div className="map">
  53. <Map
  54. style="mapbox://styles/mapbox/bright-v9"
  55. containerStyle={{
  56. height: mapHeight,
  57. width: mapWidth
  58. }}
  59. center={this.state.center}
  60. zoom={this.state.zoom}
  61. onClick={(e, c) => this.addMarker(e, c)}
  62. >
  63. <Layer type="symbol" id="marker" layout={{"icon-image": "marker-15" }}>
  64. {this.state.path.map((pos, idx) =>
  65. <Feature
  66. coordinates={pos}
  67. key={idx} draggable={true}
  68. onDragEnd={(e) => this.updateMarker(idx, e)}
  69. />
  70. )}
  71. </Layer>
  72. <ZoomControl position={"top-right"}/>
  73. <ScaleControl position={"bottom-right"}/>
  74. <RotationControl position={"top-right"}/>
  75. </Map>
  76. </div>
  77. <div className="mapInfo">
  78. <Button onClick={this.clearPath}>Clear path</Button>
  79. <Button onClick={this.getDistance}>Calculate Distance</Button>
  80. <p>
  81. Distanz: {Math.round(this.state.distance*100)/100} km
  82. </p>
  83. </div>
  84. </div>
  85. );
  86. }
  87. }