models/map.ts   A
last analyzed

Complexity

Total Complexity 4
Complexity/F 4

Size

Lines of Code 135
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 87
mnd 3
bc 3
fnc 1
dl 0
loc 135
rs 10
bpm 3
cpm 4
noi 0
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A map.ts ➔ deg2rad 0 2 4
1
import { API_KEY } from '@env';
2
import config from '../config/config.json';
3
import storage from './storage';
4
5
const mapModel = {
6
7
    /**
8
     * Get all cities from API
9
     * @param API_KEY 
10
     * @returns Promise<Object>
11
     */
12
    getCities: async function getCities(API_KEY: string): Promise<Object> {       
13
        const token = await storage.readToken();        
14
        
15
        const response = await fetch(`${config.base_url}cities?api_key=${API_KEY}`, {
16
            method: 'GET',
17
            headers: {
18
                'x-access-token': token['token']
19
            }
20
        });
21
        
22
        const result = await response.json();
23
24
        
25
        
26
        return result;
27
    },
28
29
    /**
30
     * Get closest city based on users location
31
     * @param API_KEY 
32
     * @param userData 
33
     * @returns Promise<object>
34
     */
35
    getClosestCity: async function getClosestCity(userData: object): Promise<Object> {
36
        const cities = await mapModel.getCities(API_KEY);
37
        
38
        const city2User = [];
39
        for (const city of Object.entries(cities['cities'])) {
40
            // console.log(city[1]['zones'][0]);
41
            // console.log(city[1]['name']);
42
            const cityCoordinates = mapModel.cityCoordinates(city[1]['name']);
43
            const distance2User = mapModel.calcDistance(cityCoordinates['latitude'], cityCoordinates['longitude'], userData['latitude'], userData['longitude']);
44
45
            city2User.push([city[1], distance2User]);
46
        };
47
        
48
        const sortedCity2User = city2User.sort((a, b) => {
49
            return a[1] - b[1];
50
        });
51
52
        // console.log(userData);
53
54
        // console.log(sortedCity2User[0][0]);
55
        // console.log(cities['cities'][0]);
56
        
57
        
58
        // return cities['cities'][1];
59
        return sortedCity2User[0][0];
60
    },
61
62
    /**
63
     * Get zones for a given city
64
     * @param city 
65
     * @returns string
66
     */
67
    getZones: function getZones(city: object): string[] {
68
        
69
        // All zones in current city
70
        const zones = city['zones'];
71
        
72
        // Zone colors based on zoneType
73
        const zoneColors = {
74
            parkingZone: '#96FF7166',
75
            noParkingZone: '#FF606066',
76
            bonusParkingZone: '#C64EFF66',
77
            chargingZone: '#638FFF66'
78
        };
79
80
        // Array to be returned containing all zones and data
81
        const zoneMarkers = [];
82
        
83
        // Loop through all zones and append them to return object
84
        for (let i = 0; i < zones.length; i++) {
85
            const coordinates = city['zones'][i]['coordinates'];
86
            
87
            // console.log(city['zones'][i]['zoneType']);
88
            
89
            
90
            const zone = {
91
                _id: city['zones'][i]['_id'],
92
                zoneType: city['zones'][i]['zoneType'],
93
                zoneColor: zoneColors[city['zones'][i]['zoneType']],
94
                coordinates: []
95
            };
96
            for (const LatLng of coordinates) {
97
                zone['coordinates'].push({latitude: LatLng[1], longitude: LatLng[0]})
98
            };
99
            
100
            zoneMarkers.push(zone);
101
        }        
102
        
103
        return zoneMarkers;
104
    },
105
106
    calcDistance: function calcDistance(lat1, lon1, lat2, lon2) {
107
        function deg2rad(deg) {
108
            return deg * (Math.PI/180)
109
        }
110
111
        var R = 6371; // Radius of the earth in km
112
        var dLat = deg2rad(lat2-lat1);  // deg2rad below
113
        var dLon = deg2rad(lon2-lon1); 
114
        var a = 
115
        Math.sin(dLat/2) * Math.sin(dLat/2) +
116
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
117
        Math.sin(dLon/2) * Math.sin(dLon/2)
118
        ; 
119
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
120
        var d = R * c; // Distance in km
121
        return d;
122
    },
123
124
    cityCoordinates: function cityCoordinates(cityName) {
125
        const cities = {
126
            'Stockholm': {latitude: 59.325025453165885, longitude: 18.067812149589304},
127
            'Halmstad': {latitude: 56.674283063446495, longitude: 12.857826360096537},
128
            'Karlskrona': {latitude: 56.16116530651073, longitude: 15.586898701061049}
129
        };
130
131
        return cities[cityName]
132
    }
133
};
134
135
export default mapModel;