-
Notifications
You must be signed in to change notification settings - Fork 0
/
MapLibre.java
254 lines (225 loc) · 8.09 KB
/
MapLibre.java
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
package org.vaadin.addons.maplibre;
import com.vaadin.flow.component.HasSize;
import com.vaadin.flow.component.HasStyle;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.dependency.StyleSheet;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.VelocityContext;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.vaadin.addons.velocitycomponent.AbstractVelocityJsComponent;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
/**
* A Java/Vaadin API for MapLibre GL JS.
*/
@Tag("div")
public class MapLibre extends AbstractVelocityJsComponent implements HasSize, HasStyle {
private Coordinate center = new Coordinate(0, 0);
private int zoomLevel = 15;
public MapLibre(URI styleUrl) {
init(null, styleUrl.toString());
}
public MapLibre(String styleUrl) {
init(null, styleUrl);
}
public MapLibre(InputStream styleJson) {
try {
init(IOUtils.toString(styleJson, Charset.defaultCharset()), null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void init(String styleJson, String styleUrl) {
loadMapLibreJs();
setId("map");
setWidth("800px");
setHeight("500px");
jsTemplate("org/vaadin/addons/maplibre/mapinit.js", Map.of(
"style", styleJson == null ? "null" : styleJson, // Map.of is not nullsafe :-(
"styleUrl", styleUrl == null ? "null" : styleUrl
));
}
/**
* Loads the MapLibre JS library to the host page.
* Not using @JavaScript annotation, as not all users
* necessarily want to use the unpkg.com CDN.
*
* <p>Override if you want for example
* to load it from a local file instead of from unpkg.com.</p>
*/
protected void loadMapLibreJs() {
UI ui = getUI().orElse(UI.getCurrent());
boolean loaded = ui.getElement().getProperty("maplibre-loaded", false);
if(!loaded) {
final String version = "3.2.2";
ui.getPage().addJavaScript("https://unpkg.com/maplibre-gl@v%s/dist/maplibre-gl.js".formatted(version));
ui.getPage().addStyleSheet("https://unpkg.com/maplibre-gl@v%s/dist/maplibre-gl.css".formatted(version));
ui.getElement().setProperty("maplibre-loaded", true);
}
}
public Integer getZoomLevel() {
return 15;
}
public Coordinate getCenter() {
return center;
}
public String getMapStyle() {
try {
String s = IOUtils.resourceToString("/kiinteistojaotus-taustakartalla.json", Charset.defaultCharset());
return s;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void addSource(String name, Geometry geometry) {
js("""
map.addSource('$name', {
'type': 'geojson',
'data': $GeoJsonHelper.toJs($geometry)
});
""", Map.of("name", name, "geometry", geometry));
}
public Layer addLineLayer(Geometry geometry, LinePaint linePaint) {
String id = UUID.randomUUID().toString();
addSource(id, geometry);
return addLineLayer(id, id, null, linePaint, geometry);
}
public Layer addFillLayer(Polygon polygon, FillPaint style) {
String id = UUID.randomUUID().toString();
addSource(id, polygon);
return addFillLayer(id, id, null, style, polygon);
}
protected Layer addFillLayer(String name, String source, String sourceLayer, FillPaint paintJson, Geometry geom) {
if(sourceLayer == null) {
sourceLayer = "";
} else {
sourceLayer = "'source-layer': '%s',".formatted(sourceLayer);
}
js("""
map.addLayer({
'id': '%s',
'type': 'fill',
'source': '%s',
%s
'layout': {},
'paint': %s
});
""".formatted(name, source, sourceLayer, paintJson), Collections.emptyMap());
return new Layer(this, name, geom);
}
protected Layer addLineLayer(String name, String source, String sourceLayer, LinePaint paint, Geometry geom) {
if(sourceLayer == null) {
sourceLayer = "";
} else {
sourceLayer = "'source-layer': '%s',".formatted(sourceLayer);
}
js("""
map.addLayer({
'id': '$name',
'type': 'line',
'source': '$source',
$sourceLayer
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': $paint
});
""", Map.of("name", name, "source", source, "sourceLayer", sourceLayer, "paint", paint));
return new Layer(this, name, geom);
}
public void removeLayer(Layer layer) {
if (layer instanceof Marker m) {
js("""
component.markers['$id'].remove();
""", Map.of("id", m.id));
} else {
js("""
map.removeLayer('$id');
map.removeSource('$id');
""", Map.of("id", layer.id));
}
}
public void addSource(String name, String sourceDeclarationJson) {
js("""
map.addSource('$name', $sourceDeclarationJson);
""", Map.of("name", name, "sourceDeclarationJson", sourceDeclarationJson));
}
public Marker addMarker(double x, double y) {
String id = UUID.randomUUID().toString();
js("""
component.markers = component.markers || {};
component.markers['$id'] = new maplibregl.Marker()
.setLngLat([$x, $y])
.addTo(map);
""", Map.of("id", id, "x", x, "y", y));
return new Marker(this, id, new Coordinate(x, y));
}
@Override
protected VelocityContext getVelocityContext() {
VelocityContext velocityContext = super.getVelocityContext();
velocityContext.put("GeoJsonHelper", GeoJsonHelper.class);
return velocityContext;
}
public void setCenter(double x, double y) {
this.center = new Coordinate(x, y);
js("map.setCenter($GeoJsonHelper.toJs($this.center));");
}
public void setZoomLevel(int zoomLevel) {
this.zoomLevel = zoomLevel;
js("map.setZoom($this.zoomLevel);");
}
public void fitTo(Geometry geom, double padding) {
Envelope envelope = geom.getEnvelopeInternal();
envelope.expandBy(padding);
js("""
const bounds = new maplibregl.LngLatBounds(
[%s, %s], [%s, %s]);;
map.fitBounds(bounds);
""".formatted(envelope.getMinX(), envelope.getMinY(), envelope.getMaxX(), envelope.getMaxY()));
}
public void flyTo(double x, double y, double zoom) {
js("""
map.flyTo({
center: [%s, %s],
zoom: %s
});
""".formatted(x, y, zoom));
}
/**
* Executes given JS in the context of the map component,
* either right away, or right after initial loading is done.
* @param js the JS to execute, map and component variables are initialized automatically.
*/
protected void js(String js, Map<String, Object> variables) {
velocityJs("""
const map = this.map;
const component = this;
const action = () => {
%s
};
if(!this.styleloaded) {
map.on('load', action);
} else {
action();
}
""".formatted(js), variables);
}
protected void js(String js) {
js(js, Collections.emptyMap());
}
public void flyTo(Geometry geometry, int i) {
Point centroid = geometry.getCentroid();
flyTo(centroid.getX(), centroid.getY(), i);
}
}