Advertisement
Guest User

Untitled

a guest
May 21st, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {PureComponent} from 'react';
  2. import Leaflet from 'leaflet';
  3. import cities from '../../mocks/cities';
  4.  
  5. const initData = {
  6.   ZOOM: 12
  7. };
  8.  
  9. const ICON = Leaflet.icon({
  10.   iconUrl: `img/pin.svg`,
  11.   iconSize: [27, 39],
  12.   iconAnchor: [13, 39]
  13. });
  14.  
  15. class Map extends PureComponent {
  16.   constructor(props) {
  17.     super(props);
  18.   }
  19.  
  20.   addMarkers(cards, group) {
  21.     cards.map((card) => {
  22.       Leaflet.marker(card.coords, {icon: ICON}).addTo(group);
  23.     });
  24.   }
  25.  
  26.   render() {
  27.     return (
  28.       <div id="map"
  29.         ref={
  30.           (ref) => {
  31.             this.container = ref;
  32.           }
  33.         }
  34.       />
  35.     );
  36.   }
  37.  
  38.   componentDidMount() {
  39.     const {cards} = this.props;
  40.  
  41.     setTimeout(() => {
  42.       this.map = Leaflet.map(this.container, {
  43.         center: cities.get(cards[0].city),
  44.         zoom: initData.ZOOM,
  45.         zoomControl: false,
  46.         layers: new Leaflet.TileLayer(`https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png`, {
  47.           attribution: `&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>`
  48.         })
  49.       }, 100);
  50.  
  51.       this.markers = Leaflet.layerGroup().addTo(this.map);
  52.       this.addMarkers(cards, this.markers);
  53.     });
  54.   }
  55.  
  56.   componentDidUpdate() {
  57.     const {cards} = this.props;
  58.  
  59.     if (this.map) {
  60.       this.map.setView(cities.get(cards[0].city), initData.ZOOM);
  61.       this.markers.clearLayers();
  62.       this.addMarkers(cards, this.markers);
  63.     }
  64.   }
  65. }
  66.  
  67. Map.propTypes = {
  68.   cards: PropTypes.arrayOf(PropTypes.shape({
  69.     id: PropTypes.number.isRequired,
  70.     coords: PropTypes.array,
  71.     price: PropTypes.number.isRequired,
  72.     rating: PropTypes.number.isRequired,
  73.     image: PropTypes.string.isRequired,
  74.     title: PropTypes.string.isRequired,
  75.     type: PropTypes.string.isRequired,
  76.     isPremium: PropTypes.bool.isRequired,
  77.     isBookmark: PropTypes.bool.isRequired
  78.   })).isRequired
  79. };
  80.  
  81. export default Map;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement