aboutsummaryrefslogtreecommitdiffstats
path: root/sdnr/wt/odlux/apps/lineOfSightApp/src/components/map.tsx
blob: 6f29d5993e49024ab8eade9257c4c4984e46da5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/**
 * ============LICENSE_START========================================================================
 * ONAP : ccsdk feature sdnr wt odlux
 * =================================================================================================
 * Copyright (C) 2021 highstreet technologies GmbH Intellectual Property. All rights reserved.
 * =================================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 * ============LICENSE_END==========================================================================
 */

import * as React from 'react'
import * as mapboxgl from 'mapbox-gl';
import { render } from 'react-dom';
import { RouteComponentProps, withRouter } from 'react-router-dom';
import { IApplicationStoreState } from '../../../../framework/src/store/applicationStore';
import connect, { Connect, IDispatcher } from '../../../../framework/src/flux/connect';
import { OSM_STYLE, URL_BASEPATH } from '../config';
import { GPSProfileResult } from '../model/GPSProfileResult';
import MapContextMenu from './mapContextMenu';
import { getGPSProfile } from '../services/heightService';
import { max, min } from '../utils/math';
import { HeightChart } from './heightChart';
import { makeStyles } from '@material-ui/core';
import { ClearSavedChartAction, SetChartAction, SetEndpointAction, SetHeightA, SetHeightB, SetMapCenterAction, SetStartPointAction } from '../actions/mapActions';
import { LatLon } from '../model/LatLon';
import MapInfo from './mapInfo';
import { Height } from 'model/Height';
import { PictureAsPdf } from '@material-ui/icons';
import ConnectionErrorPoup from './ConnectionErrorPoup';
import { addBaseLayer, addBaseSource, addPoint } from '../utils/map';
import { SetReachableAction } from '../actions/commonActions';

import 'mapbox-gl/dist/mapbox-gl.css';

type mapProps = RouteComponentProps & Connect<typeof mapStateToProps, typeof mapDispatchToProps>;

const mapStateToProps = (state: IApplicationStoreState) => ({
    center: state.lineOfSight.map.center,
    zoom: state.lineOfSight.map.zoom,
    start: state.lineOfSight.map.start,
    end: state.lineOfSight.map.end,
    heightA: state.lineOfSight.map.heightA,
    heightB: state.lineOfSight.map.heightB,
    ready: state.lineOfSight.map.ready
});

const mapDispatchToProps = (dispatcher: IDispatcher) => ({
  ClearChartAction: () => dispatcher.dispatch(new ClearSavedChartAction),
  SetMapPosition: (point: LatLon, zoom: number) => dispatcher.dispatch(new SetMapCenterAction(point, zoom)),
  SetHeightStart: (height: Height) => dispatcher.dispatch(new SetHeightA(height)),
  SetHeightEnd: (height: Height) => dispatcher.dispatch(new SetHeightB(height)),
  setStartPosition: (position: LatLon|null) => dispatcher.dispatch(new SetStartPointAction(position)),
  setEndPosition: (position: LatLon|null) => dispatcher.dispatch(new SetEndpointAction(position)),
  setReachable : (reachable: boolean |null) => dispatcher.dispatch(new SetReachableAction(reachable)),

  

})


let map: mapboxgl.Map;

const styles = makeStyles({
    chart: {
        position: "absolute",
        top: 0,
        bottom: 0,
        left: 0,
        right: 0
      
    }
  });


const Map: React.FC<mapProps> = (props) => {

  //const [start, setStart] = React.useState<mapboxgl.LngLat| undefined>();
  //const [end, setEnd] = React.useState<mapboxgl.LngLat| undefined>();
  const [data, setData] = React.useState<GPSProfileResult[] | number>(Number.NaN);
  const [dataMin, setDataMin] = React.useState<GPSProfileResult|undefined>();
  const [dataMax, setDataMax] = React.useState<GPSProfileResult|undefined>();
  const [isMapLoaded, setMapLoaded] = React.useState<boolean>(false);


const mapRef = React.useRef<{ map: mapboxgl.Map | null }>({ map: null });
const mapContainerRef = React.useRef<HTMLDivElement>(null);



const classes = styles();

const heightA = props.heightA !== null ? props.heightA.amsl +  props.heightA.antennaHeight : 0;
const heightB = props.heightB !== null ? props.heightB.amsl +  props.heightB.antennaHeight : 0;

const {start, end} = props;

const handleResize = () =>{

    if (map) {
        // wait a moment until resizing actually happened
        window.setTimeout(() => map.resize(), 500);
    }

}

//on mount
React.useEffect(()=>{

    window.addEventListener("menu-resized", handleResize);
    
   
    return () =>{
      console.log("unmount")
        window.removeEventListener("menu-resized", handleResize);

        const center = mapRef.current.map?.getCenter();
        const mapZoom = mapRef.current.map?.getZoom();
        if(center){
          props.SetMapPosition({latitude: center.lat, longitude:center.lng}, mapZoom!);
        }

        props.setReachable(null);
    }

},[]);


    React.useEffect(()=>{

        if(props.ready){
            setupMap();
        }

    },[props.ready]);

    React.useEffect(() => {
        if (props.ready && isMapLoaded) {
          drawChart();
          updateLosUrl();
        }

      }, [start, end, isMapLoaded]);

    const drawChart = () =>{
      if(start && end){

        addBaseSource(map, 'route');
        addBaseLayer(map, 'route');

        const json = `{
          "type": "Feature",
          "properties": {},
          "geometry": {
            "type": "LineString",
            "coordinates": [
              [${start.longitude}, ${start.latitude}],
              [${end.longitude}, ${end.latitude}]
            ]}
          }`;
         
          
  
        (map.getSource("route") as mapboxgl.GeoJSONSource).setData(JSON.parse(json));
          
  
        getGPSProfile({ latitude: start.latitude, longitude: start.longitude }, { latitude: end.latitude, longitude: end.longitude }).then(data => {
          if (Array.isArray(data)) {
            setDataMin(min(data, d => d.height));
            setDataMax(max(data, d => d.height));
          }
          setData(data);
        });
      } 
      else if (start || end){

        const point = start!==null ? start: end!;
        addBaseSource(map, 'route');
        addBaseLayer(map, 'route');
        addPoint(map, point);

      }
      else {
        //delete layers and source
        //used instead of clearing source data because it has better performance 
        //(setting data to empty results in a noticable lag of line being cleared)
        mapRef.current.map?.getLayer('line') && mapRef.current.map?.removeLayer('line') && mapRef.current.map?.removeLayer('points') && mapRef.current.map?.removeSource('route');
      
      }
    }

    const updateLosUrl = () =>{

      if(start && end){
        
        const locationPart = `lat1=${start.latitude}&lon1=${start.longitude}&lat2=${end.latitude}&lon2=${end.longitude}`;

        let heightPart = '';

        if(props.heightA && props.heightB){
        heightPart = `&amslA=${props.heightA.amsl}&antennaHeightA=${props.heightA.antennaHeight}&amslB=${props.heightB.amsl}&antennaHeightB=${props.heightB.antennaHeight}`;
          
        }
          
        props.history.replace(`/${URL_BASEPATH}/los?${locationPart}${heightPart}`)
            
      }else if(!start && !end){
        props.history.replace(`/${URL_BASEPATH}`);
      }
    }

    
    const updateHeightA = (value:number, value2: number) =>{
      props.SetHeightStart({amsl: value, antennaHeight: value2});
    }

    const updateHeightB = (value:number, value2: number) =>{
      props.SetHeightEnd({amsl: value, antennaHeight: value2});
    }

    const OnEndPosition = (position: mapboxgl.LngLat) =>{
      props.setEndPosition({latitude: position.lat, longitude: position.lng})
    }

    const OnStartPosition = (position: mapboxgl.LngLat) =>{
      props.setStartPosition({latitude: position.lat, longitude: position.lng})
    }
    

    const setupMap = () => {

        let lat = props.center.latitude
        let lon = props.center.longitude;
        let zoom = props.zoom;

        map = new mapboxgl.Map({
            container: mapContainerRef.current!,
            style: OSM_STYLE as any,
            center: [lon, lat],
            zoom: zoom,
            accessToken: ''
        });

        mapRef.current.map = map;

        map.on('load', (ev) => {

            map.setMaxZoom(18);
            setMapLoaded(true);
           
            //add source, layer

            addBaseSource(map, 'route');
            addBaseLayer(map, 'route');

            });

            let currentPopup: mapboxgl.Popup | null = null;
            map.on('contextmenu', (e) => {

              if (currentPopup)
                currentPopup.remove();

                //change height if start/end changes
                //???  -> show value? / reset after chart display?
          
                const popupNode = document.createElement("div");
                render(
                  <MapContextMenu pos={e.lngLat}
                    onStart={(p) => { OnStartPosition(p); if (currentPopup) currentPopup.remove(); }}
                    onEnd={(p) => { OnEndPosition(p); if (currentPopup) currentPopup.remove(); }}
                    onHeightA={(p,p1)=> updateHeightA(p, p1)}
                    onHeightB={(p, p1)=> updateHeightB(p, p1)} />,
                  popupNode);
          
                currentPopup = new mapboxgl.Popup()
                  .setLngLat(e.lngLat)
                  .setDOMContent(popupNode)
                  .addTo(map);
              });

            map.on('moveend', mapMoveEnd);
               
        };

        const mapMoveEnd = () =>{
        const mapZoom = Number(map.getZoom().toFixed(2));
        const lat = Number(map.getCenter().lat.toFixed(4));
        const lon = Number(map.getCenter().lng.toFixed(4));

        props.SetMapPosition({latitude: lat, longitude: lon}, mapZoom);
        
        }
    


    return <>
    <div id="map" style={{ width: "100%", height:'100%', position: 'relative' }} ref={mapContainerRef} >
    <MapInfo minHeight={dataMin} maxHeight={dataMax}  />
    <ConnectionErrorPoup reachable={props.ready} />
    
    {typeof data === "object"
        ? (
          < div className={classes.chart} onClick={() => {
            setData(Number.NaN);
            setDataMax(undefined);
            setDataMin(undefined);
            props.ClearChartAction();
          }}>
            <HeightChart heightPosA={heightA} heightPosB={heightB} width={mapContainerRef.current?.clientWidth!} height={mapContainerRef.current?.clientHeight!} data={data} dataMin={dataMin!} dataMax={dataMax!} />
          </div>
        )
        : null
      }

        </div>
        </>
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Map));