forked from popenc/red_rover_analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
google_map_dragdrop_geojson.html
382 lines (309 loc) · 12.6 KB
/
google_map_dragdrop_geojson.html
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0" />
<title>Drag and Drop GeoJSON</title>
<style>
html { height: 100% }
body { height: 100%; margin: 0; padding: 0; overflow: hidden; }
#map { height: 100% }
#drop-container {
display: none;
height: 100%;
width: 100%;
position: absolute;
z-index: 1;
top: 0px;
left: 0px;
padding: 20px;
background-color: rgba(100, 100, 100, 0.5);
}
#drop-silhouette {
color: white;
border: white dashed 8px;
height: calc(100% - 56px);
width: calc(100% - 56px);
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAAZiS0dEAGQAZABkkPCsTwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB90LHAIvICWdsKwAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAACdklEQVR42u3csU7icBzA8Xp3GBMSeRITH8JHMY7cRMvmVmXoE9TAcJubhjD4ApoiopgqDMWAKAgIcSAiCfxuwhwROVJbkPD9rP23ob8vpZCQKgoAAAAAAAAAAPDYyiK/eNM05bNtr6+vSjgcXiHxDMkE1WpVFvGcfpCVICAIQUAQgoAgBAFBCAKCgCAEAUEIAoIQBAQhCAgCghAEBCEICEIQEIQgIAgIQhAQhCAgCEFAEIKAICAIQUAQgoAgBAFBCDIzhmFINBo9/K6D0XVddnd3ZaneDY7jSCqVcn3SfjyeKRKJbJ2dnYllWbKUl2i5XJaXlxdJJBIy7yDHx8fy9vYm6XR6OWMM3d/fi4hIqVSSWCwmsw5ycHAgrVZLRETOz8+XO8ZQpVJ5H2Y6nRZN0/b9DqLruhSLxfd9MpkMMT6L0uv1JJlMih9BhveJwWDwvv7i4oIY4zw8PIwMtt1uSzweF6+CHB0dSbfbHVmbzWaJMcnj4+OHAd/d3cne3p64DWKapjw/P39Yd3l5SYxpVKvVsYO2LEtUVd2ZNoiu6+I4ztg1V1dXxPAiSq/Xk5OTk0k9pNVqyenp6ch94l+5XI4YbtRqNfHa9fX1t43xcwGa/Nnc3PwdDAY9OZht28rGxgZPvP6KSCSy9fT09OUrw7ZtPqa8jFKv113HuLm5IYbXVFXdcRPl9vaWGH5GaTQaU8fI5/PE8JumafvNZvO/MQqFAjFmJRqNHk6Ksqgx5vr1zzAM2d7edr3/6uqqsra2NnZbp9NR+v2+62OHQqG5zObXPIMEAgFlfX3dl2N79btl1viTA0FAEIKAIAQBAAAAAAAAsMz+Ai1bUgo6ebm8AAAAAElFTkSuQmCC');
background-repeat: no-repeat;
background-position: center;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="drop-container"><div id="drop-silhouette"></div></div>
<script>
/* Map functions */
var map, heatmap, infowindow;
function initMap() {
// set up the map
map = new google.maps.Map(document.getElementById('map'), {
// center: new google.maps.LatLng(0, 0),
center: new google.maps.LatLng(31.473600, -83.529900),
zoom: 18,
mapTypeId: "satellite"
});
infowindow = new google.maps.InfoWindow();
// heatmap = new google.maps.visualization.HeatmapLayer({
// data: getPoints(),
// map: map
// });
}
// function showProperties() {
// // display the Point's properties if clicked, uses the infowindow from google maps..
// infowindow.open(map, marker);
// }
function displayProperties() {
console.log("here we are");
}
function loadGeoJsonString(geoString, data_type) {
console.log(geoString);
var geojson;
try {
geojson = JSON.parse(geoString); // should raise SyntaxError if CSV (i.e., not json parsable)
}
// catch (e if e instanceof SyntaxError) {
catch (e) {
if (e instanceof SyntaxError) {
// try converting expected csv to geojson
// geojson_string = csvToGeoJSON(geoString);
data_arr = csvToObject(geoString);
// geojson = JSON.parse(geojson_string);
}
else {
alert("error loading data file..");
console.log(e);
}
// return;
}
// map.data.addGeoJson(geojson); // Should this be removed for below creation of Cirles???????
// var points_list = geojson['features'];
var gmap_points_array = [];
if (data_type == "heatmap") {
for (var arr_index in data_arr) {
var lat = data_arr[arr_index][1];
var lon = data_arr[arr_index][0];
var weight = data_arr[arr_index][2];
// weighted_location = {location: new google.maps.LatLng(lat, lon), weight: weight};
// gmap_points_array.push(weighted_location);
// Trying to use varying radii circles instead of heatmap for now..
var marker = new google.maps.Circle({
strokeColor: '#FF0000',
// strokeOpacity: 0.8,
strokeOpacity: 1.0,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
title: String(lat) + ", " + String(lon),
center: new google.maps.LatLng(lat, lon),
radius: weight / 5
// center: citymap[city].center,
// radius: Math.sqrt(citymap[city].population) * 100
});
// marker.addListener('click', function () {
// infowindow.setContent('<div>' + marker.title + '</div>');
// infowindow.open(map, this);
// });
// marker.addListener('click', displayProperties());
google.maps.event.addListener(marker, 'click', function () {
// do something with this marker ...
// this.setTitle('I am clicked');
infowindow.setContent('<div>' + this.title + '</div>');
infowindow.setPosition(this.center);
infowindow.open(map, this);
});
}
// heatmap = new google.maps.visualization.HeatmapLayer({
// data: gmap_points_array,
// map: map
// });
}
else if (data_type == "regular") {
PolylineCoordinates = [];
for (var i = 0; i < data_arr.length; i++) {
var datum_arr = data_arr[i];
var lat = datum_arr[1];
var lon = datum_arr[0];
// var cityCircle = new google.maps.Circle({
// strokeColor: '#FF0000',
// strokeOpacity: 1,
// // strokeWeight: 2,
// fillColor: '#FF0000',
// fillOpacity: 1,
// map: map,
// center: new google.maps.LatLng(lat, lon),
// radius: 0.1
// });
PolylineCoordinates.push(new google.maps.LatLng(lat, lon))
}
var Path = new google.maps.Polyline({
clickable: false,
geodesic: true,
path: PolylineCoordinates,
strokeColor: "#6495ED",
strokeOpacity: 0.5,
strokeWeight: 2
});
Path.setMap(map);
}
}
/**
* Update a map's viewport to fit each geometry in a dataset
* @param {google.maps.Map} map The map to adjust
*/
function zoom(map) {
var bounds = new google.maps.LatLngBounds();
map.data.forEach(function(feature) {
processPoints(feature.getGeometry(), bounds.extend, bounds);
});
map.fitBounds(bounds);
}
function csvToObject(csvData) {
// Returns lat, lon, and weight
var lines = csvData.split("\n");
var headers = lines[0].split(",");
var lat_index = 6;
var lon_index = 7;
var weight_index = 10;
var results = [];
for (var i = 1; i < lines.length - 1; i++) {
var currentline = lines[i].split(","); // lat/lon array
var datNum = [Number(currentline[lon_index]), Number(currentline[lat_index]), Number(currentline[weight_index])]; // datNum arr --> [lon, lat, weight] (for geojson_)
results.push(datNum);
}
// return JSON.stringify(geojsonObj);
return results;
}
/**
Handles a drop-n-dropped CSV file,
converting it to geoJSON to load onto the map
*/
function csvToGeoJSON(csvData) {
var featuresArray = [];
var lines = csvData.split("\n");
var result = [];
var headers = lines[0].split(",");
var lat_header = "field.latitude";
var lon_header = "field.longitude";
// var lat_header = "latitude";
// var lon_header = "longitude";
// CHANGE THESE IF LAT/LON AT DIFFERENT INDICES
var lat_index = 6;
var lon_index = 7;
var weight_index = 10;
for (var i = 1; i < lines.length - 1; i++) {
var currentline = lines[i].split(","); // lat/lon array
var datNum = [Number(currentline[lon_index]), Number(currentline[lat_index])]; // datNum arr --> [lon, lat] (for geojson_)
var latLonPointObj = {
'type': "Feature",
'geometry': {'type': "Point", 'coordinates': datNum},
'properties': {}
};
featuresArray.push(latLonPointObj);
// var geoObj = {};
// geoObj['type'] = "Point";
// geoObj['coordinates'] = datNum;
// var propObj = {};
// propObj['lat'] = datNum[0];
// propObj['lon'] = datNum[1];
// var pointObj = {};
// pointObj['type'] = "Feature";
// pointObj['geometry'] = geoObj;
// pointObj['properties'] = {};
// featuresArray.push(pointObj);
}
var geojsonObj = {};
geojsonObj['type'] = "FeatureCollection";
geojsonObj['features'] = featuresArray;
return JSON.stringify(geojsonObj);
}
/**
* Process each point in a Geometry, regardless of how deep the points may lie.
* @param {google.maps.Data.Geometry} geometry The structure to process
* @param {function(google.maps.LatLng)} callback A function to call on each
* LatLng point encountered (e.g. Array.push)
* @param {Object} thisArg The value of 'this' as provided to 'callback' (e.g.
* myArray)
*/
function processPoints(geometry, callback, thisArg) {
if (geometry instanceof google.maps.LatLng) {
callback.call(thisArg, geometry);
} else if (geometry instanceof google.maps.Data.Point) {
callback.call(thisArg, geometry.get());
} else {
geometry.getArray().forEach(function(g) {
processPoints(g, callback, thisArg);
});
}
}
/* DOM (drag/drop) functions */
function initEvents() {
// set up the drag & drop events
var mapContainer = document.getElementById('map');
var dropContainer = document.getElementById('drop-container');
// map-specific events
mapContainer.addEventListener('dragenter', showPanel, false);
// overlay specific events (since it only appears once drag starts)
dropContainer.addEventListener('dragover', showPanel, false);
dropContainer.addEventListener('drop', handleDrop, false);
dropContainer.addEventListener('dragleave', hidePanel, false);
}
function showPanel(e) {
e.stopPropagation();
e.preventDefault();
document.getElementById('drop-container').style.display = 'block';
return false;
}
function hidePanel(e) {
document.getElementById('drop-container').style.display = 'none';
}
function handleDrop(e) {
e.preventDefault();
e.stopPropagation();
hidePanel(e);
var files = e.dataTransfer.files;
var file_name = files[0]['name']; // check if "ponits of interest" or field row data..
var data_type = "";
// if (file_name.indexOf("gps_field_test") > 0) {
if (file_name.includes("gps_field_test")) {
// plot these as normal dots, not heatmap
data_type = "regular";
}
else {
data_type = "heatmap";
}
if (files.length) {
// process file(s) being dropped
// grab the file data from each file
for (var i = 0, file; file = files[i]; i++) {
var reader = new FileReader();
reader.onload = function(e) {
loadGeoJsonString(e.target.result, data_type);
};
reader.onerror = function(e) {
console.error('reading failed');
};
reader.readAsText(file);
}
} else {
// process non-file (e.g. text or html) content being dropped
// grab the plain text version of the data
var plainText = e.dataTransfer.getData('text/plain');
if (plainText) {
loadGeoJsonString(plainText);
}
}
// prevent drag event from bubbling further
return false;
}
function initialize() {
initMap();
initEvents();
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA7FqD8uqa9pk7FFmTrYY5ZUBHcYE6wRCQ&libraries=visualization&callback=initialize"></script>
</body>
</html>