-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathmmqgis_library.py
5295 lines (4059 loc) · 170 KB
/
mmqgis_library.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
# --------------------------------------------------------
# mmqgis_library - mmqgis operation functions
#
# begin : 10 May 2010
# copyright : (c) 2010 by Michael Minn
# email : See michaelminn.com
#
# MMQGIS is free software and is offered without guarantee
# or warranty. You can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public
# License (GPL v2) as published by the Free Software
# Foundation (www.gnu.org).
# --------------------------------------------------------
import io
import re
import csv
import sys
import time
import locale
import random
import urllib2
import os.path
import operator
import tempfile
import xml.etree.ElementTree
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# Used instead of "import math" so math functions can be used without "math." prefix
from math import *
# --------------------------------------------------------
# MMQGIS Utility Functions
# --------------------------------------------------------
# Needed to replace the useful function QgsVectorLayer::featureAtId()
# that was tantalizingly added in 1.9 but then removed
def mmqgis_feature_at_id(layer, featureid):
iterator = layer.getFeatures(QgsFeatureRequest(featureid))
feature = QgsFeature()
if iterator.nextFeature(feature):
return feature
return None
def mmqgis_find_layer(layer_name):
# print "find_layer(" + str(layer_name) + ")"
#for name, search_layer in QgsMapLayerRegistry.instance().mapLayers().iteritems():
# if search_layer.name() == layer_name:
# return search_layer
if not layer_name:
return None
layers = QgsMapLayerRegistry.instance().mapLayersByName(layer_name)
if (len(layers) >= 1):
return layers[0]
return None
def mmqgis_is_float(s):
try:
float(s)
return True
except:
return False
# Cumbersome function to give backward compatibility before python 2.7
def mmqgis_format_float(value, separator, decimals):
formatstring = ("%0." + unicode(int(decimals)) + "f")
# print str(value) + ": " + formatstring
string = formatstring % value
intend = string.find('.')
if intend < 0:
intend = len(string)
if separator and (intend > 3):
start = intend % 3
if start == 0:
start = 3
intstring = string[0:start]
for x in range(start, intend, 3):
intstring = intstring + separator + string[x:x+3]
string = intstring + string[intend:]
return string
def mmqgis_gridify_points(hspacing, vspacing, points):
# Align points to grid
point_count = 0
deleted_points = 0
newpoints = []
for point in points:
point_count += 1
newpoints.append(QgsPoint(round(point.x() / hspacing, 0) * hspacing, \
round(point.y() / vspacing, 0) * vspacing))
# Delete overlapping points
z = 0
while z < (len(newpoints) - 2):
if newpoints[z] == newpoints[z + 1]:
newpoints.pop(z + 1)
deleted_points += 1
else:
z += 1
# Delete line points that go out and return to the same place
z = 0
while z < (len(newpoints) - 3):
if newpoints[z] == newpoints[z + 2]:
newpoints.pop(z + 1)
newpoints.pop(z + 1)
deleted_points += 2
# Step back to catch arcs
if (z > 0):
z -= 1
else:
z += 1
# Delete overlapping start/end points
while (len(newpoints) > 1) and (newpoints[0] == newpoints[len(newpoints) - 1]):
newpoints.pop(len(newpoints) - 1)
deleted_points += 2
return newpoints, point_count, deleted_points
# http://stackoverflow.com/questions/3410976/how-to-round-a-number-to-significant-figures-in-python
def mmqgis_round(number, digits):
if (number == 0):
return 0
else:
return round(number, digits - int(floor(log10(abs(number)))) - 1)
# Use common address abbreviations to reduce naming discrepancies and improve hit ratio
def mmqgis_searchable_streetname(name):
# print "searchable_name(" + str(name) + ")"
if not name:
return ""
# name = unicode(name).strip().lower()
name = name.strip().lower()
name = name.replace(".", "")
name = name.replace(" street", " st")
name = name.replace(" avenue", " av")
name = name.replace(" plaza", " plz")
name = name.replace(" drive", " dr")
name = name.replace("saint ", "st ")
name = name.replace("fort ", "ft ")
name = name.replace(" ave", " av")
name = name.replace("east", "e")
name = name.replace("west", "w")
name = name.replace("north", "n")
name = name.replace("south", "s")
name = name.replace("1st", "1")
name = name.replace("2nd", "2")
name = name.replace("3rd", "3")
name = name.replace("4th", "4")
name = name.replace("5th", "5")
name = name.replace("6th", "6")
name = name.replace("7th", "7")
name = name.replace("8th", "8")
name = name.replace("9th", "9")
name = name.replace("0th", "0")
name = name.replace("1th", "1")
name = name.replace("2th", "2")
name = name.replace("3th", "3")
return name
# Parses and normalizes street addresses to make search easier.
# Returns list: [number street unit]
def mmqgis_normalize_address(address):
if not address:
return [None, None, None]
# Everything upper case
address = address.strip()
address = address.upper()
# Remove confusing punctuation
address = address.replace(".", "")
address = address.replace(",", "")
# address = address.replace("#", "")
parts = address.split()
if (len(parts) <= 1):
return [None, address, None]
# Find Unit Number (if any)
unit = None
if (len(parts) >= 3) and (parts[len(parts) - 2] == "SUITE"):
unit = parts[len(parts) - 1]
del parts[(len(parts) - 2):len(parts)]
elif (len(parts) >= 3) and (parts[len(parts) - 2] == "UNIT"):
unit = parts[len(parts) - 1]
del parts[(len(parts) - 2):len(parts)]
elif (len(parts) >= 3) and (parts[len(parts) - 2] == "STE"):
unit = parts[len(parts) - 1]
del parts[(len(parts) - 2):len(parts)]
elif (len(parts) >= 3) and (parts[len(parts) - 2] == "FLOOR"):
unit = "FLOOR " + unicode(parts[len(parts) - 1])
del parts[(len(parts) - 2):len(parts)]
elif (len(parts) > 1) and (parts[len(parts) - 1][0] == "#"):
unit = parts[len(parts) - 1].replace('#','')
del parts[len(parts) - 1]
# Find Lot Number (if any)
number = None
if (len(parts) >= 3) and (not parts[0][0].isdigit()) and \
(parts[len(parts) - 2][0].isdigit()) and (parts[len(parts) - 1][0].isdigit()):
# European street number + unit number last
number = parts[len(parts) - 2]
del parts[len(parts) - 2]
elif (not parts[0][0].isdigit() and (parts[len(parts) - 1][0].isdigit())):
# European street number last
number = parts[len(parts) - 1]
del parts[len(parts) - 1]
elif parts[0][0].isdigit():
# American street number first
number = parts[0]
del parts[0]
# Replace numeric suffixes
suffixes = {
"1ST": "1",
"2ND": "2",
"3RD": "3",
"4TH": "4",
"5TH": "5",
"6TH": "6",
"7TH": "7",
"8TH": "8",
"9TH": "9",
"0TH": "0",
"1TH": "1",
"2TH": "2",
"3TH": "3" }
# Regular expressions are much faster than loop
# https://www.safaribooksonline.com/library/view/python-cookbook-2nd/0596007973/ch01s19.html
regex = re.compile("(%s)" % "|".join(suffixes.keys()))
for index, part in enumerate(parts):
parts[index] = regex.sub(lambda x: suffixes[x.group(0)], part)
#for suffix in suffixes:
# for index, part in enumerate(parts):
# parts[index] = part.replace(suffix[0], suffix[1])
# Text versions of numbered streets
number_words = {
"FIRST": "1",
"SECOND": "2",
"THIRD": "3",
"FOURTH": "4",
"FIFTH": "5",
"SIXTH": "6",
"SEVENTH": "7",
"EIGHTH": "8",
"NINTH": "9",
"TENTH": "10",
"ELEVENTH": "11",
"TWELFTH": "12",
"THIRTEENTH": "13",
"FOURTEENTH": "14",
"FIFTEENTH": "15",
"SIXTEENTH": "16",
"SEVENTEENTH": "17",
"EIGHTEENTH": "18",
"NINTEENTH": "19",
"TWENTIETH": "20" }
parts = map(lambda x: number_words.get(x, x), parts)
# Full strings replaced with abbreviations because
# replacing abbreviations with full strings would involve uncertain inference
# while replacing full strings with abbreviations increases
# potential matches at the expense of accuracy
abbreviations = {
"STREET": "ST",
"BOULEVARD": "BLVD",
"PARKWAY": "PKWY",
"HIGHWAY": "HWY",
"CIRCLE": "CIR",
"AVENUE": "AV",
"PLACE": "PL",
"PLAZA": "PL",
"DRIVE": "DR",
"SAINT": "ST",
"NORTH": "N",
"SOUTH": "S",
"FORT": "FT",
"ROAD": "RD",
"EAST": "E",
"WEST": "W",
"AVE": "AV"}
# map() is faster than loop
parts = map(lambda x: abbreviations.get(x, x), parts)
#for abbreviation in abbreviations:
# for index, part in enumerate(parts):
# if (part == abbreviation[0]):
# parts[index] = abbreviation[1]
# Recombine into street name
street = ' '.join(parts)
return [number, street, unit]
def mmqgis_geocode_address_google(address, apikey):
if apikey:
url = "https://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=" + address + "&key=" + apikey
else:
url = "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=" + address
max_attempts = 5
for attempt in range(1, max_attempts + 1):
try:
xml = urllib2.urlopen(url).read()
break
except Exception, e:
message = "Failure connecting to maps.googleapis.com: " + unicode(e)
if (attempt >= max_attempts):
return message, None, None, None, None
# Wait a second and try again
time.sleep(1)
if (xml.find('OVER_QUERY_LIMIT') > 0):
return "Exceeded Daily Google Limit", None, None, None, None
if (xml.find('The provided API key is invalid.') > 0):
return "Invalid API Key", None, None, None, None
if (xml.find('REQUEST_DENIED') > 0):
return "Request Denied", None, None, None, None
#print(url)
resultstart = 0
x = []
y = []
addrtype = []
addrlocat = []
formatted_addr = []
resultstart = xml.find("<result>")
while (resultstart > 0):
resultend = xml.find("</result>", resultstart)
if (resultend < 0):
resultend = len(xml)
result = xml[resultstart:resultend]
resultstart = xml.find("<result>", resultend)
latstart = result.find("<lat>")
latend = result.find("</lat>")
if (latstart < 0) or (latend < (latstart + 5)):
continue
longstart = result.find("<lng>")
longend = result.find("</lng>")
if (longstart < 0) and (longend < (longstart + 5)):
continue
y.append(float(result[latstart + 5:latend]))
x.append(float(result[longstart + 5:longend]))
addrtypestart = result.find("<type>")
addrtypeend = result.find("</type>")
if (addrtypestart > 0) and (addrtypeend > (addrtypestart + 6)):
addrtype.append(unicode(result[(addrtypestart + 6):addrtypeend], 'utf-8').strip())
else:
addrtype.append("")
addrlocatstart = result.find("<location_type>")
addrlocatend = result.find("</location_type>")
if (addrlocatstart > 0) and (addrlocatend > (addrlocatstart + 15)):
addrlocat.append(unicode(result[(addrlocatstart + 15):addrlocatend], 'utf-8').strip())
else:
addrlocat.append("")
formstart = result.find("<formatted_address>")
formend = result.find("</formatted_address>")
if (formstart > 0) and (formend > (formstart + 19)):
formatted_addr.append(unicode(result[(formstart + 19):formend], 'utf-8').strip())
else:
formatted_addr.append(address)
return x, y, addrtype, addrlocat, formatted_addr
def mmqgis_geocode_address_osm(address):
url = "http://nominatim.openstreetmap.org/search?format=xml&q=" + address
max_attempts = 5
for attempt in range(1, max_attempts + 1):
try:
osm = urllib2.urlopen(url).read()
break
except Exception, e:
message = "Failure connecting to maps.googleapis.com: " + unicode(e)
if (attempt >= max_attempts):
return message, None, None, None, None
# Wait a second and try again
time.sleep(1)
# print(url)
# print(osm)
x = []
y = []
addrtype = []
addrlocat = []
formatted_addr = []
# Parse the XML
try:
results = xml.etree.ElementTree.fromstring(osm)
# results = tree.getroot()
except:
# print("XML Parser Failure")
return None, None, None, None, None
# Parse <place> under <searchresults>
for place in results:
try:
lat = place.attrib['lat']
lon = place.attrib['lon']
except:
lat = None
lon = None
try:
aclass = place.attrib['class']
except:
aclass = ""
try:
atype = place.attrib['type']
except:
atype = ""
try:
aname = place.attrib['display_name']
except:
aname = ""
# print(lat, lon)
if (lat != None) and (lon != None):
x.append(float(lon))
y.append(float(lat))
addrtype.append(aclass)
addrlocat.append(atype)
formatted_addr.append(aname)
return x, y, addrtype, addrlocat, formatted_addr
# Legacy code left here for reference if anything breaks in new XML parsing 1/31/2016
def mmqgis_old_geocode_address_osm(address):
url = "http://nominatim.openstreetmap.org/search?format=xml&q=" + address
try:
xml = urllib2.urlopen(url).read()
except:
# URLError as e: e.reason
return "Failure connecting to nominatim.openstreetmap.org", None, None, None, None
#print(url)
#print(xml)
x = []
y = []
addrtype = []
addrlocat = []
formatted_addr = []
placestart = xml.find("<place")
while (placestart > 0):
placeend = xml.find("/>", placestart)
if (placeend < 0):
placeend = len(xml)
place = xml[placestart:placeend]
placestart = xml.find("<place", placeend)
latstart = place.find('lat="')
latend = place.find('"', latstart + 5)
if (latstart < 0) or (latend < (latstart + 5)):
continue
longstart = place.find('lon="')
longend = place.find('"', longstart + 5)
if (latstart < 0) or (latend < (latstart + 5)):
continue
y.append(float(place[latstart + 5:latend]))
x.append(float(place[longstart + 5:longend]))
addrtypestart = place.find("class=")
addrtypeend = place.find("'", addrtypestart + 7)
if (addrtypestart > 0) and (addrtypeend > (addrtypestart + 7)):
addrtype.append(unicode(place[(addrtypestart + 7):addrtypeend], 'utf-8').strip())
else:
addrtype.append("")
addrlocatstart = place.find("type=")
addrlocatend = place.find("'", addrlocatstart + 6)
if (addrlocatstart > 0) and (addrlocatend > (addrlocatstart + 6)):
addrlocat.append(unicode(place[(addrlocatstart + 6):addrlocatend], 'utf-8').strip())
else:
addrlocat.append("")
formstart = place.find("display_name=")
formend = place.find("'", formstart + 14)
if (formstart > 0) and (formend > (formstart + 14)):
formatted_addr.append(unicode(place[(formstart + 14):formend], 'utf-8').strip())
else:
formatted_addr.append(address)
return x, y, addrtype, addrlocat, formatted_addr
def mmqgis_wkbtype_to_text(wkbtype):
if wkbtype == QGis.WKBUnknown: return "Unknown"
if wkbtype == QGis.WKBPoint: return "point"
if wkbtype == QGis.WKBLineString: return "linestring"
if wkbtype == QGis.WKBPolygon: return "polygon"
if wkbtype == QGis.WKBMultiPoint: return "multipoint"
if wkbtype == QGis.WKBMultiLineString: return "multilinestring"
if wkbtype == QGis.WKBMultiPolygon: return "multipolygon"
if wkbtype == QGis.WKBPoint25D: return "point 2.5d"
if wkbtype == QGis.WKBLineString25D: return "linestring 2.5D"
if wkbtype == QGis.WKBPolygon25D: return "polygon 2.5D"
if wkbtype == QGis.WKBMultiPoint25D: return "multipoint 2.5D"
if wkbtype == QGis.WKBMultiLineString25D: return "multilinestring 2.5D"
if wkbtype == QGis.WKBMultiPolygon25D: return "multipolygon 2.5D"
return "Unknown WKB " + unicode(wkbtype)
def mmqgis_status_message(qgis, message):
qgis.mainWindow().statusBar().showMessage(message)
def mmqgis_completion_message(qgis, message):
mmqgis_status_message(qgis, message)
qgis.messageBar().pushMessage(message, 0, 3)
def mmqgis_distance(start, end):
# Assumes points are WGS 84 lat/long
# Returns great circle distance in meters
radius = 6378137 # meters
flattening = 1/298.257223563
# Convert to radians with reduced latitudes to compensate
# for flattening of the earth as in Lambert's formula
start_lon = start.x() * pi / 180
start_lat = atan2((1 - flattening) * sin(start.y() * pi / 180), cos(start.y() * pi / 180))
end_lon = end.x() * pi / 180
end_lat = atan2((1 - flattening) * sin(end.y() * pi / 180), cos(end.y() * pi / 180))
# Haversine formula
arc_distance = (sin((end_lat - start_lat) / 2) ** 2) + \
(cos(start_lat) * cos(end_lat) * (sin((end_lon - start_lon) / 2) ** 2))
return 2 * radius * atan2(sqrt(arc_distance), sqrt(1 - arc_distance))
def mmqgis_bearing(start, end):
# Assumes points are WGS 84 lat/long
# http://www.movable-type.co.uk/scripts/latlong.html
start_lon = start.x() * pi / 180
start_lat = start.y() * pi / 180
end_lon = end.x() * pi / 180
end_lat = end.y() * pi / 180
return atan2(sin(end_lon - start_lon) * cos(end_lat), \
(cos(start_lat) * sin(end_lat)) - \
(sin(start_lat) * cos(end_lat) * cos(end_lon - start_lon))) \
* 180 / pi
def mmqgis_endpoint(start, distance, degrees):
# Assumes points are WGS 84 lat/long, distance in meters,
# bearing in degrees with north = 0, east = 90, west = -90
# Uses the haversine formula for calculation:
# http://www.movable-type.co.uk/scripts/latlong.html
radius = 6378137.0 # meters
start_lon = start.x() * pi / 180
start_lat = start.y() * pi / 180
bearing = degrees * pi / 180
end_lat = asin((sin(start_lat) * cos(distance / radius)) +
(cos(start_lat) * sin(distance / radius) * cos(bearing)))
end_lon = start_lon + atan2( \
sin(bearing) * sin(distance / radius) * cos(start_lat),
cos(distance / radius) - (sin(start_lat) * sin(end_lat)))
return QgsPoint(end_lon * 180 / pi, end_lat * 180 / pi)
def mmqgis_feet_to_meters(feet):
return feet / 3.2808399
def mmqgis_meters_to_feet(meters):
return meters * 3.2808399
def mmqgis_miles_to_meters(miles):
return miles * 1609.344
def mmqgis_meters_to_miles(meters):
return meters / 1609.344
#chm = QgsPoint(-88.241161, 40.115742)
#dav = QgsPoint(-88.226386,40.1072)
#chi = QgsPoint(-87.640368,41.877438)
#jan = QgsPoint(-90.191065, 32.301516)
#ufl = QgsPoint(-88.209445, 40.111328)
def mmqgis_buffer_geometry(geometry, meters):
if meters <= 0:
return None
# To approximate meaningful meter distances independent of the original CRS,
# the geometry is transformed to an azimuthal equidistant projection
# with the center of the polygon as the origin. After buffer creation,
# the buffer is transformed to WGS 84 and returned. While this may introduce
# some deviation from the original CRS, buffering is assumed in practice
# to be a fairly inexact operation that can tolerate such deviation
wgs84 = QgsCoordinateReferenceSystem()
wgs84.createFromProj4("+proj=longlat +datum=WGS84 +no_defs")
latitude = str(geometry.centroid().asPoint().y())
longitude = str(geometry.centroid().asPoint().x())
#proj4 = "+proj=aeqd +lat_0=" + str(geometry.centroid().asPoint().y()) + \
# " +lon_0=" + str(geometry.centroid().asPoint().x()) + \
# " +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"
# For some reason, Azimuthal Equidistant transformation noticed to not be
# working on 10 July 2014. World Equidistant Conic works, but there may be errors.
proj4 = "+proj=eqdc +lat_0=0 +lon_0=0 +lat_1=60 +lat_2=60 " + \
"+x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"
azimuthal_equidistant = QgsCoordinateReferenceSystem()
azimuthal_equidistant.createFromProj4(proj4)
transform = QgsCoordinateTransform(wgs84, azimuthal_equidistant)
geometry.transform(transform)
newgeometry = geometry.buffer(meters, 7)
wgs84 = QgsCoordinateReferenceSystem()
wgs84.createFromProj4("+proj=longlat +datum=WGS84 +no_defs")
transform = QgsCoordinateTransform(azimuthal_equidistant, wgs84)
newgeometry.transform(transform)
return newgeometry
def mmqgis_buffer_point(point, meters, edges, rotation_degrees):
if (meters <= 0) or (edges < 3):
return None
# Points are treated separately from other geometries so that discrete
# edges can be supplied for non-circular buffers that are not supported
# by the QgsGeometry.buffer() function
wgs84 = QgsCoordinateReferenceSystem()
wgs84.createFromProj4("+proj=longlat +datum=WGS84 +no_defs")
# print "Point " + unicode(point.x()) + ", " + unicode(point.y()) + " meters " + unicode(meters)
polyline = []
for edge in range(0, edges + 1):
degrees = ((float(edge) * 360.0 / float(edges)) + rotation_degrees) % 360
polyline.append(mmqgis_endpoint(point, meters, degrees))
return QgsGeometry.fromPolygon([polyline])
def mmqgis_buffer_line_side(geometry, width, direction):
# width in meters
# direction should be 0 for north side, 90 for east, 180 for south, 270 for west
# print "\nmmqgis_buffer_line_side(" + unicode(direction) + ")"
if (geometry.wkbType() == QGis.WKBMultiLineString) or \
(geometry.wkbType() == QGis.WKBMultiLineString25D):
multipolygon = None
for line in geometry.asMultiPolyline():
segment = mmqgis_buffer_line_side(QgsGeometry.fromPolyline(line), width, direction)
if multipolygon == None:
multipolygon = segment
else:
multipolygon = multipolygon.combine(segment)
# print " Build multipolygon " + str(multipolygon.isGeosValid())
# Multiline always has multipolygon buffer even if buffers merge into one polygon
if multipolygon.wkbType() == QGis.WKBPolygon:
multipolygon = QgsGeometry.fromMultiPolygon([multipolygon.asPolygon()])
# print "Final Multipolygon " + str(multipolygon.isGeosValid())
return multipolygon
if (geometry.wkbType() != QGis.WKBLineString) and \
(geometry.wkbType() != QGis.WKBLineString25D):
return geometry
points = geometry.asPolyline()
line_bearing = mmqgis_bearing(points[0], points[-1]) % 360
# Determine side of line to buffer based on angle from start point to end point
# "bearing" will be 90 for right side buffer, -90 for left side buffer
direction = round((direction % 360) / 90) * 90
if (direction == 0): # North
if (line_bearing >= 180):
bearing = 90 # Right
else:
bearing = -90 # Left
elif (direction == 90): # East
if (line_bearing >= 270) or (line_bearing < 90):
bearing = 90 # Right
else:
bearing = -90 # Left
elif (direction == 180): # South
if (line_bearing < 180):
bearing = 90 # Right
else:
bearing = -90 # Left
else: # West
if (line_bearing >= 90) and (line_bearing < 270):
bearing = 90 # Right
else:
bearing = -90 # Left
# Buffer individual segments
polygon = None
for z in range(0, len(points) - 1):
b1 = mmqgis_bearing(points[z], points[z + 1]) % 360
# Form rectangle beside line
# 2% offset mitigates topology floating-point errors
linestring = [QgsPoint(points[z])]
if (z == 0):
linestring.append(mmqgis_endpoint(points[z], width, b1 + bearing))
else:
linestring.append(mmqgis_endpoint(points[z], width, b1 + (1.02 * bearing)))
linestring.append(mmqgis_endpoint(points[z + 1], width, b1 + bearing))
# Determine if rounded convex elbow is needed
if (z < (len(points) - 2)):
b2 = mmqgis_bearing(points[z + 1], points[z + 2]) % 360
elbow = b2 - b1
if (elbow < -180):
elbow = elbow + 360
elif (elbow > 180):
elbow = elbow - 360
# print unicode(b1) + ", " + unicode(b2) + " = " + unicode(elbow)
# 8-step interpolation of arc
if (((bearing > 0) and (elbow < 0)) or \
((bearing < 0) and (elbow > 0))):
for a in range(1,8):
b = b1 + (elbow * a / 8.0) + bearing
linestring.append(mmqgis_endpoint(points[z + 1], width, b))
# print " arc: " + unicode(b)
linestring.append(mmqgis_endpoint(points[z + 1], width, b2 + bearing))
# Close polygon
linestring.append(QgsPoint(points[z + 1]))
linestring.append(QgsPoint(points[z]))
segment = QgsGeometry.fromPolygon([linestring])
# print linestring
# print " Line to polygon " + str(segment.isGeosValid())
if (polygon == None):
polygon = segment
else:
polygon = polygon.combine(segment)
#print " Polygon build " + str(polygon.isGeosValid())
#if not polygon.isGeosValid():
# print polygon.asPolygon()
# print " Final polygon " + str(polygon.isGeosValid())
return polygon
def mmqgis_line_center(geometry, distance_percent):
try:
geometry_type = geometry.wkbType()
except:
return None
# Find the list of node points
# This function is only really meaningful for linestrings
if (geometry_type == QGis.WKBPoint) or (geometry_type == QGis.WKBPoint25D):
return geometry
elif (geometry_type == QGis.WKBLineString) or (geometry_type == QGis.WKBLineString25D):
points = geometry.asPolyline()
elif (geometry_type == QGis.WKBPolygon) or (geometry_type == QGis.WKBPolygon25D):
points = geometry.asPolygon()[0]
elif (geometry_type == QGis.WKBMultiPoint) or (geometry_type == QGis.WKBMultiPoint25D):
points = geometry.asMultiPoint()
elif (geometry_type == QGis.WKBMultiLineString) or (geometry_type == QGis.WKBMultiLineString25D):
points = geometry.asMultiPolyline()[0]
elif (geometry_type == QGis.WKBMultiPolygon) or (geometry_type == QGis.WKBMultiPolygon25D):
points = geometry.asMultiPolygon()[0][0]
else:
return None
# Returns for invalid parameters
if (len(points) <= 0):
return None
if (len(points) <= 1):
return QgsGeometry.fromPoint(points[0])
if (distance_percent <= 0):
return QgsGeometry.fromPoint(points[0])
if (distance_percent >= 100):
return QgsGeometry.fromPoint(points[len(points) - 1])
# Find lengths of segments between nodes
segment_length = []
for index in range(0, len(points) - 1):
point1 = points[index]
point2 = points[index + 1]
length = sqrt(((point1.x() - point2.x())**2) + ((point1.y() - point2.y())**2))
segment_length = segment_length + [length]
# Find the point on the appropriate segment line
segment_start = 0
distance = sum(segment_length) * distance_percent / 100.0
for index in range(0, len(segment_length)):
segment_end = segment_start + segment_length[index]
if (distance >= segment_start) and (distance <= segment_end):
if (segment_length[index] <= 0):
ratio = 0
else:
ratio = (distance - segment_start) / segment_length[index]
xdiff = points[index + 1].x() - points[index].x()
ydiff = points[index + 1].y() - points[index].y()
linex = points[index].x() + (xdiff * ratio)
liney = points[index].y() + (ydiff * ratio)
return QgsGeometry.fromPoint(QgsPoint(linex, liney))
segment_start = segment_end
# Graceful failure - Shouldn't ever get here
return QgsGeometry.fromPoint(points[0])
# --------------------------------------------------------
# mmqgis_street_address_join - join address CSV
# with vector shapes using fuzzy address match
# --------------------------------------------------------
def mmqgis_street_address_join(qgis, shapelayer, shapeaddress, csvname, csvaddress, outfilename, notfoundname, addlayer):
# Find the layer of shapes
layer = mmqgis_find_layer(shapelayer)
if layer == None:
return "Shape layer not found: " + layername
layer_index = layer.fieldNameIndex(shapeaddress)
if (layer_index < 0):
return "Shape layer address field " + shapeaddress + " not found"
if len(csvname) <= 0:
return "No CSV address file given"
mmqgis_status_message(qgis, "Loading and processing CSV file");
# Read the CSV addresses into memory
try:
infile = open(csvname, 'r')
dialect = csv.Sniffer().sniff(infile.read(4096))
infile.seek(0)
reader = csv.reader(infile, dialect)
addresses = list(reader)
del reader
del infile
except Exception as e:
return unicode(csvname) + ": " + unicode(e)
# Decode from UTF-8 characters because csv.reader can only handle 8-bit characters
for rownum, row in enumerate(addresses):
try:
addresses[rownum] = [unicode(field, "utf-8") for field in row]
except:
return "Row " + unicode(rownum) + " in CSV file not in UTF-8 encoding"
# Find the address field from the CSV file
header = addresses[0]
del addresses[0]
try:
csvindex = header.index(csvaddress)
except:
return "Column " + unicode(csvindex) + " not found in " + unicode(csvname)
# Combine attribute fields
fields = QgsFields()
for field in layer.fields():
fields.append(field)
for field in header:
newname = field[0:10].strip()
if (fields.indexFromName(newname) >= 0):
newname = newname[0:9] + '2'
fields.append(QgsField(newname, QVariant.String))
# notfound file for addresses that were not numeric or were not joined
try:
notfound = open(notfoundname, 'w')
notfoundwriter = csv.writer(notfound, dialect)
# Encoding is forced to UTF-8 because CSV writer doesn't support Unicode
notfoundwriter.writerow([field.encode("utf-8") for field in header])
except:
return "Failure opening " + notfoundname
# Create the output shapefile
if QFile(outfilename).exists():
if not QgsVectorFileWriter.deleteShapeFile(outfilename):
return "Failure deleting existing shapefile: " + outfilename
outfile = QgsVectorFileWriter(outfilename, "utf-8", fields, layer.wkbType(), layer.crs())
if (outfile.hasError() != QgsVectorFileWriter.NoError):
return "Failure creating output shapefile: " + unicode(outfile.errorMessage())
# Iterate through each feature in the shape layer
matched_count = 0