map.component.ts 1.71 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { Component, ChangeDetectorRef, OnDestroy, ChangeDetectionStrategy } from '@angular/core';
import { latLng, tileLayer, MapOptions, TileLayer } from 'leaflet';
import { MediaMatcher } from '@angular/cdk/layout';

const createLayer = (map) => tileLayer(
    map,
    {
        attribution:
            '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>',
        subdomains: 'abcd',
        maxZoom: 19
    }
);

const LIGHT_MODE_LAYER = createLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}{r}.png');
const DARK_MODE_LAYER = createLayer('https://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}{r}.png');
Andrew Hrdy's avatar
Andrew Hrdy committed
17
18
19
20

@Component({
    selector: 'app-map',
    templateUrl: './map.component.html',
21
22
    styleUrls: ['./map.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
Andrew Hrdy's avatar
Andrew Hrdy committed
23
})
24
25
26
27
28
export class MapComponent implements OnDestroy {

    mapOptions: MapOptions = {
            zoom: 17,
            center: latLng(38.831493, -77.311485)
Andrew Hrdy's avatar
Andrew Hrdy committed
29
    };
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

    private darkModeQuery: MediaQueryList;
    private darkModeQueryListener;

    constructor(private cd: ChangeDetectorRef, media: MediaMatcher)  {
        this.darkModeQuery = media.matchMedia('(prefers-color-scheme: dark)');

        this.darkModeQueryListener = () => cd.detectChanges();

        this.darkModeQuery.addListener(this.darkModeQueryListener);
    }

    get isDarkMode(): boolean {
        return this.darkModeQuery.matches;
    }

    get mapLayers(): TileLayer[] {
        return this.isDarkMode ? [DARK_MODE_LAYER] : [LIGHT_MODE_LAYER];
    }

    ngOnDestroy() {
        this.darkModeQuery.removeListener(this.darkModeQueryListener);
    }
Andrew Hrdy's avatar
Andrew Hrdy committed
53
}