-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
373 lines (321 loc) · 15.2 KB
/
Program.cs
File metadata and controls
373 lines (321 loc) · 15.2 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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using OsmSharp;
using OsmSharp.Streams;
using Newtonsoft.Json;
/* STRONG TOWNS LANGLEY PARKING LOT MAPPING TOOL
* Coded by: James Hansen (james@strongtownslangley.org)
* https://github.com/StrongTownsLangley/ParkingLots
* strongtownslangley.org
*/
namespace pl
{
class Program
{
public static double minLongitude = 0;
public static double minLatitude = 0;
public static double maxLongitude = 0;
public static double maxLatitude = 0;
public static string outputFolder = "json";
public static List<Relation> _allRelations;
public static List<Way> _allWays;
public static List<Node> _allNodes;
public enum ParkingLotType
{
None,
Public,
Private
}
public class WayWithNodes
{
public WayWithNodes(Way Way)
{
this.Way = Way;
if(Way.Nodes != null)
{
var nodeIds = Way.Nodes.ToList();
var nodes = _allNodes
.Where(m => m.Id != null && nodeIds.Contains(m.Id.Value))
.OrderBy(node => nodeIds.IndexOf(node.Id.Value)) // Preserve Order
.ToList();
this.PopulatedNodes = nodes;
} else {
this.PopulatedNodes = new List<Node>();
}
}
public Way Way { get; set; }
public List<Node> PopulatedNodes { get; set; }
}
public class ParkingLot
{
public List<WayWithNodes> WaysWithNodes { get; set; }
public ParkingLotType ParkingLotType { get; set; }
}
public static ParkingLotType GetParkingType(OsmSharp.Tags.TagsCollectionBase tags)
{
if (tags == null)
return ParkingLotType.None;
if (tags.ContainsKey("amenity") && tags["amenity"] == "parking")
{
if (tags.ContainsKey("parking"))
if (tags["parking"] == "underground" || tags["parking"] == "rooftop")
{
return ParkingLotType.None;
}
if (tags.ContainsKey("access") && tags["access"] == "private")
return ParkingLotType.Private;
return ParkingLotType.Public;
}
return ParkingLotType.None;
}
static void Main(string[] args)
{
Console.WriteLine("Strong Towns Langley Parking Lot Mapping Tool");
Console.WriteLine("https://github.com/StrongTownsLangley/ParkingLots");
Console.WriteLine("https://strongtownslangley.org");
Console.WriteLine("Coded by James Hansen (james@strongtownslangley.org)");
Console.WriteLine("---------------------------------------------------");
// Read Arguments //
#region Read Arguments
int regionCount = 0;
foreach (var arg in args)
{
if (arg.StartsWith("-min-longitude="))
{
double.TryParse(arg.Substring("-min-longitude=".Length), out minLongitude);
regionCount++;
}
else if (arg.StartsWith("-min-latitude="))
{
double.TryParse(arg.Substring("-min-latitude=".Length), out minLatitude);
regionCount++;
}
else if (arg.StartsWith("-max-longitude="))
{
double.TryParse(arg.Substring("-max-longitude=".Length), out maxLongitude);
regionCount++;
}
else if (arg.StartsWith("-max-latitude="))
{
double.TryParse(arg.Substring("-max-latitude=".Length), out maxLatitude);
regionCount++;
}
else if (arg.StartsWith("-output-folder="))
{
outputFolder = arg.Substring("-output-folder=".Length);
}
}
if(regionCount < 4)
{
Console.WriteLine("Usage: pl.exe -min-longitude=* -min-latitude=* -max-longitude=* -max-latitude=* [output-folder=\"json\"]");
return;
}
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
#endregion
// Define the bounding box
#region Download OSM
string overpassApiUrl = "http://www.overpass-api.de/api/map?bbox=" + minLongitude + "," + minLatitude + "," + maxLongitude + "," + maxLatitude;
string osmDataFilePath = Path.Combine(outputFolder,"osm_data.osm"); // file to save OSM data
try
{
using (WebClient webClient = new WebClient())
{
Console.WriteLine("Downloading OSM data...");
webClient.DownloadFile(overpassApiUrl, osmDataFilePath);
Console.WriteLine("OSM data downloaded successfully.");
}
}
catch (Exception ex)
{
Console.WriteLine("Error downloading OSM data: {ex.Message}");
return;
}
#endregion
#region Identify Surface Parking Lots
// Read the OSM file
using (var stream = File.OpenRead(osmDataFilePath))
{
// Create an OsmReader
var osmStreamSource = new OsmSharp.Streams.XmlOsmStreamSource(stream);
Console.WriteLine("Reading All OSM Data Relations...");
_allRelations = osmStreamSource.Where(m => m.Type == OsmGeoType.Relation).Select(m => (Relation)m).ToList();
Console.WriteLine("Reading All OSM Data Ways...");
_allWays = osmStreamSource.Where(m => m.Type == OsmGeoType.Way).Select(m => (Way)m).ToList();
Console.WriteLine("Reading All OSM Data Nodes...");
_allNodes = osmStreamSource.Where(m => m.Type == OsmGeoType.Node).Select(m => (Node)m).ToList();
// Close Stream
}
Console.WriteLine("Finding Parking Lot Relations..."); // Some parking lots are multiple ways grouped as relations, with the relation having the parking info
var relationParkingWayIds = new List<long>();
var parkingLots = new List<ParkingLot>();
foreach (Relation relation in _allRelations)
{
var parkingType = GetParkingType(relation.Tags);
if(parkingType != ParkingLotType.None)
{
var waysWithNodes = new List<WayWithNodes>();
foreach(var member in relation.Members)
{
if (member.Type == OsmGeoType.Way)
{
var wayInRelation = _allWays.FirstOrDefault(m => m.Id == member.Id);
if (wayInRelation == null)
continue;
waysWithNodes.Add(new WayWithNodes(wayInRelation));
relationParkingWayIds.Add(member.Id);
}
}
var parkingLot = new ParkingLot()
{
WaysWithNodes = waysWithNodes,
ParkingLotType = parkingType
};
parkingLots.Add(parkingLot);
}
}
Console.WriteLine("Finding Parking Ways...");
foreach (var way in _allWays)
{
var tags = way.Tags;
ParkingLotType parkingType = ParkingLotType.None;
if (way.Id != null && relationParkingWayIds.Contains(way.Id.Value))
{
// Way already found as part of a relation
continue;
}
else
{
// Way not as part of relation
parkingType = GetParkingType(tags);
if (parkingType != ParkingLotType.None)
{
var parkingLot = new ParkingLot()
{
WaysWithNodes = new List<WayWithNodes>() { new WayWithNodes(way) },
ParkingLotType = parkingType
};
parkingLots.Add(parkingLot);
}
}
}
Console.WriteLine(parkingLots.Count() + " surface parking lots found.");
#endregion
#region Output JSON
// Output the identified parking lots
// Configure JSON serialization settings
var geoJsonPublicLots = new
{
type = "FeatureCollection",
features = new List<object>(),
info = new List<object>()
};
var geoJsonPrivateLots = new
{
type = "FeatureCollection",
features = new List<object>(),
info = new List<object>()
};
foreach (var parkingLot in parkingLots)
{
if(parkingLot.WaysWithNodes.Count() == 1)
{
// Polygon
var parkingLotWay = parkingLot.WaysWithNodes[0];
var parkingLotPoints = new List<double[]>();
foreach (Node node in parkingLotWay.PopulatedNodes)
{
double[] point = { node.Longitude ?? 0, node.Latitude ?? 0 };
parkingLotPoints.Add(point);
}
var feature = new
{
type = "Feature",
properties = new { },
geometry = new
{
type = "Polygon",
coordinates = new[]
{
parkingLotPoints.ToArray()
}
}
};
if(parkingLot.ParkingLotType == ParkingLotType.Public)
geoJsonPublicLots.features.Add(feature);
else
geoJsonPrivateLots.features.Add(feature);
} else {
// MultiPolygon
var parkingLotPolygons = new List<List<double[]>>();
foreach(var parkingLotWay in parkingLot.WaysWithNodes)
{
var parkingLotPoints = new List<double[]>();
foreach (Node node in parkingLotWay.PopulatedNodes)
{
double[] point = { node.Longitude ?? 0, node.Latitude ?? 0 };
parkingLotPoints.Add(point);
}
parkingLotPolygons.Add(parkingLotPoints);
}
var feature = new
{
type = "Feature",
properties = new { },
geometry = new
{
type = "MultiPolygon",
coordinates = new[]
{
parkingLotPolygons.ToArray()
}
}
};
if (parkingLot.ParkingLotType == ParkingLotType.Public)
geoJsonPublicLots.features.Add(feature);
else
geoJsonPrivateLots.features.Add(feature);
}
}
// Write GeoJSON to file
Console.WriteLine("Writing JSON 'parkinglots.json' file...");
File.WriteAllText(Path.Combine(outputFolder, "publicParkingLots.json"), Newtonsoft.Json.JsonConvert.SerializeObject(geoJsonPublicLots, Formatting.Indented));
File.WriteAllText(Path.Combine(outputFolder, "privateParkingLots.json"), Newtonsoft.Json.JsonConvert.SerializeObject(geoJsonPrivateLots, Formatting.Indented));
#endregion
#region Write Map HTML
// Replace {AVGLAT}, {AVGLON}, {DATALIST}
// taxLevel.addData(data);
var website = File.ReadAllText("pl.template.html");
website = website.Replace("{AVGLAT}", ((minLatitude + maxLatitude) / 2).ToString());
website = website.Replace("{AVGLON}", ((minLongitude + maxLongitude) / 2).ToString());
string websiteStatic = website.Replace("{DATALIST}",
@"publicParkingLots.addData(" + Newtonsoft.Json.JsonConvert.SerializeObject(geoJsonPublicLots) + @");
privateParkingLots.addData(" + Newtonsoft.Json.JsonConvert.SerializeObject(geoJsonPrivateLots) + @");
");
string websiteDynamic = website.Replace("{DATALIST}",
@" fetch('publicParkingLots.json')
.then(response => response.json())
.then(data => publicParkingLots.addData(data))
.catch(error => console.error('Error loading GeoJSON file:', error));
fetch('privateParkingLots.json')
.then(response => response.json())
.then(data => privateParkingLots.addData(data))
.catch(error => console.error('Error loading GeoJSON file:', error));"
);
var websiteStaticFile = "website.static.html";
Console.WriteLine("Writing Static Website '" + websiteStaticFile + "' file...");
File.WriteAllText(Path.Combine(outputFolder, websiteStaticFile), websiteStatic);
var websiteDynamicFile = "website.dynamic.html";
Console.WriteLine("Writing Dynamic Website '" + websiteDynamicFile + "' file...");
File.WriteAllText(Path.Combine(outputFolder, websiteDynamicFile), websiteDynamic);
#endregion
Console.WriteLine("Complete!");
}
}
}