-
Notifications
You must be signed in to change notification settings - Fork 3
/
nvdb2osm.py
2936 lines (2250 loc) · 97.7 KB
/
nvdb2osm.py
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf8
# nvdb2osm.py
# Converts road objects and road networks from NVDB to OSM file format
# Usage:
# 1) nvdb2osm -vegobjekt <vegobjektkode> [-kommune <kommune>] > outfile.osm --> Produces osm file with all road objects of a given type (optionally within a given municipality)
# 2) nvdb2osm -vegnett -kommune <kommune> > outfile.osm --> Produces osm file with road network for a given municipality
# 3) nvdb2osm -vegref <vegreferanse> > outfile.osm --> Produces osm file with road network for given road reference code
# 4) nvdb2osm -vegurl "<http string from vegnett.no>"" > outfile.osm --> Produces osm file defined by given NVDB http api call from vegkart.no.
# "&srid=wgs84" automatically added. Bounding box only supported for wgs84 coordinates, not UTM from vegkart.no.
import json
import urllib.request
import sys
import socket
import os
import copy
import math
import calendar
import time
from xml.etree import ElementTree as ET
version = "1.6.0"
longer_ways = True # True: Concatenate segments with identical tags into longer ways, within sequence
debug = False # True: Include detailed information tags for debugging
save_input = False # True: Save raw input from api to file
include_objects = True # True: Include road objects in network output
object_tags = False # True: Include detailed road object information tags
date_filter = None # Limit data to given date, for example "2020-05" to get highways created in May 2020
segment_margin = 10.0 # Tolerance for snap of way property to way start/end (meters)
point_margin = 2.0 # Tolerance for snap of point to way start/end (meters)
node_margin = 1.0 # Tolerance for snap of point to nodes of way (meters)
fix_margin = 0.5 # Minimum distance between way nodes (meters)
angle_margin = 45.0 # Maximum change of bearing at intersection for merging segments into longer ways (degrees)
max_travel_depth = 10 # Maximum depth of recursive calls when finding route
simplify_factor = 0.2 # Minimum deviation to straight line before simplification of redundant nodes (meters)
years_back = 1 # Maximum number of years between survey of road ("datafangst") and start date (for date option)
import_folder = "~/Jottacloud/osm/nvdb nye/log/" # Folder containing json with history of road network for each month
#server = "https://nvdbapiles-v3.utv.atlas.vegvesen.no/" # UTV - Utvikling
#server = "https://nvdbapiles-v3-stm.utv.atlas.vegvesen.no/" # STM - Systemtest
#server = "https://nvdbapiles-v3.test.atlas.vegvesen.no/" # ATM - Testproduksjon
server = "https://nvdbapiles-v3.atlas.vegvesen.no/" # Produksjon
request_headers = {
"X-Client": "nvdb2osm",
"X-Kontaktperson": "[email protected]",
"Accept": "application/vnd.vegvesen.nvdb-v3-rev1+json"
}
road_category = {
'E': {'name': 'Europaveg', 'tag': 'trunk'},
'R': {'name': 'Riksveg', 'tag': 'trunk'},
'F': {'name': 'Fylkesveg', 'tag': 'secondary'},
'K': {'name': 'Kommunal veg', 'tag': 'residential'},
'P': {'name': 'Privat veg', 'tag': 'service'},
'S': {'name': 'Skogsbilveg', 'tag': 'service'}
}
road_status = {
'V': 'Eksisterende veg',
'A': 'Veg under bygging',
'P': 'Planlagt veg',
'F': 'Fiktiv veg'
}
medium_types = {
'T': 'På terrenget/på bakkenivå',
'B': 'I bygning/bygningsmessig anlegg',
'L': 'I luft',
'U': 'Under terrenget',
'S': 'På sjøbunnen',
'O': 'På vannoverflaten',
'V': 'Alltid i vann',
'D': 'Tidvis under vann',
'I': 'På isbre',
'W': 'Under sjøbunnen',
'J': 'Under isbre',
'X': 'Ukjent'
}
# Extension of dict class which returns an empty string if element does not exist
class Properties(dict):
def __missing__(self, key):
return ""
# Write message to console
def message (text):
sys.stderr.write(text)
sys.stderr.flush()
# Open URL request. Retry if needed.
def open_url (url):
tries = 0
while tries <= 5:
try:
return urllib.request.urlopen(url)
except Exception as err: #(urllib.error.HTTPError, ConnectionResetError) as err:
if tries == 5:
raise
elif tries == 0:
message ("\n")
message ("Retry %i: %s\n" % (tries + 1, err))
time.sleep(5 * (2**tries))
tries += 1
# Load data from api. Retry if needed.
def load_data (url):
tries = 0
while tries <= 5:
try:
request = urllib.request.Request(url, headers=request_headers)
file = urllib.request.urlopen(request)
data = json.load(file)
file.close()
return data
except Exception as err:
if tries == 5:
raise
elif tries == 0:
message ("\n")
message ("Retry %i: %s\n" % (tries + 1, err))
time.sleep(5 * (2**tries))
tries += 1
# Compute approximation of distance between two coordinates, (lat,lon), in kilometers
# Works for short distances
def compute_distance (point1, point2):
lon1, lat1, lon2, lat2 = map(math.radians, [point1[1], point1[0], point2[1], point2[0]])
x = (lon2 - lon1) * math.cos( 0.5*(lat2+lat1) )
y = lat2 - lat1
return 6371000.0 * math.sqrt( x*x + y*y ) # Metres
# Return bearing in degrees of line between two points (latitude, longitude)
def compute_bearing (point1, point2):
lon1, lat1, lon2, lat2 = map(math.radians, [point1[1], point1[0], point2[1], point2[0]])
dLon = lon2 - lon1
y = math.sin(dLon) * math.cos(lat2)
x = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(dLon)
angle = (math.degrees(math.atan2(y, x)) + 360) % 360
return angle
# Compute closest distance from point p3 to line segment [s1, s2].
# Works for short distances.
def line_distance(s1, s2, p3):
x1, y1, x2, y2, x3, y3 = map(math.radians, [s1[1], s1[0], s2[1], s2[0], p3[1], p3[0]]) # Note: (y,x)
# Simplified reprojection of latitude
x1 = x1 * math.cos( y1 )
x2 = x2 * math.cos( y2 )
x3 = x3 * math.cos( y3 )
A = x3 - x1
B = y3 - y1
dx = x2 - x1
dy = y2 - y1
dot = (x3 - x1)*dx + (y3 - y1)*dy
len_sq = dx*dx + dy*dy
if len_sq != 0: # in case of zero length line
param = dot / len_sq
else:
param = -1
if param < 0:
x4 = x1
y4 = y1
elif param > 1:
x4 = x2
y4 = y2
else:
x4 = x1 + param * dx
y4 = y1 + param * dy
# Also compute distance from p to segment
x = x4 - x3
y = y4 - y3
distance = 6371000 * math.sqrt( x*x + y*y ) # In meters
'''
# Project back to longitude/latitude
x4 = x4 / math.cos(y4)
lon = math.degrees(x4)
lat = math.degrees(y4)
return (lon, lat, distance)
'''
return distance
# Fix street name initials/dots and spacing + corrections table.
# Same algorithm as in addr2osm.
# Examples:
# Dr.Gregertsens vei -> Dr. Gregertsens vei
# Arne M Holdens vei -> Arne M. Holdens vei
# O G Hauges veg -> O.G. Hauges veg
# C. A. Pihls gate -> C.A. Pihls gate
def fix_street_name (name):
# First test exceptions from Github json file
name = name.replace(" ", " ").strip()
if name in name_corrections:
return name_corrections[ name ]
# Loop characters in street name and make automatic corrections for dots and spacing
new_name = ""
length = len(name)
i = 0
word = 0 # Length of last word while looping street name
while i < length - 3: # Avoid last 3 characters to enable forward looking tests
if name[i] == ".":
if name[i + 1] == " " and name[i + 3] in [".", " "]: # Example "C. A. Pihls gate"
new_name = new_name + "." + name[i + 2]
i += 2
word = 1
elif name[i + 1] != " " and name[i + 2] not in [".", " "]: # Example "Dr.Gregertsens vei"
new_name = new_name + ". "
word = 0
else:
new_name = new_name + "."
word = 0
elif name[i] == " ":
# Avoid "Elvemo / Bávttevuolbállggis", "Skjomenveien - Elvegård", "Bakken i Lysefjorden", "Kristian 4 gate"
if word == 1 and name[i-1] not in ["-", "/", "i"] and not name[i-1].isdigit():
if name[i + 2] in [" ", "."]: # Example "O G Hauges veg"
new_name = new_name + "."
else:
new_name = new_name + ". " # Example "K Sundts vei"
else:
new_name = new_name + " "
word = 0
else:
new_name = new_name + name[i]
word += 1
i += 1
new_name = new_name + name[i:i + 3]
# Check correction table for last part of name
split_name = new_name.split()
for i in range(1, len(split_name)):
if split_name[i] in name_ending_corrections:
split_name[i] = split_name[i].lower()
new_name = " ".join(split_name)
if name != new_name:
return new_name
else:
return name
# Generate display road number
def get_ref (category, number):
if category == "E":
ref = "E " + str(number)
elif category in ["R", "F"]:
ref = str(number)
else:
ref = ""
return ref
# Generate forward/backward direction + NVDB lane code
def get_direction (lane):
if not lane:
return ("", "")
if isinstance(lane, list):
# Check if all directions are similar
last_direction = ""
for one_lane in lane:
direction, code = get_direction(one_lane)
if last_direction and direction != last_direction:
return ("", "")
last_direction = direction
return (last_direction, "")
else:
# Decompose lane coding
code = ""
if len(lane) > 1 and lane[1].isdigit():
side = lane[0:2]
if len(lane) > 2:
code = lane[2].upper()
else:
side = lane[0]
if len(lane) > 1:
code = lane[1].upper()
# Odd numbers forward, else backward
if side[-1] in ["1", "3", "5", "7", "9"]:
return ("forward", code)
else:
return ("backward", code)
# Decode NVDB lane coding to OSM tags
def process_lanes (lane_codes):
lanes = {}
turn = {}
psv = {}
cycleway = {}
tags = {}
for direction in ["forward", "backward"]:
lanes[direction] = 0
turn[direction] = ""
psv[direction] = ""
cycleway[direction] = False
# Loop all lanes and build turn:lane tags + count lanes
for i, lane in enumerate(lane_codes):
direction, code = get_direction(lane)
if i == 0:
segment_reverse = (direction == "backward")
# Build lane tagging for turn, psv and cycleway
if code == "V":
turn[direction] = "|left" + turn[direction]
psv[direction] = "|" + psv[direction]
lanes[direction] += 1
elif code == "H":
turn[direction] += "|right"
psv[direction] += "|"
lanes[direction] += 1
elif code == "K":
turn[direction] += "|"
psv[direction] += "|designated"
lanes[direction] += 1
elif code == "S":
cycleway[direction] = True
else:
turn[direction] += "|through"
psv[direction] += "|"
lanes[direction] += 1
# Simplify turn and psv tagging if all lanes are equal
for direction in ["forward", "backward"]:
turn[direction] = turn[direction][1:]
if "left" not in turn[direction] and "right" not in turn[direction]:
turn[direction] = ""
psv[direction] = psv[direction][1:]
if "designated" not in psv[direction]:
psv[direction] = ""
elif psv[direction].replace("|designated", "") == "designated": # All turns designated
psv[direction] = "designated"
# Produce turn:lane and access tags. Forward and backward tagging only needed if not oneway
for direction in ["forward", "backward"]:
if lanes['forward'] > 0 and lanes['backward'] > 0:
suffix = ":" + direction
else:
suffix = ""
if "|" in turn[direction]:
tags['turn:lanes' + suffix] = turn[direction]
elif turn[direction] and lanes['forward'] + lanes['backward'] > 1:
tags['turn' + suffix] = turn[direction]
if "|" in psv[direction]:
tags['psv:lanes' + suffix] = psv[direction]
tags['motor_vehicle:lanes' + suffix] = psv[direction].replace("designated","no")
elif psv[direction]:
if psv['forward'] == psv['backward']:
suffix = ""
tags['psv' + suffix] = psv[direction]
tags['motor_vehicle' + suffix] = psv[direction].replace("designated","no")
# Lanes tagging if more than one line in either direction
if lanes['forward'] > 1 or lanes['backward'] > 1 or psv['forward'] or psv['backward'] or \
(turn['forward'] or turn['backward']) and lanes['forward'] + lanes['backward'] > 1:
tags['lanes'] = str(lanes['forward'] + lanes['backward'])
if lanes['forward'] > 0 and lanes['backward'] > 0 and lanes['forward'] + lanes['backward'] > 2:
tags['lanes:forward'] = str(lanes['forward'])
tags['lanes:backward'] = str(lanes['backward'])
# One-way if either direction is missing
if lanes['forward'] == 0 or lanes['backward'] == 0:
tags['oneway'] = "yes"
# Produce cycleway lane tags
if cycleway['forward'] and cycleway['backward']:
tags['cycleway'] = "lane"
elif segment_reverse:
if cycleway['forward']:
tags['cycleway:left'] = "lane"
elif cycleway['backward']:
tags['cycleway:right'] = "lane"
else:
if cycleway['forward']:
tags['cycleway:right'] = "lane"
elif cycleway['backward']:
tags['cycleway:left'] = "lane"
# Remove empty keys
for key, value in tags.items():
if not value:
del tags[key]
return tags
# Produce basic highway tagging for segment
def tag_highway (segment, lanes, tags, extras):
if segment['vegsystemreferanse']:
ref = segment['vegsystemreferanse']['vegsystem']
else:
ref = None
# Set key according to status (proposed, construction, existing)
tag_key = "highway"
if ref:
if ref['fase'] == "A":
tags['highway'] = "construction"
tag_key = "construction"
elif ref['fase'] == "P":
if segment['typeVeg'] in ["Bilferje", "Passasjerferje"]:
tags['route'] = "proposed"
else:
tags['highway'] = "proposed"
tag_key = "proposed"
else:
if segment['typeVeg'] in ["Bilferje", "Passasjerferje"]:
tag_key = "route"
# Special case: Strange data tagged as crossing
if segment['typeVeg'] in ["Kanalisert veg", "Enkel bilveg"] and ref and \
"strekning" in segment['vegsystemreferanse'] and segment['vegsystemreferanse']['strekning']['trafikantgruppe'] == "G" or \
segment['typeVeg'] == "Gang- og sykkelveg" and "topologinivå" in segment and segment['topologinivå'] == "KJOREBANE":
tags[tag_key] = "footway"
tags['footway'] = "crossing"
tags['bicycle'] = "yes"
segment['typeVeg'] == "Gangfelt"
# Tagging for normal highways (cars)
elif segment['typeVeg'] in ["Enkel bilveg", "Kanalisert veg", "Rampe", "Rundkjøring"] and ref: # Regular highways (excluding "kjørefelt")
if "sideanlegg" in segment['vegsystemreferanse'] or \
len(lanes) == 1 and "K" in lanes[0] and ref['vegkategori'] in ["E", "R", "F"] and segment['detaljnivå'] != "Kjørebane" and \
(segment['typeVeg'] != "Enkel bilveg" or "kryssystem" in segment['vegsystemreferanse']): # Trafikklommer/rasteplasser
tags[tag_key] = "unclassified"
else:
if (ref['vegkategori'] == "F" or ref['vegkategori'] == "K" and municipality_id == "0301") and ref['nummer'] < 1000: # After reform
tags[tag_key] = "primary"
tags['ref'] = get_ref("F", ref['nummer'])
else:
tags[tag_key] = road_category[ ref['vegkategori'] ]['tag']
if ref['vegkategori'] in ["E", "R", "F"]:
tags['ref'] = get_ref(ref['vegkategori'], ref['nummer'])
# Add Ring ref in Oslo/Bærum
if ref['nummer'] == 162 and ref['vegkategori'] == "R":
tags['ref'] += ";Ring 1"
elif ref['nummer'] == 161 and ref['vegkategori'] == "K":
tags['ref'] = "161;Ring 2"
elif (ref['nummer'] == 150 and ref['vegkategori'] == "R"
or ref['nummer'] == 6 and "gate" in segment and segment['gate']['navn'] in ["Hjalmar Brantings vei", "Adolf Hedins vei"]):
tags['ref'] += ";Ring 3"
if tags[tag_key] in ["trunk", "primary", "secondary"]: # ref['vegkategori'] in ["E", "R", "F"]:
if segment['typeVeg'] == "Rampe" or segment['detaljnivå'] == "Kjørefelt" and lanes and "H" in lanes[0]:
tags[tag_key] += "_link"
# tags['ref'] = get_ref(ref['vegkategori'], ref['nummer'])
tags['surface'] = "asphalt" # May be owerwritten later, based on road object info
if segment['typeVeg'] == "Rundkjøring":
tags['junction'] = "roundabout"
if lanes:
tags.update (process_lanes (lanes))
elif segment['detaljnivå'] != "Vegtrase" and segment['typeVeg'] in ["Kanalisert veg", "Rampe", "Rundkjøring"]:
tags['oneway'] = "yes"
if segment['detaljnivå'] == "Kjørefelt" and not (lanes and ("K" in lanes[0] and lanes[0] != "SVKL")): # or "H" in lanes[0])):
# tags.clear()
# tags['FIXME'] = 'Please replace way with "turn:lanes" on main way'
if tag_key in tags:
del tags[tag_key]
if "turn:lanes" in tags:
del tags['turn:lanes']
# if lanes and "V1" in lanes[0] and "turn:lanes" not in tags:
# tags['turn:lanes'] = "left"
# Ferries
elif segment['typeVeg'] in ["Bilferje", "Passasjerferje"]: # Ferry
tags[tag_key] = "ferry"
if ref:
tags['ref'] = get_ref(ref['vegkategori'], ref['nummer'])
if ref['vegkategori'] == "F" and ref['nummer'] < 1000:
tags['ferry'] = "primary"
else:
tags['ferry'] = road_category[ ref['vegkategori'] ]['tag'].replace("residential", "unclassified").replace("service", "unclassified")
else:
tags['ferry'] = "unclassified"
# All other highway types
elif segment['typeVeg'] == "Gågate": # Pedestrian street
tags[tag_key] = "pedestrian"
tags['bicycle'] = "yes"
tags['surface'] = "asphalt"
elif segment['typeVeg'] == "Gatetun": # Living street
tags[tag_key] = "living_street"
elif segment['typeVeg'] == "Gang- og sykkelveg": # Combined cycleway/footway
if ref and ref['vegkategori'] != "P":
tags[tag_key] = "cycleway"
tags['foot'] = "designated"
tags['segregated'] = "no"
tags['surface'] = "asphalt"
else:
tags[tag_key] = "footway"
tags['bicycle'] = "yes"
tags['segregated'] = "no"
elif segment['typeVeg'] == "Sykkelveg": # Express cycleway
tags[tag_key] = "cycleway"
tags["foot"] = "designated"
tags['segregated'] = "yes"
tags['surface'] = "asphalt"
if len(lanes) == 2 and lanes[0] == "1S" and lanes[1] == "2S":
tags['lanes'] = "2"
elif segment['typeVeg'] == "Gangveg": # Footway
tags[tag_key] = "footway"
tags['bicycle'] = "yes"
elif segment['typeVeg'] == "Fortau": # Sidewalk
tags[tag_key] = "footway"
# tags['bicycle'] = "yes"
tags['footway'] = "sidewalk"
elif segment['typeVeg'] == "Gangfelt": # Crossing
tags[tag_key] = "footway"
# tags['bicycle'] = "yes"
tags['footway'] = "crossing"
elif segment['typeVeg'] == "Trapp": # Stairs
tags[tag_key] = "steps"
elif segment['typeVeg'] == "Traktorveg": # Track
tags[tag_key] = "track"
elif segment['typeVeg'] == "Sti": # Path
tags[tag_key] = "path"
elif segment['typeVeg'] == "Annet": # Other
tags[tag_key] = "road"
else:
tags["fixme"] = "Add highway tag for %s" % segment['typeVeg']
message (" ** No highway tagging - %s %s\n" % (segment['typeVeg'], segment['referanse']))
# Tunnels and bridges
medium = ""
if "medium" in segment['geometri']:
medium = segment['geometri']['medium']
elif "medium" in segment:
medium = segment['medium']
if medium:
if medium in ["U", "W", "J"]:
tags['tunnel'] = "yes"
tags['layer'] = "-1"
elif medium == "B":
tags['tunnel'] = "building_passage"
elif medium == "L":
tags['bridge'] = "yes"
tags['layer'] = "1"
# Street name
if "gate" in segment:
if segment['typeVeg'] != "Rundkjøring":
tags['name'] = fix_street_name(segment['gate']['navn'])
# if tag_key in tags and tags[tag_key] == "service": # Upgrade street category if name is present (now done through road object "Gate")
# tags[tag_key] = "unclassified"
# Information tags for debugging
if debug:
extras["DETALJNIVÅ"] = segment['detaljnivå']
extras["TYPEVEG"] = segment['typeVeg']
if lanes:
extras['FELT'] = " ".join(lanes)
if medium:
extras["MEDIUM"] = "#" + medium + " " + medium_types[ medium ]
if "topologinivå" in segment:
extras["TOPOLOGINIVÅ"] = segment['topologinivå']
if ref:
ref = segment['vegsystemreferanse']
extras["VEGNUMMER"] = str(ref['vegsystem']['nummer'])
extras["VEGREFERANSE"] = ref['kortform']
extras["FASE"] = "#" + ref['vegsystem']['fase'] + " " + road_status[ ref['vegsystem']['fase'] ]
extras["KATEGORI"] = "#" + ref['vegsystem']['vegkategori'] + " " + road_category[ ref['vegsystem']['vegkategori'] ]['name']
if "sideanlegg" in ref:
extras['SIDEANLEGG'] = "%i-%i id:%i" % (ref['sideanlegg']['sideanlegg'], ref['sideanlegg']['sideanleggsdel'], ref['sideanlegg']['id'])
if "kryssystem" in ref:
extras['KRYSSYSTEM'] = "%i-%i id:%i" % (ref['kryssystem']['kryssystem'], ref['kryssystem']['kryssdel'], ref['kryssystem']['id'])
# Return highway type
if segment['typeVeg'] in ["Enkel bilveg", "Kanalisert veg"]:
return "Bilveg"
elif segment['typeVeg'] in ["Gang- og sykkelveg", "Sykkelveg"]:
return "Sykkelveg"
else:
return segment['typeVeg']
# Produce tagging for supported road objects.
# Important note: Each individual segment is not known in this function.
# Updates which depend on each segment is done in the update_tags function below.
def tag_object (object_id, properties, tags):
if object_id == "595": # Motorway/motorroad
if properties['Motorvegtype'] == "Motorveg":
tags['motorway'] = "yes" # Dummy to flag new highway class
elif properties['Motorvegtype'] == "Motortrafikkveg":
tags['motorroad'] = "yes"
elif object_id == "821": # Functional road class
if municipality_id == "0301" and properties['Vegklasse'] == 4:
tags['secondary'] = "yes" # Dummy to flag secondary highway class for Oslo
elif properties['Vegklasse'] < 6: # Only class 4 and 5 ?
tags['tertiary'] = "yes" # Dummy to flag new highway class below secondary level
elif object_id == "105": # Maxspeed
if "Fartsgrense" in properties:
tags['maxspeed'] = str(properties["Fartsgrense"])
elif object_id == "538": # Address name
if "Adressenavn" in properties: # Used to be "Gatenavn"
tags['name'] = fix_street_name(properties['Adressenavn'])
if properties['Sideveg'] != "Ja": # Not consistently tagged in NVDB (== "Nei")
tags['mainroad'] = "yes" # Dummy to flag new highway class instead of residential/service
elif object_id == "581": # Tunnels, 1st pass
if "Navn" in properties:
tags['tunnel:name'] = properties['Navn'].replace(" "," ").strip()
if properties['Sykkelforbud'] == "Ja":
tags['bicycle'] = "no"
tags['foot'] = "no"
elif object_id == "67": # Tunnels, 2nd pass
tags['tunnel'] = "yes"
tags['layer'] = "-1"
if "Navn" in properties and not("tunnel:name" in tags and tags['tunnel:name'] == properties['Navn']):
tags['tunnel:description'] = properties['Navn'].replace(" "," ").strip()
if object_id == "66": # Avalanche protector
tags['tunnel'] = "avalanche_protector"
tags['layer'] = "-1"
if "Navn" in properties:
tags['tunnel:name'] = properties['Navn'].replace(" "," ").strip()
elif object_id == "60": # Bridge
tags['bridge'] = "yes"
tags['layer'] = "1"
if "Navn" in properties:
tags['bridge:description'] = properties['Navn'].replace(" "," ").replace(" Bru", " bru").strip()
if "Byggverkstype" in properties:
bridge_type = properties['Byggverkstype'].lower()
if "hengebru" in bridge_type:
tags['bridge:structure'] = "suspension"
if "bue" in bridge_type or "hvelv" in bridge_type:
tags['bridge:structure'] = "arch"
elif "fagverk" in bridge_type:
tags['bridge:structure'] = "truss"
elif bridge_type in ["klaffebru", "svingbru", "rullebru"]:
tags['bridge'] = "movable"
if bridge_type == "klaffebru":
tags['bridge:movable'] = "bascule"
elif bridge_type == "svingbru":
tags['bridge:movable'] = "swing"
elif bridge_type == "rullebru":
tags['bridge:movable'] = "retractable"
elif bridge_type == "flytebru":
tags['bridge:structure'] = "floating"
elif object_id == "856": # Access restriction
restrictions = {
'Forbudt for alle kjøretøy': {'motor_vehicle': 'no'},
'Forbudt for gående': {'foot': 'no'},
'Forbudt for gående og syklende': {'foot': 'no', 'bicycle': 'no'},
'Forbudt for lastebil og trekkbil': {'hgv': 'no'},
'Forbudt for lastebil og trekkbil m unntak': {'hgv': 'permissive'},
'Forbudt for motorsykkel': {'motorcycle': 'no'},
'Forbudt for motorsykkel og moped': {'motorcycle': 'no', 'moped': 'no'},
'Forbudt for motortrafikk': {'motor_vehicle': 'no'},
'Forbudt for motortrafikk unntatt buss': {'motor_vehicle': 'no', 'bus': 'yes'},
'Forbudt for motortrafikk unntatt buss og taxi': {'motor_vehicle': 'no', 'psv': 'yes'},
'Forbudt for motortrafikk unntatt moped': {'motor_vehicle': 'no', 'moped': 'yes'},
'Forbudt for motortrafikk unntatt spesiell motorvogntype': {'motor_vehicle': 'permissive'},
'Forbudt for motortrafikk unntatt taxi': {'motor_vehicle': 'no', 'taxi': 'yes'},
'Forbudt for motortrafikk unntatt varetransport': {'motor_vehicle': 'delivery'},
'Forbudt for syklende': {'bicycle': 'no'},
'Forbudt for traktor': {'agricultural': 'no'},
'Utgår_Gjennomkjøring forbudt': {'motor_vehicle': 'destination'},
'Utgår_Gjennomkjøring forbudt for lastebil og trekkbil': {'hgv': 'destination'},
'Utgår_Gjennomkjøring forbudt til veg eller gate': {'motor_vehicle': 'destination'},
'Motortrafikk kun tillatt for kjøring til eiendommer': {'motor_vehicle': 'destination'},
'Motortrafikk kun tillatt for kjøring til virksomhet eller adresse': {'motor_vehicle': 'destination'},
'Motortrafikk kun tillatt for varetransport': {'motor_vehicle': 'delivery'},
'Motortrafikk kun tillatt for varetransport og kjøring til eiendommer': {'motor_vehicle': 'destination'},
'Utgår_Sykling mot kjøreretningen tillatt': {'oneway:bicycle': 'no'}
}
if "Trafikkreguleringer" in properties:
if properties['Trafikkreguleringer'].strip() in restrictions:
tags.update(restrictions[ properties['Trafikkreguleringer'].strip() ])
else:
message (" *** Unknown access restriction: %s\n" % properties['Trafikkreguleringer'])
elif object_id == "103": # Speed bump
if properties['Type'] == "Fartshump":
tags['traffic_calming'] = "table" # Mostly long/wide humps
elif object_id == "22": # Cattle grid
tags['barrier'] = "cattle_grid"
elif object_id == "47": # Passing place
if properties['Bruksområde'] == "Møteplass":
tags['highway'] = "passing_place"
elif object_id in ["607", "23"]: # Barrier
barriers = {
'Heve-/senkebom': 'lift_gate',
'Utgår_Heve-/senkebom, ensidig': 'lift_gate',
'Utgår_Heve-/senkebom, tosidig': 'lift_gate',
'Svingbom': 'swing_gate',
'Utgår_Svingbom, enkel': 'swing_gate',
'Utgår_Svingbom, dobbel': 'swing_gate',
'Stolpe/pullert/kjegle': 'bollard',
'Rørgelender': 'cycle_barrier',
'Steinblokk': 'block',
'Betongblokk': 'jersey_barrier',
'Bussluse': 'bus_trap',
'Annen type vegbom/sperring': 'gate',
'Låst bom': 'yes',
# 'Utgår_Trafikkavviser': 'bollard',
# 'Bilsperre': 'gate',
}
if (properties['Bruksområde'] == "Gang-/sykkelveg, sluse"
and (properties['Type'] == "Annen type vegbom/sperring" or "Type" not in properties)):
tags['barrier'] = "swing_gate"
elif properties['Bruksområde'] not in ["Tunnel", "Bomstasjon", "Ferjekai", "Jernbane"]:
if properties['Type'] in barriers:
tags['barrier'] = barriers[ properties['Type'] ]
else:
if "Type" in properties:
message (" *** Unknown barrier type: %s\n" % properties['Type'])
tags['barrier'] = "yes"
if properties['Bruksområde'] == "Høyfjellsovergang":
tags['access'] = "yes"
if "Stedsnavn" in properties:
tags['name'] = properties['Stedsnavn']
elif object_id == "174": # Pedestrian crossing
tags['highway'] = "crossing"
if properties['Trafikklys'] == "Ja":
tags['crossing'] = "traffic_signals"
elif properties['Markering av striper'] == "Malte striper":
tags['crossing'] = "uncontrolled"
elif properties['Markering av striper'] == "Ikke striper":
tags['crossing'] = "unmarked"
if properties ["Trafikkøy"] == "Ja":
tags['crossing:island'] = "yes"
elif object_id == "100": # Railway crossing
if "I plan" in properties['Type']:
tags['railway'] = "level_crossing"
if "uten lysregulering og bommer" in properties['Type']:
tags['crossing'] = "uncontrolled"
else:
if "uten bommer" not in properties['Type'] or "grind" in properties['Type']:
tags['crossing:barrier'] = "yes"
if "lysregulert" in properties['Type']:
tags['crossing:light'] = "yes" # crossing = traffic_light ?
elif object_id == "89": # Traffic signal
if properties['Bruksområde'] == "Vegkryss": # ,"Skyttelsignalanlegg"
tags['highway'] = "traffic_signals"
elif properties['Bruksområde'] == "Gangfelt":
tags['highway'] = "crossing"
tags['crossing'] = "traffic_signals"
elif object_id == "241": # Surface
if "asfalt" not in properties['Massetype'].lower():
if "betong" in properties['Massetype'].lower():
tags['surface'] = "concrete"
elif "grus" in properties['Massetype'].lower():
tags['surface'] = "gravel"
elif properties['Massetype'] == "Brostein/Gatestein":
tags['surface'] = "sett"
elif properties['Massetype'] == "Belegningsstein":
tags['surface'] = "paving_stones"
elif properties['Massetype'] == "Tre (bru)":
tags['surface'] = "wood"
elif properties['Massetype'] == "Stålgitter (bru)":
tags['surface'] = "metal"
else:
tags['surface'] = "asphalt"
elif object_id == "591": # Maxheight
if "Skilta høyde" in properties:
tags['maxheight'] = str(properties['Skilta høyde'])
elif object_id == "904": # Maxweight/maxlength
if "tonn" in properties['Bruksklasse'] and "50 tonn" not in properties['Bruksklasse']:
tags['maxweight'] = properties['Bruksklasse'][-7:-5] # "xx tonn"
if properties['Maks vogntoglengde'] in ['12,40', '15,00']:
tags['maxlength'] = properties['Maks vogntoglengde'].replace(",", ".")
elif object_id == "64": # Ferry terminal
tags['amenity'] = "ferry_terminal"
if "Navn" in properties:
tags['name'] = properties['Navn'].replace("Fk","").replace("Kai","").replace(" "," ").strip()
elif object_id == "770": # Ferry route
if "Navn" in properties:
tags['name'] = properties['Navn'].strip()
elif object_id == "37": # Motorway junction
if "Planskilt kryss" in properties['Type']:
tags['highway'] = "motorway_junction"
if "Kryssnummer" in properties:
tags['ref'] = str(properties['Kryssnummer'])
if "Navn" in properties:
tags['name'] = properties['Navn'].replace(" ", " ").strip()
elif object_id == "96": # Sign
if "Trafikk" in properties['Ansiktsside, rettet mot']:
if properties['Skiltnummer'] == "204 - Stopp": # 7643
tags['highway'] = "stop"
elif properties['Skiltnummer'] == "202 - Vikeplikt": # 7642
tags['highway'] = "give_way"
elif properties['Skiltnummer'] == "306.6 - Forbudt for syklende": # 7655
tags['traffic_sign'] = "NO:306.6"
tags['bicycle'] = "no"
elif properties['Skiltnummer'] == "306.7 - Forbudt for gående": # 7656
tags['traffic_sign'] = "NO:306.7"
tags['foot'] = "no"
elif properties['Skiltnummer'] == "306.8 - Forbudt for gående og syklende": # 7657
tags['traffic_sign'] = "NO:306.8"
tags['bicycle'] = "no"
tags['foot'] = "no"
elif object_id == "107": # Weather restriction
if "Vinterstengt, fra dato" in properties or "Vinterstengt, til dato" in properties:
tags['snowplowing'] = "no"
if "Vinterstengt, fra dato" in properties and "Vinterstengt, til dato" in properties:
tags['motor_vehicle:conditional'] = "no @ %s-%s" % (calendar.month_abbr[int(properties['Vinterstengt, fra dato'][0:2])], \
calendar.month_abbr[int(properties['Vinterstengt, til dato'][0:2])])
if "Tilleggsinformasjon" in properties:
tags['description'] = properties['Tilleggsinformasjon'].replace(" "," ")
elif object_id == "291": # Hazard
tags['hazard'] = "animal_crossing"
if properties['Art'] == "Hjort":
tags['species:en'] = "deer"
elif properties['Art'] == "Elg":
tags['species:en'] = "moose"
elif properties['Art'] == "Rein":
tags['species:en'] = "raindeer"
elif properties['Art'] == "Rådyr":
tags['species:en'] = "venison"
elif object_id == "777": # Scenic route
if properties['Status'] != "Framtidig turistveg":
tags['scenic'] = "yes"
tags['scenic:name'] = properties['Navn']
elif object_id == "922": # Highway class undetermined
if properties['Foreslått endring'] and properties['Foreslått endring'] != "Annen endring":
tags['note'] = "Foreslått " + properties['Foreslått endring'].lower()
else:
tags['note'] = "Foreslått endring av veiklasse"
elif object_id == "923": # Diversion
tags['note'] = "Beredskapsvei" # Further tagging in update_tags function
elif object_id == "924": # Service road
tags['note'] = "Servicevei" # Further tagging in update_tags function
# Update tags in segment, including required corrections for motorway, maxspeed and street name
# This is the only place to make road object tagging dependent on earlier basic highway tagging based on road reference
def update_tags (segment, tags, direction):
# Get right key, if highway
if "construction" in segment['tags']:
highway = "construction"
elif "proposed" in segment['tags']:
highway = "proposed"
else:
highway = "highway"
# Please note only if/elif below due to catch-all at the end
# Keep name and unclassified update together
if "name" in tags or "mainroad" in tags:
# No street name for cycleways/footways and roundabouts
if "name" in tags and not ("junction" in segment['tags'] and segment['tags']['junction'] == "roundabout"):
segment['tags']['name'] = tags['name']