Blame view

src/main/kotlin/map/LeafletMapView.kt 13.6 KB
53f01ecc3   lsagona   display message o...
1
  package map
d06a68ec6   lsagona   add Leaflet Kotli...
2

d06a68ec6   lsagona   add Leaflet Kotli...
3
4
5
6
7
8
  import javafx.concurrent.Worker
  import javafx.scene.layout.StackPane
  import javafx.scene.paint.Color
  import javafx.scene.shape.Polygon
  import javafx.scene.web.WebEngine
  import javafx.scene.web.WebView
53f01ecc3   lsagona   display message o...
9
  import map.events.*
d06a68ec6   lsagona   add Leaflet Kotli...
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
  import netscape.javascript.JSObject
  import java.io.ByteArrayOutputStream
  import java.io.File
  import java.io.IOException
  import java.net.URL
  import java.util.*
  import java.util.concurrent.CompletableFuture
  import javax.imageio.ImageIO
  
  
  /**
   * JavaFX component for displaying OpenStreetMap based maps by using the Leaflet.js JavaScript library inside a WebView
   * browser component.<br/>
   * This component can be embedded most easily by placing it inside a StackPane, the component uses then the size of the
   * parent automatically.
   *
   * @author Stefan Saring
   * @author Niklas Kellner
   */
  class LeafletMapView : StackPane() {
  
      private val webView = WebView()
      private val webEngine: WebEngine = webView.engine
  
      private var varNameSuffix: Int = 1
      private val mapClickEvent = MapClickEventMaker()
      private val markerClickEvent = MarkerClickEventMaker()
      private val mapMoveEvent = MapMoveEventMaker()
      internal val zoomLimitSmallMarker = 8
  
      /**
       * Creates the LeafletMapView component, it does not show any map yet.
       */
      init {
          this.children.add(webView)
      }
  
      /**
       * Displays the initial map in the web view. Needs to be called and complete before adding any markers or tracks.
       * The returned CompletableFuture will provide the final map load state, the map can be used when the load has
       * completed with state SUCCEEDED (use CompletableFuture#whenComplete() for waiting to complete).
       *
       * @param mapConfig configuration of the map layers and controls
       * @return the CompletableFuture which will provide the final map load state
       */
      fun displayMap(mapConfig: MapConfig): CompletableFuture<Worker.State> {
          val finalMapLoadState = CompletableFuture<Worker.State>()
  
          webEngine.loadWorker.stateProperty().addListener { _, _, newValue ->
  
              if (newValue == Worker.State.SUCCEEDED) {
                  executeMapSetupScripts(mapConfig)
              }
  
              if (newValue == Worker.State.SUCCEEDED || newValue == Worker.State.FAILED) {
                  finalMapLoadState.complete(newValue)
              }
          }
  
          val localFileUrl: URL = LeafletMapView::class.java.getResource("/leafletmap/leafletmap.html")
          webEngine.load(localFileUrl.toExternalForm())
          return finalMapLoadState
      }
  
      private fun executeMapSetupScripts(mapConfig: MapConfig) {
  
          // execute scripts for layer definition
          mapConfig.layers.forEachIndexed { i, layer ->
              execScript("var layer${i + 1} = ${layer.javaScriptCode};")
          }
  
          val jsLayers = mapConfig.layers
53f01ecc3   lsagona   display message o...
82
83
              .mapIndexed { i, layer -> "'${layer.displayName}': layer${i + 1}" }
              .joinToString(", ")
d06a68ec6   lsagona   add Leaflet Kotli...
84
85
86
          execScript("var baseMaps = { $jsLayers };")
  
          // execute script for map view creation (Leaflet attribution must not be a clickable link)
53f01ecc3   lsagona   display message o...
87
88
          execScript(
              """
d06a68ec6   lsagona   add Leaflet Kotli...
89
90
                  |var myMap = L.map('map', {
                  |    center: new L.LatLng(${mapConfig.initialCenter.latitude}, ${mapConfig.initialCenter.longitude}),
79b001037   lsagona   heat map
91
                  |    zoom: 1,
d06a68ec6   lsagona   add Leaflet Kotli...
92
93
94
                  |    zoomControl: false,
                  |    layers: [layer1]
                  |});
43370abfe   lsagona   clear map canvas ...
95
                  |L.control.scale().addTo(myMap);
78935bd62   lsagona   slider bind to al...
96
                  |var markers = []
9e952e84e   lsagona   add message clust...
97
                  |var myRenderer = L.canvas({ padding: 0.5 });
79b001037   lsagona   heat map
98
99
                  |var markerClusters = L.markerClusterGroup({spiderfyOnMaxZoom: false, disableClusteringAtZoom: 10});
                  |var heatLayer = L.heatLayer([]).addTo(myMap);""".trimMargin()
53f01ecc3   lsagona   display message o...
100
101
102
          )
  
  //        eventZoomChangeIcon()
d06a68ec6   lsagona   add Leaflet Kotli...
103
104
105
  
          // execute script for layer control definition if there are multiple layers
          if (mapConfig.layers.size > 1) {
53f01ecc3   lsagona   display message o...
106
107
              execScript(
                  """
d06a68ec6   lsagona   add Leaflet Kotli...
108
                      |var overlayMaps = {};
53f01ecc3   lsagona   display message o...
109
110
                      |L.control.layers(baseMaps, overlayMaps).addTo(myMap);""".trimMargin()
              )
d06a68ec6   lsagona   add Leaflet Kotli...
111
112
113
114
115
  
          }
  
          // execute script for scale control definition
          if (mapConfig.scaleControlConfig.show) {
53f01ecc3   lsagona   display message o...
116
117
118
119
120
121
              execScript(
                  "L.control.scale({position: '${mapConfig.scaleControlConfig.position.positionName}', " +
                          "metric: ${mapConfig.scaleControlConfig.metric}, " +
                          "imperial: ${!mapConfig.scaleControlConfig.metric}})" +
                          ".addTo(myMap);"
              )
d06a68ec6   lsagona   add Leaflet Kotli...
122
123
124
125
          }
  
          // execute script for zoom control definition
          if (mapConfig.zoomControlConfig.show) {
53f01ecc3   lsagona   display message o...
126
127
128
129
              execScript(
                  "L.control.zoom({position: '${mapConfig.zoomControlConfig.position.positionName}'})" +
                          ".addTo(myMap);"
              )
d06a68ec6   lsagona   add Leaflet Kotli...
130
131
132
133
134
135
136
137
138
139
          }
      }
  
      /**
       * Sets the view of the map to the specified geographical center position and zoom level.
       *
       * @param position map center position
       * @param zoomLevel zoom level (0 - 19 for OpenStreetMap)
       */
      fun setView(position: LatLong, zoomLevel: Int) =
53f01ecc3   lsagona   display message o...
140
          execScript("myMap.setView([${position.latitude}, ${position.longitude}], $zoomLevel);")
d06a68ec6   lsagona   add Leaflet Kotli...
141
142
143
144
145
146
147
  
      /**
       * Pans the map to the specified geographical center position.
       *
       * @param position map center position
       */
      fun panTo(position: LatLong) =
53f01ecc3   lsagona   display message o...
148
          execScript("myMap.panTo([${position.latitude}, ${position.longitude}]);")
d06a68ec6   lsagona   add Leaflet Kotli...
149
150
151
152
153
154
155
  
      /**
       * Sets the zoom of the map to the specified level.
       *
       * @param zoomLevel zoom level (0 - 19 for OpenStreetMap)
       */
      fun setZoom(zoomLevel: Int) =
53f01ecc3   lsagona   display message o...
156
          execScript("myMap.setZoom([$zoomLevel]);")
d06a68ec6   lsagona   add Leaflet Kotli...
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
  
      /**
       * Adds a Marker Object to a map
       *
       * @param marker the Marker Object
       */
      fun addMarker(marker: Marker) {
          marker.addToMap(getNextMarkerName(), this)
      }
  
      fun addCircle(circle: Circle) {
          circle.addToMap(this)
      }
  
      fun addZone(zone: Zone) {
          zone.addToMap(this)
      }
  
      /**
       * Removes an existing marker from the map
       *
       * @param marker the Marker object
       */
      fun removeMarker(marker: Marker) {
          execScript("myMap.removeLayer(${marker.getName()});")
      }
  
      fun removeCircle(circle: Circle) {
          circle.removeCircle(this)
      }
  
      fun removeZone(zone: Zone) {
          zone.removeZone()
      }
  
      fun removeZone(id: String) {
          val idSanitized = id.replace("-", "")
          execScript("myMap.removeLayer(polygon$idSanitized);")
      }
  
  
      fun uppdateCircle(circle: Circle, latLong: LatLong, radius: Double) {
          circle.modifyCircle(latLong, radius)
          circle.uppdateMap()
      }
  
      fun setEventMousePosition() {
53f01ecc3   lsagona   display message o...
204
205
206
207
208
209
210
211
212
213
          execScript(
              "var lat=0.0, lng=0.0;
  " +
                      "myMap.addEventListener('mousemove', function(ev) {
  " +
                      "   lat = ev.latlng.lat;
  " +
                      "   lng = ev.latlng.lng;
  " +
                      "});"
d06a68ec6   lsagona   add Leaflet Kotli...
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
          )
      }
  
      fun getMousePosition(): LatLong {
          val lat = execScript("lat;") as Double
          val lng = execScript("lng;") as Double
          return LatLong(lat, lng)
      }
  
      /**
       * Adds a custom marker type
       *
       * @param markerName the name of the marker type
       * @param iconUrl the url if the marker icon
       */
      fun addCustomMarker(markerName: String, iconUrl: String): String {
53f01ecc3   lsagona   display message o...
230
231
232
233
234
235
236
237
238
239
240
          execScript(
              "var $markerName = L.icon({
  " +
                      "iconUrl: '${createImage(iconUrl, "png")}',
  " +
                      "iconSize: [24, 24],
  " +
                      "iconAnchor: [12, 12],
  " +
                      "});"
          )
d06a68ec6   lsagona   add Leaflet Kotli...
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
          return markerName
      }
  
      private fun createImage(path: String, type: String): String {
          val image = ImageIO.read(File(path))
          var imageString: String? = null
          val bos = ByteArrayOutputStream()
  
          try {
              ImageIO.write(image, type, bos)
              val imageBytes = bos.toByteArray()
  
              val encoder = Base64.getEncoder()
              imageString = encoder.encodeToString(imageBytes)
  
              bos.close()
          } catch (e: IOException) {
              e.printStackTrace()
          }
          return "data:image/$type;base64,$imageString"
      }
  
      /**
       * Sets the onMarkerClickListener
       *
       * @param listener the onMarerClickEventListener
       */
      fun onMarkerClick(listener: MarkerClickEventListener) {
          val win = execScript("document") as JSObject
          win.setMember("java", this)
          markerClickEvent.addListener(listener)
      }
  
      /**
       * Handles the callback from the markerClickEvent
       */
      fun markerClick(title: String) {
          markerClickEvent.MarkerClickEvent(title)
      }
  
      /**
       * Sets the onMapMoveListener
       *
       * @param listener the MapMoveEventListener
       */
      fun onMapMove(listener: MapMoveEventListener) {
          val win = execScript("document") as JSObject
          win.setMember("java", this)
          execScript("myMap.on('moveend', function(e){ document.java.mapMove(myMap.getCenter().lat, myMap.getCenter().lng);});")
          mapMoveEvent.addListener(listener)
      }
  
      /**
       * Handles the callback from the mapMoveEvent
       */
      fun mapMove(lat: Double, lng: Double) {
          val latlng = LatLong(lat, lng)
          mapMoveEvent.MapMoveEvent(latlng)
      }
  
      /**
       * Sets the onMapClickListener
       *
       * @param listener the onMapClickEventListener
       */
      fun onMapClick(listener: MapClickEventListener) {
          val win = execScript("document") as JSObject
          win.setMember("java", this)
          execScript("myMap.on('click', function(e){ document.java.mapClick(e.latlng.lat, e.latlng.lng);});")
          mapClickEvent.addListener(listener)
      }
  
      /**
       * Handles the callback from the mapClickEvent
       */
      fun mapClick(lat: Double, lng: Double) {
          val latlng = LatLong(lat, lng)
          mapClickEvent.MapClickEvent(latlng)
      }
  
      /**
       * Draws a track path along the specified positions.
       *
       * @param positions list of track positions
       */
      fun addTrack(positions: List<LatLong>) {
  
          val jsPositions = positions
53f01ecc3   lsagona   display message o...
329
330
331
              .map { "    [${it.latitude}, ${it.longitude}]" }
              .joinToString(", 
  ")
d06a68ec6   lsagona   add Leaflet Kotli...
332

53f01ecc3   lsagona   display message o...
333
334
          execScript(
              """
d06a68ec6   lsagona   add Leaflet Kotli...
335
336
337
              |var latLngs = [
              |$jsPositions
              |];
53f01ecc3   lsagona   display message o...
338
339
340
341
342
343
344
345
346
347
              |var polyline = L.polyline(latLngs, {color: 'red', weight: 2}).addTo(myMap);""".trimMargin()
          )
      }
  
      fun clearAllLayer() {
          execScript("""
              myMap.eachLayer(function (layer) {
                  map.removeLayer(layer);
              });
          """.trimIndent())
d06a68ec6   lsagona   add Leaflet Kotli...
348
349
350
351
352
      }
  
      fun addTrack(positions: List<LatLong>, id: String, color: Color, tooltip: String) {
  
          val jsPositions = positions
53f01ecc3   lsagona   display message o...
353
354
355
              .map { "    [${it.latitude}, ${it.longitude}]" }
              .joinToString(", 
  ")
d06a68ec6   lsagona   add Leaflet Kotli...
356
357
  
          val cleanTooltip = tooltip.replace("'", "&apos;")
53f01ecc3   lsagona   display message o...
358
359
          execScript(
              """
d06a68ec6   lsagona   add Leaflet Kotli...
360
361
362
              |var latLngs = [
              |$jsPositions
              |];
53f01ecc3   lsagona   display message o...
363
364
365
366
              |var color = "rgb(${Math.floor(color.getRed() * 255).toInt()} ,${Math.floor(color.getGreen() * 255)
                  .toInt()},${Math.floor(color.getBlue() * 255).toInt()})";
              |var polyline$id = L.polyline(latLngs, {color: color, weight: 2, zIndexOffset: 200}).bindTooltip('$cleanTooltip', {sticky: true}).addTo(trackGroup)""".trimMargin()
          )
d06a68ec6   lsagona   add Leaflet Kotli...
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
      }
  
      fun makeVesselTrackTransparent(id: String) {
          execScript("polyline$id.setStyle({opacity: 0.5});")
      }
  
      fun highlightTrack(id: String) {
          execScript("polyline$id.setStyle({weight: 4});")
      }
  
      fun normalizeVesselTrack(id: String) {
          execScript("polyline$id.setStyle({opacity: 1,weight: 2});")
      }
  
      fun eventZoomChangeIcon() {
53f01ecc3   lsagona   display message o...
382
383
          execScript(
              """
d06a68ec6   lsagona   add Leaflet Kotli...
384
385
386
387
388
389
390
391
392
393
394
395
              |myMap.on('zoomend', function() {
                  |var currentZoom = myMap.getZoom();
                  |if (currentZoom < $zoomLimitSmallMarker) {
                      |markersGroup.eachLayer(function(layer) {
                          return layer.setIcon(aircraftSmallIcon)
                      |});
                  |} else {
                      |markersGroup.eachLayer(function(layer) {
                          return layer.setIcon(aircraftIcon)
                      |});
                  |}
              |});
53f01ecc3   lsagona   display message o...
396
397
          """.trimMargin()
          )
d06a68ec6   lsagona   add Leaflet Kotli...
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
      }
  
      fun removeTrack(id: String) {
          execScript("myMap.removeLayer(polyline$id);")
      }
  
      fun fitBoundsMarkers() {
          execScript("setTimeout(() => {myMap.fitBounds(markersGroup.getBounds().pad(0.05));}, 500);")
      }
  
      fun addZone(polygon: Polygon, id: String, color: Color) {
          val points = polygon.points
          val latLongs = arrayListOf<LatLong>()
          var lat: Double
          var lon = 0.0
  
          for (i in 0 until points.size) {
              if (i % 2 == 0) {
                  lon = points[i]
              } else {
                  lat = points[i]
                  latLongs.add(LatLong(lat, lon))
              }
          }
  
          val jsPositions = latLongs
53f01ecc3   lsagona   display message o...
424
425
426
              .map { "    [${it.latitude}, ${it.longitude}]" }
              .joinToString(", 
  ")
d06a68ec6   lsagona   add Leaflet Kotli...
427
          val idSanitized = id.replace("-", "")
53f01ecc3   lsagona   display message o...
428
429
          execScript(
              """
d06a68ec6   lsagona   add Leaflet Kotli...
430
431
432
              |var latLngs = [
              |$jsPositions
              |];
53f01ecc3   lsagona   display message o...
433
434
435
436
              |var color = "rgb(${Math.floor(color.getRed() * 255).toInt()} ,${Math.floor(color.getGreen() * 255)
                  .toInt()},${Math.floor(color.getBlue() * 255).toInt()})";
              |var polygon$idSanitized = L.polygon(latLngs, {color: color}).addTo(myMap);""".trimMargin()
          )
d06a68ec6   lsagona   add Leaflet Kotli...
437
438
439
440
441
442
443
  
      }
  
      internal fun execScript(script: String) = webEngine.executeScript(script)
  
      private fun getNextMarkerName(): String = "marker${varNameSuffix++}"
  }