-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
290 lines (266 loc) · 10.4 KB
/
main.js
File metadata and controls
290 lines (266 loc) · 10.4 KB
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
// main.js: Alpine.js glue for Plot Finder
import {formatCoords, formatDistance, createMap, watchUserPosition} from './utils.js';
import {fetchParcelById, fetchParcelByXY, wktToGeoJSON, drawParcel, findNearestVertex, measureEdges} from './data.js';
document.addEventListener('alpine:init', () => {
Alpine.data('plotFinderApp', () => ({
map: null,
tileLayer: null,
darkMode: window.matchMedia('(prefers-color-scheme: dark)').matches,
searchId: '300301_1.0001.AR_19.85',
showSearchModal: false,
enableMapClickSearch: true,
autoCenter: true,
showEdges: false,
showAccuracyCircle: false,
error: '',
userPosition: null,
parcel: null,
derived: null,
userMarker: null,
watchId: null,
parcelLayer: null,
vertexLine: null,
edgeLines: [],
init() {
this.map = createMap(this.darkMode);
this.initGeolocation();
this.map.on('click', e => this.onMapClick(e));
this.$watch('showEdges', () => this.updateDerived());
this.$watch('showAccuracyCircle', () => this.initGeolocation());
},
initGeolocation() {
if (this.watchId) {
navigator.geolocation.clearWatch(this.watchId);
}
this.watchId = watchUserPosition(this.map, this.showAccuracyCircle, (pos, marker) => {
this.userPosition = pos;
this.userMarker = marker;
if (this.autoCenter) {
this.map.setView([pos.lat, pos.lng], this.map.getZoom());
}
this.updateDerived();
}, err => {
this.error = err;
});
},
toggleAutoCenter() {
this.autoCenter = !this.autoCenter;
if (this.autoCenter && this.userPosition) {
this.map.setView([this.userPosition.lat, this.userPosition.lng], this.map.getZoom());
}
},
async searchParcelById() {
this.error = '';
if (!this.searchId) {
this.error = 'Podaj identyfikator działki.';
return;
}
try {
const data = await fetchParcelById(this.searchId);
if (!data || !data.geom_wkt) throw new Error('Brak działki o podanym ID.');
this.setParcelFromULDK(data);
} catch (e) {
this.error = 'Nie udało się pobrać działki: ' + (e.message || e);
this.clearParcel();
}
},
async onMapClick(e) {
if (!this.enableMapClickSearch) return;
this.error = '';
const lng = e.latlng.lng.toFixed(7);
const lat = e.latlng.lat.toFixed(7);
try {
const data = await fetchParcelByXY(lng, lat);
if (!data || !data.geom_wkt) throw new Error('Brak działki pod wskazanym punktem.');
this.setParcelFromULDK(data);
} catch (e) {
this.error = 'Nie udało się pobrać działki: ' + (e.message || e);
this.clearParcel();
}
},
setParcelFromULDK(result) {
this.parcel = {
id: result.id,
geomWkt: result.geom_wkt,
region: result.region,
county: result.county,
commune: result.commune,
voivodeship: result.voivodeship,
datasource: result.datasource
};
const geo = wktToGeoJSON(result.geom_wkt);
if (!geo) {
this.error = 'Nieprawidłowa geometria działki.';
return;
} else {
console.log('geo', geo);
}
this.searchId = this.parcel.id;
// Calculate unique coordinates once and store them
const coords = geo.coordinates[0];
const uniqueCoords = coords[0][0] === coords[coords.length - 1][0] &&
coords[0][1] === coords[coords.length - 1][1] ?
coords.slice(0, -1) : coords;
this.parcel.uniqueCoords = uniqueCoords;
this.parcel.vertexCount = uniqueCoords.length;
this.parcelLayer = drawParcel(this.map, geo);
this.updateDerived();
},
clearParcel() {
this.parcel = null;
if (this.parcelLayer) {
this.map.removeLayer(this.parcelLayer);
this.parcelLayer = null;
}
if (this.vertexLine) {
this.map.removeLayer(this.vertexLine);
this.vertexLine = null;
}
if (this.edgeLines) this.edgeLines.forEach(l => this.map.removeLayer(l));
this.edgeLines = [];
if (this.map._vertexMarkers) {
this.map._vertexMarkers.forEach(m => this.map.removeLayer(m));
this.map._vertexMarkers = [];
}
if (this.map._edgeProjectionMarkers) {
this.map._edgeProjectionMarkers.forEach(m => this.map.removeLayer(m));
this.map._edgeProjectionMarkers = [];
}
this.derived = null;
},
updateDerived() {
if (!this.parcel || !this.userPosition) {
this.derived = null;
if (this.vertexLine) {
this.map.removeLayer(this.vertexLine);
this.vertexLine = null;
}
if (this.edgeLines) {
this.edgeLines.forEach(l => this.map.removeLayer(l));
this.edgeLines = [];
}
if (this.map._edgeProjectionMarkers) {
this.map._edgeProjectionMarkers.forEach(m => this.map.removeLayer(m));
this.map._edgeProjectionMarkers = [];
}
return;
}
// Use stored unique coordinates
const coords = this.parcel.uniqueCoords;
if (!coords) return;
// Najbliższy wierzchołek
const nearest = findNearestVertex(coords, this.userPosition);
let edges = [];
if (this.showEdges && nearest) {
edges = measureEdges(coords, nearest.index, this.userPosition);
// Rysuj linie prostopadłe
if (this.edgeLines) this.edgeLines.forEach(l => this.map.removeLayer(l));
this.edgeLines = [];
// Remove old edge projection markers
if (this.map._edgeProjectionMarkers) {
this.map._edgeProjectionMarkers.forEach(m => this.map.removeLayer(m));
this.map._edgeProjectionMarkers = [];
} else {
this.map._edgeProjectionMarkers = [];
}
edges.forEach(ed => {
const latlngs = [
[this.userPosition.lat, this.userPosition.lng],
[ed.projLat, ed.projLng]
];
const line = L.polyline(latlngs, { className: 'edge-line' }).addTo(this.map);
this.edgeLines.push(line);
// Add distance label on the edge line
const midLat = (this.userPosition.lat + ed.projLat) / 2;
const midLng = (this.userPosition.lng + ed.projLng) / 2;
const edgeDistanceLabel = L.marker([midLat, midLng], {
icon: L.divIcon({
html: formatDistance(ed.distanceM),
className: 'distance-label edge-label',
iconSize: [60, 20],
iconAnchor: [30, 10]
})
}).addTo(this.map);
this.edgeLines.push(edgeDistanceLabel);
// Check if projection point is outside the edge segment
const edgeStart = coords[ed.edgeIndex];
const edgeEnd = coords[(ed.edgeIndex + 1) % coords.length];
const projPoint = [ed.projLng, ed.projLat];
if (isPointOutsideSegment(projPoint, edgeStart, edgeEnd)) {
// Add dashed line from projection to nearest endpoint of the edge
const distToStart = turf.distance(turf.point(projPoint), turf.point(edgeStart), { units: 'meters' });
const distToEnd = turf.distance(turf.point(projPoint), turf.point(edgeEnd), { units: 'meters' });
const nearestPoint = distToStart < distToEnd ? edgeStart : edgeEnd;
const extensionLine = L.polyline([
[ed.projLat, ed.projLng],
[nearestPoint[1], nearestPoint[0]]
], { className: 'edge-extension-line' }).addTo(this.map);
this.edgeLines.push(extensionLine);
}
// Add projection point marker
const marker = L.marker([ed.projLat, ed.projLng], {
icon: L.divIcon({
html: ed.edgeIndex.toString(),
className: 'edge-label',
iconSize: [20, 20],
iconAnchor: [10, 10]
})
}).addTo(this.map);
this.map._edgeProjectionMarkers.push(marker);
});
} else {
if (this.edgeLines) this.edgeLines.forEach(l => this.map.removeLayer(l));
this.edgeLines = [];
if (this.map._edgeProjectionMarkers) {
this.map._edgeProjectionMarkers.forEach(m => this.map.removeLayer(m));
this.map._edgeProjectionMarkers = [];
}
}
this.derived = nearest ? {
nearestVertex: { index: nearest.index, lat: nearest.lat, lng: nearest.lng },
distanceToVertexM: nearest.distance,
edges: edges.length ? edges : undefined
} : null;
// Rysuj linię do wierzchołka
if (this.vertexLine) {
this.map.removeLayer(this.vertexLine);
this.vertexLine = null;
}
if (nearest) {
this.vertexLine = L.polyline([
[this.userPosition.lat, this.userPosition.lng],
[nearest.lat, nearest.lng]
], { className: 'vertex-line' }).addTo(this.map);
// Add distance label on the vertex line
const midLat = (this.userPosition.lat + nearest.lat) / 2;
const midLng = (this.userPosition.lng + nearest.lng) / 2;
const vertexDistanceLabel = L.marker([midLat, midLng], {
icon: L.divIcon({
html: formatDistance(nearest.distance),
className: 'distance-label vertex-label',
}),
}).addTo(this.map);
this.edgeLines.push(vertexDistanceLabel);
}
},
toggleShowEdges() {
this.showEdges = !this.showEdges;
this.updateDerived();
},
formatCoords,
formatDistance
}));
});
function isPointOutsideSegment(point, segmentStart, segmentEnd) {
// Use turf.js to check if point is outside the line segment
const line = turf.lineString([segmentStart, segmentEnd]);
const projectedPoint = turf.nearestPointOnLine(line, turf.point(point), { units: 'meters' });
// Check if the projected point is at the start or end of the segment
// If the projection equals one of the endpoints, the original point is outside the segment
const startPoint = turf.point(segmentStart);
const endPoint = turf.point(segmentEnd);
const distToStart = turf.distance(projectedPoint, startPoint, { units: 'meters' });
const distToEnd = turf.distance(projectedPoint, endPoint, { units: 'meters' });
// If projection is very close to either endpoint, the point is outside the segment
return distToStart < 0.001 || distToEnd < 0.001;
}