-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.html
More file actions
278 lines (253 loc) · 9.23 KB
/
map.html
File metadata and controls
278 lines (253 loc) · 9.23 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Leaflet MarkerCluster with KML Upload</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet/dist/leaflet.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet.markercluster/dist/MarkerCluster.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet.markercluster/dist/MarkerCluster.Default.css">
<style>
#map {
height: 90vh;
}
#upload {
margin: 10px;
}
#toggle-clustering {
position: absolute;
top: 10px;
right: 10px;
z-index: 1000;
background: white;
padding: 5px;
border: 1px solid #ccc;
}
.distance-label {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid #000;
padding: 2px 5px;
border-radius: 3px;
font-size: 12px;
text-align: center;
}
</style>
</head>
<body>
<input type="file" id="upload" accept=".kml">
<div id="toggle-clustering">
<label><input type="checkbox" id="clustering-toggle"> Enable
Clustering</label>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/leaflet/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet.markercluster/dist/leaflet.markercluster.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet-omnivore/leaflet-omnivore.min.js"></script>
<script>
// Define a reusable Leaflet icon with default marker images
const defaultMarkerIcon = L.icon({
iconUrl: "https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/images/marker-icon.png",
shadowUrl: "https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/images/marker-shadow.png",
iconSize: [15, 25], // smaller size of the icon
iconAnchor: [7, 25],
shadowSize: [25, 25], // smaller size of the shadow
shadowAnchor: [7, 25],
});
// Initialize the map
var map = L.map("map").setView([0, 0], 2);
var googleStreets = L.tileLayer(
"http://{s}.google.com/vt?lyrs=m&x={x}&y={y}&z={z}",
{
maxZoom: 20,
subdomains: ["mt0", "mt1", "mt2", "mt3"],
}
);
googleStreets.addTo(map);
// Add scale control to the map
L.control.scale().addTo(map);
// Create a marker cluster group
var markers = L.markerClusterGroup({
maxClusterRadius: 40,
});
// Create a layer group for non-clustered markers
var nonClusteredMarkers = L.layerGroup();
// Add the marker cluster group to the map
map.addLayer(nonClusteredMarkers);
// Variables to store the points and the route
let rightClickCount = 0;
let firstPoint = null;
let secondPoint = null;
let distanceLine = null;
let distanceLabel = null;
let secondMarker = null;
let firstMarker = null;
function fetchAndDrawRoute(start, end) {
// OSRM public API endpoint
const osrmEndpoint = `https://router.project-osrm.org/route/v1/driving/${start.lng},${start.lat};${end.lng},${end.lat}?overview=full&geometries=geojson`;
fetch(osrmEndpoint)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
if (data.code !== 'Ok' || data.routes.length === 0) {
throw new Error('No route found');
}
// Extract route geometry and distance
const route = data.routes[0];
const routeCoords = route.geometry.coordinates.map(coord => [coord[1], coord[0]]);
const distance = route.distance; // in meters
// Draw the route on the map
if (distanceLine) {
map.removeLayer(distanceLine);
}
distanceLine = L.polyline(routeCoords, {
color: "blue",
weight: 4,
opacity: 0.7
}).addTo(map);
// Calculate distance text
const distanceText = distance >= 1000
? (distance / 1000).toFixed(2) + " km"
: distance.toFixed(2) + " m";
// Add distance label at the midpoint of the route
const midIndex = Math.floor(routeCoords.length / 2);
const midPoint = L.latLng(routeCoords[midIndex][0], routeCoords[midIndex][1]);
if (distanceLabel) {
map.removeLayer(distanceLabel);
}
distanceLabel = L.marker(midPoint, {
icon: L.divIcon({
className: "distance-label",
html: distanceText,
iconSize: [100, 40],
iconAnchor: [50, 20],
}),
}).addTo(map);
})
.catch(error => {
console.error('Error fetching the route:', error);
alert('Unable to fetch the route. Please try again.');
// Cleanup in case of error
if (distanceLine) {
map.removeLayer(distanceLine);
distanceLine = null;
}
if (distanceLabel) {
map.removeLayer(distanceLabel);
distanceLabel = null;
}
if (secondMarker) {
map.removeLayer(secondMarker);
secondMarker = null;
}
if (firstMarker) {
map.removeLayer(firstMarker);
firstMarker = null;
}
secondPoint = null;
firstPoint = null;
rightClickCount = 1; // Reset to allow re-selection of the second point
});
}
// Handle clustering toggle
document
.getElementById("clustering-toggle")
.addEventListener("change", function (event) {
if (event.target.checked) {
map.removeLayer(nonClusteredMarkers);
map.addLayer(markers);
} else {
map.removeLayer(markers);
map.addLayer(nonClusteredMarkers);
}
});
document.getElementById("upload").addEventListener("change", function (event) {
var file = event.target.files[0];
if (file && file.name.endsWith(".kml")) {
var reader = new FileReader();
reader.onload = function (e) {
var kmlText = e.target.result;
var kmlLayer = omnivore.kml.parse(kmlText);
markers.clearLayers();
nonClusteredMarkers.clearLayers();
kmlLayer.eachLayer(function (layer) {
var latlng = layer.getLatLng();
var circleMarker = L.circleMarker(latlng, {
radius: 5, // small radius
color: "#3388ff",
fillColor: "#3388ff",
weight: 1,
fillOpacity: 0.5, // semi-transparent
});
if (
layer.feature &&
layer.feature.properties &&
layer.feature.properties.name
) {
circleMarker.bindPopup(layer.feature.properties.name);
}
markers.addLayer(circleMarker);
nonClusteredMarkers.addLayer(circleMarker);
});
map.fitBounds(markers.getBounds());
};
reader.readAsText(file);
} else {
alert("Please upload a valid KML file.");
}
});
// Handle right-clicks for measuring distance
map.on("contextmenu", function (e) {
rightClickCount += 1;
if (rightClickCount === 1) {
// First right-click: store the first point
firstPoint = e.latlng;
// Add a marker for the first point without a popup and assign a customId
firstMarker = L.marker(firstPoint, {
icon: defaultMarkerIcon,
}).addTo(map);
firstMarker.customId = "firstPoint";
} else if (rightClickCount === 2) {
// Second right-click: store the second point and fetch the route
secondPoint = e.latlng;
// Add marker for the second point without a popup and assign a custom property
secondMarker = L.marker(secondPoint, {
icon: defaultMarkerIcon,
}).addTo(map);
secondMarker.customId = "secondPoint";
// Fetch and draw the route
fetchAndDrawRoute(firstPoint, secondPoint);
} else if (rightClickCount === 3) {
// Third right-click: clear the route and labels
if (distanceLine) {
map.removeLayer(distanceLine);
distanceLine = null;
}
if (distanceLabel) {
map.removeLayer(distanceLabel);
distanceLabel = null;
}
if (secondMarker) {
map.removeLayer(secondMarker);
secondMarker = null;
}
if (firstMarker) { // Ensure firstMarker is removed
map.removeLayer(firstMarker);
firstMarker = null;
}
// Reset points and counter
firstPoint = null;
secondPoint = null;
rightClickCount = 0;
} else {
// Reset after the fourth right-click
rightClickCount = 0;
}
});
</script>
</body>
</html>