/
xgps.py
1481 lines (1182 loc) · 42.7 KB
/
xgps.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
######################
#xgps.py.c -- Gui for my Gps Program
#Creation date: March 10, 2010
#Last updated: April 8, 2010
#Description:
#This provides a GUI interface to assignment #2, and also utilizes
#Google maps to provide awesomness,
#also utilizes a database to store and retrieve hike information
#and display these hikes through google earth
#Problems:
#- wont warn the removing waypts will also remove routes
#- modal windows arent modal (allow access to original window)
#- hikes all have the same colour
#- cant query with % wildcard symbol
#David Farr
#0629099
#farrd@uoguelph.ca
#######################
#!/usr/bin/python
import os
from math import *
from Tkinter import *
import tkFileDialog
import tkColorChooser
from subprocess import Popen, PIPE
import MySQLdb
# import the shared library and the maps
import Gps
from GMapData import *
# some global variables
filename = ''
delete = 0
rIndex = 0
hikeno = 0
ptno = 0
fileno = 0
waypts=[]
routes=[]
trkpts=[]
tracks=[]
wColour = 0
rColour = "#00ff00"
tColour = 1
trColour = "#efef00"
# start the web server
startWebServer(49099)
# connect to database (default host)
if len(sys.argv) == 3:
try:
db = MySQLdb.connect (host = "db.cis.uoguelph.ca",
user = sys.argv[1],
passwd = sys.argv[2],
db = sys.argv[1])
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)
# connect to database (provided host)
elif len(sys.argv) == 4:
try:
db = MySQLdb.connect (host = sys.argv[3],
user = sys.argv[1],
passwd = sys.argv[2],
db = sys.argv[1])
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)
# provide proper command line prototype,
# and then exit if not entered properly
else:
print "Invalid use of xgps"
print "The correct command line argument is:"
print " python xgps.py username password [hostname]"
sys.exit(1)
# make the tables if they dont exist
cursor = db.cursor()
hike = """ CREATE TABLE IF NOT EXISTS HIKE (
hikeno INT AUTO_INCREMENT,
name VARCHAR(30),
location VARCHAR(30),
comment VARCHAR(80),
rating SMALLINT,
note TINYTEXT,
PRIMARY KEY(hikeno) ) """
waypts = """ CREATE TABLE IF NOT EXISTS WAYPTS (
fileno INT,
ptno INT,
id VARCHAR(30),
comment VARCHAR(80),
lat DOUBLE,
lon DOUBLE,
PRIMARY KEY(fileno, ptno) ) """
hikepts = """ CREATE TABLE IF NOT EXISTS HIKEPTS (
hikeno INT,
fileno INT,
ptno INT,
leg INT,
distance FLOAT,
PRIMARY KEY(hikeno, leg),
FOREIGN KEY(hikeno) REFERENCES HIKE(hikeno),
FOREIGN KEY(fileno) REFERENCES WAYPTS(fileno),
FOREIGN KEY(fileno) REFERENCES WAYPTS(ptno) ) """
cursor.execute(hike)
cursor.execute(waypts)
cursor.execute(hikepts)
#change some settings so TRANACTION, COMMIT, ROLLBACK work
cursor.execute("SET autocommit = 0")
cursor.execute("ALTER TABLE HIKE ENGINE = InnoDB")
cursor.execute("ALTER TABLE WAYPTS ENGINE = InnoDB")
cursor.execute("ALTER TABLE HIKEPTS ENGINE = InnoDB")
# Open up a new Gps File
def openGps(event):
global filename, hikeno, fileno, ptno
filename = tkFileDialog.askopenfilename(filetypes = [('Gps', '*.gps')])
if filename != () and filename != '':
# read in the gps file
status = Gps.readFile(filename)
if status != 'OK':
filename = ''
if len(status) == 2:
msgWindow("Error opening file", status[0] + ": " + str(status[1]))
else:
msgWindow("Error opening file", status)
filemenu.entryconfig(2, state="disabled")
filemenu.entryconfig(3, state="disabled")
limitOptions()
else:
global delete
delete = 1
# update the title
root.title("David's GPS Program: " + filename)
# get the output from the gps file
fileInfo = os.popen("./gpstool -info < " + filename + " 2>> log.txt")
# read in the info for the components
global waypts, routes, trkpts, tracks
waypts, routes, trkpts, tracks = Gps.getData(waypts, routes, trkpts, tracks)
free = Gps.freeFile()
# change the options available, and update some stuff
filemenu.entryconfig(2, state="normal")
filemenu.entryconfig(3, state="normal")
hikemenu.entryconfig(0, state="normal")
hikemenu.entryconfig(1, state="normal")
limitOptions()
writeInfo(fileInfo)
updateLog()
# get the biggest hikeno
getHikeno = "SELECT MAX(hikeno) FROM HIKE"
cursor.execute(getHikeno)
temp = cursor.fetchone()
if temp[0] == None:
hikeno = 0
else:
hikeno = temp[0]
# get the biggest fileno
getFileno = "SELECT MAX(fileno) FROM WAYPTS"
cursor.execute(getFileno)
temp = cursor.fetchone()
if temp[0] == None:
fileno = 1
else:
fileno = temp[0] + 1
# set the ptno to 0
ptno = 0
# write the remaing info out to the temporary file
def writeInfo(fileInfo):
# clear the panel
info.config(state=NORMAL)
info.delete(1.0, END)
info.config(state=DISABLED)
# write the gps info to the panel
info.config(state=NORMAL)
for index in range(0, 5):
info.insert(INSERT, fileInfo.readline())
info.config(state=DISABLED)
# write the rest of the file out to a temp file
temp = open("temp_gps_file.gps", "w")
for index in fileInfo.readlines():
temp.write(index)
temp.close()
# update the log file on the screen
def updateLog():
# write any error out to the log area
log.config(state=NORMAL)
logFile = open("log.txt", "r")
log.insert(INSERT, logFile.read())
log.config(state=DISABLED)
logFile.close()
# read in the stuff for routes and tracks
routeList.delete(0, END)
trackList.delete(0, END)
for item in routes:
routeList.insert(END, str(item[0]) + " - " + item[1])
for item in tracks:
trackList.insert(END, str(item[0]) + " - " + item[1])
# save the file
def save(event):
if filename != () and filename != '':
# open the necessary files
fTo = open(filename, "w")
fFrom = open("temp_gps_file.gps", "r")
fTo.write(fFrom.read())
# close the files
fTo.close()
fFrom.close()
# save the file under a different name
def saveAs(event):
global filename
if filename != () and filename != '':
fTo = tkFileDialog.asksaveasfile(filetypes = [('Gps', '*.gps')])
filename = fTo.name
root.title("David's GPS Program: " + filename)
# open the necessary files
fFrom = open("temp_gps_file.gps", "r")
fTo.write(fFrom.read())
# close the files
fTo.close()
fFrom.close()
# the discard and keep option,
# this function will either keep components or remove them
# NOTE will not warn about waypoints implicating the removal of routes
def remove(option):
msg = Toplevel(padx=80, pady=5)
if(option == "keep"):
msg.title("Choose what should be kept")
else:
msg.title("Choose what should be discarded")
def kill(event):
msg.destroy()
msg.bind("<Escape>", kill)
w = StringVar()
r = StringVar()
t = StringVar()
def ok():
msg.destroy()
global waypts, routes, trkpts, tracks
# get the arguments
_w = w.get()
_r = r.get()
_t = t.get()
args = _w + _r + _t
cont = 1
if (option == "discard" and _w == "w" and _t == "t") or (option == "keep" and _w == "" and _t == "") or (option == "discard" and _w == "w" and not trkpts) or (option == "discard" and _t == "t" and not waypts):
modal("Error", "Cannot discard all components")
cont = 0
cont2 = 1
#if (cont == 1) and ((option == "discard" and _w == "w" and _r == "" and routes) or (option == "keep" and _w == "" and _r == "r")):
#cont2 = modal("Warning", "Discarding waypoints will also remove the routes, do you wish to continue?")
# make sure this can be done
if cont == 1 and cont2 == 1:
# discard/keep
fileInfo = os.popen("./gpstool -" + option + " " + args + " < temp_gps_file.gps 2>> log.txt | ./gpstool -info 2>> log.txt")
writeInfo(fileInfo)
# read in the adjusted file
status = Gps.readFile("temp_gps_file.gps")
if status != 'OK':
if len(status) == 2:
msgWindow("Error opening file", status[0] + ": " + str(status[1]))
else:
msgWindow("Error opening file", status)
else:
# read in the info for the components
waypts, routes, trkpts, tracks = Gps.getData(waypts, routes, trkpts, tracks)
free = Gps.freeFile()
updateLog()
limitOptions()
Label(msg, text="Waypoints").grid(row=0, column=0, padx=10, pady=5)
Checkbutton(msg, variable=w, onvalue="w", offvalue="").grid(row=0, column=1)
Label(msg, text="Routes").grid(row=1, column=0, padx=10, pady=5)
Checkbutton(msg, variable=r, onvalue="r", offvalue="").grid(row=1, column=1)
Label(msg, text="Trackpoints").grid(row=2, column=0, padx=10, pady=5)
Checkbutton(msg, variable=t, onvalue="t", offvalue="").grid(row=2, column=1)
Button(msg, text="Cancel", command=msg.destroy).grid(row=3, column=0, padx=5)
Button(msg, text="OK", command=ok).grid(row=3, column=1)
# the merge option
# this will merge new file to the current one
def merge():
file = tkFileDialog.askopenfilename(filetypes = [('Gps', '*.gps')], title = "Choose a file to merge")
# merge the files
fileInfo = os.popen("./gpstool -merge " + file + " < temp_gps_file.gps 2>> log.txt | ./gpstool -info 2>> log.txt")
writeInfo(fileInfo)
# read in the sorted file
status = Gps.readFile("temp_gps_file.gps")
if status != 'OK':
if len(status) == 2:
msgWindow("Error opening file", status[0] + ": " + str(status[1]))
else:
msgWindow("Error opening file", status)
else:
# read in the info for the components
global waypts, routes, trkpts, tracks
waypts, routes, trkpts, tracks = Gps.getData(waypts, routes, trkpts, tracks)
free = Gps.freeFile()
updateLog()
limitOptions()
# the sort option
# sorts the waypoints alphabetically
def sort():
# sort the file
fileInfo = os.popen("./gpstool -sortwp < temp_gps_file.gps 2>> log.txt | ./gpstool -info 2>> log.txt")
writeInfo(fileInfo)
# read in the sorted file
status = Gps.readFile("temp_gps_file.gps")
if status != 'OK':
if len(status) == 2:
msgWindow("Error opening file", status[0] + ": " + str(status[1]))
else:
msgWindow("Error opening file", status)
else:
# read in the info for the components
global waypts, routes, trkpts, tracks
waypts, routes, trkpts, tracks = Gps.getData(waypts, routes, trkpts, tracks)
free = Gps.freeFile()
updateLog()
limitOptions()
# limit the menu options
def limitOptions():
# change the options if some are empty
if not waypts:
w.set(1)
editmenu.entryconfig(2, state="disabled")
else:
w.set(0)
filemenu.entryconfig(5, state="normal")
editmenu.entryconfig(0, state="normal")
editmenu.entryconfig(1, state="normal")
editmenu.entryconfig(2, state="normal")
if not routes:
r.set(1)
routeList.delete(0, END)
else:
w.set(0)
filemenu.entryconfig(5, state="normal")
editmenu.entryconfig(0, state="normal")
editmenu.entryconfig(1, state="normal")
if not trkpts:
t.set(1)
else:
w.set(0)
filemenu.entryconfig(5, state="normal")
editmenu.entryconfig(0, state="normal")
editmenu.entryconfig(1, state="normal")
if not tracks:
tr.set(1)
trackList.delete(0, END)
else:
w.set(0)
# check for all
if not waypts and not routes and not trkpts:
filemenu.entryconfig(2, state="disabled")
filemenu.entryconfig(3, state="disabled")
filemenu.entryconfig(5, state="disabled")
editmenu.entryconfig(0, state="disabled")
editmenu.entryconfig(1, state="disabled")
# Update the display of waypts, trkpts, routes, and tracks
def updateDisplay():
if filename != () and filename != '':
# calculate the average lat/lon
global waypts, trkpts, routes, tracks
lat = 0
lon = 0
avgLat = 0
avgLon = 0
for item in waypts:
lat = lat + item[0]
lon = lon + item[1]
for item in trkpts:
lat = lat + item[0]
lon = lon + item[1]
avgLat = lat / (len(waypts) + len(trkpts))
avgLon = lon / (len(waypts) + len(trkpts))
# make the map, centre it at the average lat/lon
gMap = GMapData(filename, [avgLat, avgLon], 10)
count = 0
# set the colours 0->routes, 1->tracks
colours = (rColour, trColour, "#FFFFFF")
gMap.setColors(colours)
# add the waypoints
if(w.get() == 0):
for item in waypts:
gMap.addPoint(item)
gMap.addOverlay(count, 1, wColour)
count = count + 1
# add the trackpoints
if(t.get() == 0):
for item in trkpts:
gMap.addPoint(item)
gMap.addOverlay(count, 1, tColour)
count = count + 1
# add the routes
rSelect = routeList.curselection()
rSelect = map(int, rSelect)
if(r.get() == 0):
for index in rSelect:
nLegs = 0
start = count
for leg in routes[index][2]:
gMap.addPoint(waypts[leg])
count = count + 1
nLegs = nLegs + 1
gMap.addOverlay(start, nLegs, 0)
# add the tracks
trSelect = trackList.curselection()
trSelect = map(int, trSelect)
if(tr.get() == 0):
for index in trSelect:
# get the upper value
if(index < len(tracks) - 1):
upper = tracks[index + 1][0]
else:
upper = len(trkpts) - 1
nTracks = 0
start = count
for trk in range(tracks[index][0], upper - 1):
gMap.addPoint(trkpts[trk])
count = count + 1
nTracks = nTracks + 1
gMap.addOverlay(start, nTracks, 1)
gMap.serve("public_html/index.html")
launchBrowser("http://localhost:49099/")
# clears the log area
def clear():
# clear the gui area
log.config(state=NORMAL)
log.delete(1.0, END)
log.config(state=DISABLED)
# clear the log file
logClear = open("log.txt", "w")
logClear.write("")
logClear.close()
# exits the GUI, removing temporary files and killing the servers beforehand
def exitGui():
# delete the temporary files and kill the gui
if delete == 1:
os.system("rm temp_gps_file.gps")
os.system("rm log.txt")
db.close()
killServers()
root.destroy()
# choose colours for routes and tracks
def chooseColour(option):
global rColour, trColour
colour = tkColorChooser.askcolor()
if option == 'r':
rBox.create_rectangle(0, 0, 20, 20, fill=colour[1])
rColour = colour[1]
else:
trBox.create_rectangle(0, 0, 20, 20, fill=colour[1])
trColour = colour[1]
# choose colours for waypnts and trkpts
def getColour(option):
msg = Toplevel(padx=40, pady=5)
msg.title("Choose Colour")
def kill(event):
msg.destroy()
msg.bind("<Escape>", kill)
colour = StringVar()
def ok():
global wColour, tColour
msg.destroy()
if option == 'w':
temp = colour.get()
if temp == "red":
wColour = 0
elif temp == "blue":
wColour = 1;
else:
wColour = 2
wBox.create_rectangle(0, 0, 20, 20, fill=colour.get())
wBox.create_rectangle(0, 0, 20, 20, fill=colour.get())
wBox.create_rectangle(0, 0, 20, 20, fill=colour.get())
else:
temp = colour.get()
if temp == "red":
tColour = 0
elif temp == "blue":
tColour = 1;
else:
tColour = 2
tBox.create_rectangle(0, 0, 20, 20, fill=colour.get())
tBox.create_rectangle(0, 0, 20, 20, fill=colour.get())
tBox.create_rectangle(0, 0, 20, 20, fill=colour.get())
Label(msg, text="Red").grid(row=0, column=0, padx=10, pady=5)
Radiobutton(msg, variable=colour, value="red").grid(row=0, column=1)
Label(msg, text="Green").grid(row=1, column=0, padx=10, pady=5)
Radiobutton(msg, variable=colour, value="green").grid(row=1, column=1)
Label(msg, text="Blue").grid(row=2, column=0, padx=10, pady=5)
Radiobutton(msg, variable=colour, value="blue").grid(row=2, column=1)
Button(msg, text="Cancel", command=msg.destroy).grid(row=3, column=0, padx=5)
Button(msg, text="OK", command=ok).grid(row=3, column=1)
# This function allows the user to store or omit specific
# routes as hikes in an sql database
def store():
global db, cursor, routes, waypts
# start the window with proper route info
def initialise():
global rIndex
cursor.execute("START TRANSACTION")
name.insert(INSERT, routes[rIndex][1])
comment.set(routes[rIndex][1])
rIndex = rIndex + 1
# saves a route as a hike
def save():
global rIndex, fileno, hikeno, ptno
# add the info to the database
location = countries.get(ACTIVE)
if countries.select_includes(39) != 0:
temp = regions.curselection()
if len(temp) > 0:
location = location + ", " + regions.get(ACTIVE)
elif countries.select_includes(236) != 0:
temp = regions.curselection()
if len(temp) > 0:
location = location + ", " + regions.get(ACTIVE)
noteText = note.get(1.0, END)
noteText = os.linesep.join([s for s in noteText.splitlines() if s])
# the HIKE table
route = "INSERT INTO HIKE(name, location, comment, rating, note)\
VALUES('%s', '%s', '%s', '%d', '%s')" % (name.get(), location, routes[rIndex - 1][1], rating.get(), noteText)
cursor.execute(route)
hikeno = hikeno + 1
# the WAYPTS table
leg = 0
oldLat = 0
oldLon = 0
for item in routes[rIndex - 1][2]:
# insert stuff into the waypts
waypt = "INSERT INTO WAYPTS(fileno, ptno, id, comment, lat, lon)\
VALUES('%d', '%d', '%s', '%s', '%f', '%f')" % (fileno, ptno, waypts[item][2], waypts[item][3], waypts[item][0], waypts[item][1])
cursor.execute(waypt)
# calculate the distance
if oldLat == 0 and oldLon == 0:
distance = 0
else:
distance = calcDistance(oldLat, waypts[item][0], oldLon, waypts[item][1])
#insert stuff into the hikepts
hikept = "INSERT INTO HIKEPTS(hikeno, fileno, ptno, leg, distance)\
VALUES('%d', '%d', '%d', '%d', '%f')" % (hikeno, fileno, ptno, leg, distance)
cursor.execute(hikept)
# update stuff
oldLat = waypts[item][0]
oldLon = waypts[item][1]
leg = leg + 1
ptno = ptno + 1
# if this is the last route
if rIndex == len(routes):
cursor.execute("COMMIT")
rIndex = 0
store.destroy()
else:
name.delete(0, END)
name.insert(INSERT, routes[rIndex][1])
comment.set(routes[rIndex][1])
rating.set(0)
note.delete(1.0, END)
rIndex = rIndex + 1
# moves on to the hike, does not store the current one
def omit():
global rIndex
# if this is the last route
if rIndex == len(routes):
cursor.execute("COMMIT")
rIndex = 0
store.destroy()
else:
name.delete(0, END)
name.insert(INSERT, routes[rIndex][1])
comment.set(routes[rIndex][1])
rating.set(0)
note.delete(1.0, END)
rIndex = rIndex + 1
# exits this window and makes sure nothing was put up to the server
def cancel():
global rIndex
cursor.execute("ROLLBACK")
getHikeno = "SELECT MAX(hikeno) FROM HIKE"
cursor.execute(getHikeno)
temp = cursor.fetchone()
if temp[0] == None:
hikeno = 1
else:
hikeno = temp[0]
rIndex = 0
store.destroy()
# if Canada or US is selected this fills the provinces/states
def fillRegion(event):
regions.delete(0, END)
if countries.select_includes(39) != 0:
pList = open("provinces.txt", "r")
for item in pList.readlines():
regions.insert(END, item.strip())
pList.close()
elif countries.select_includes(236) != 0:
pList = open("states.txt", "r")
for item in pList.readlines():
regions.insert(END, item.strip())
pList.close()
# calculates the distance between two coordinates
def calcDistance(lat1, lat2, lon1, lon2):
# calculate the delta
lat = lat2 - lat1
lon = lon2 - lon1
a = (sin(radians(lat/2.0)) ** 2.0) + cos(radians(lat1)) * cos(radians(lat2)) * (sin(radians(lon/2.0)) ** 2.0)
c = 2.0 * atan2(radians(sqrt(a)), radians(sqrt(1.0 - a)))
distance = 6378.1 * c
return distance
# the store GUI
store = Toplevel(padx=10, pady=10)
store.title("Hike Information")
store.protocol("WM_DELETE_WINDOW", cancel)
infoFrame = Frame(store, pady=5)
infoFrame.grid(row=0, column=0)
listFrame = Frame(store, pady=5)
listFrame.grid(row=1, column=0)
ratingFrame = Frame(store, pady=5)
ratingFrame.grid(row=2, column=0)
noteFrame = Frame(store, pady=5)
noteFrame.grid(row=3, column=0)
buttonFrame = Frame(store, pady=5)
buttonFrame.grid(row=4, column=0)
# the info frame
Label(infoFrame, text="Name:", padx=10, pady=5).grid(row=0, column=0)
name = Entry(infoFrame, width=35)
name.grid(row=0, column=1)
comment = StringVar()
Label(infoFrame, text="Comment:", padx=10).grid(row=1, column=0)
Label(infoFrame, textvariable=comment, width=35).grid(row=1, column=1)
# the list frame
countryFrame = Frame(listFrame)
countryFrame.grid(row=0, column=0)
regionFrame = Frame(listFrame)
regionFrame.grid(row=0, column=1)
Label(countryFrame, text="Country:", width=30, anchor=W, justify=LEFT).pack()
scroll1 = Scrollbar(countryFrame, orient=VERTICAL)
countries = Listbox(countryFrame, exportselection=0, yscrollcommand=scroll1.set, font=("Helvetica", 10), width=30, height=10)
scroll1.config(command=countries.yview)
scroll1.pack(side=RIGHT, fill=Y)
countries.bind("<ButtonRelease-1>", fillRegion)
countries.pack(side=LEFT, fill=BOTH, expand=1)
Label(regionFrame, text="Province/State:", width=30, anchor=W, justify=LEFT).pack()
scroll2 = Scrollbar(regionFrame, orient=VERTICAL)
regions = Listbox(regionFrame, exportselection=0, yscrollcommand=scroll2.set, font=("Helvetica", 10), width=30, height=10)
scroll2.config(command=regions.yview)
scroll2.pack(side=RIGHT, fill=Y)
regions.pack(side=LEFT, fill=BOTH, expand=1)
# the rating frame
Label(ratingFrame, text="Rating:", padx=10).grid(row=0, column=0)
rating = IntVar()
r0 = Radiobutton(ratingFrame, text="0", variable=rating, value=0, padx=5)
r1 = Radiobutton(ratingFrame, text="1", variable=rating, value=1, padx=5)
r2 = Radiobutton(ratingFrame, text="2", variable=rating, value=2, padx=5)
r3 = Radiobutton(ratingFrame, text="3", variable=rating, value=3, padx=5)
r4 = Radiobutton(ratingFrame, text="4", variable=rating, value=4, padx=5)
r5 = Radiobutton(ratingFrame, text="5", variable=rating, value=5, padx=5)
r0.grid(row=0, column=1)
r1.grid(row=0, column=2)
r2.grid(row=0, column=3)
r3.grid(row=0, column=4)
r4.grid(row=0, column=5)
r5.grid(row=0, column=6)
# the note frame
Label(noteFrame, text="Note:", width=45, anchor=W, justify=LEFT).grid(row=0, column=0)
note = Text(noteFrame, wrap=WORD, width=50, height=5)
note.grid(row=1, column=0)
# the button frame
Button(buttonFrame, text="Store Route", padx=15, command=save).grid(row=0, column=0)
Button(buttonFrame, text="Omit Route", padx=15, command=omit).grid(row=0, column=1)
Button(buttonFrame, text="Cancel", padx=15, command=cancel).grid(row=0, column=2)
# fill the countries and ititialise
cList = open("countrylist.txt", "r")
for item in cList.readlines():
countries.insert(END, item.strip())
cList.close()
initialise()
store.mainloop()
# This function allows the user to perform queries
# in an sql database as well as view hikes in google maps
def query():
# see how many hikes are in the database
cursor.execute("SELECT COUNT(*) from HIKE")
fetch = cursor.fetchone()
numHikes = fetch[0]
# don't open window if there are no hikes
if numHikes > 0:
hikeno = []
# start the window with the info in the database
def intitialise():
cursor.execute("SELECT name from HIKE ORDER BY name")
while (1):
entry = cursor.fetchone()
if entry == None:
break
hikes.insert(END, entry[0])
cursor.execute("SELECT hikeno from HIKE ORDER BY name")
while(1):
entry = cursor.fetchone()
if entry == None:
break
hikeno.append(entry[0])
# fills the info when ONE hike is selected
def fillInfo(event):
#get currently selected hike
select = hikes.curselection();
if len(select) == 1:
index = int(select[0])
getInfo = "SELECT location from HIKE WHERE hikeno = '%d'" % (hikeno[index])
cursor.execute(getInfo)
fetch = cursor.fetchone()
location.set(fetch[0])
getInfo = "SELECT comment from HIKE WHERE hikeno = '%d'" % (hikeno[index])
cursor.execute(getInfo)
fetch = cursor.fetchone()
comment.set(fetch[0])
getInfo = "SELECT rating from HIKE WHERE hikeno = '%d'" % (hikeno[index])
cursor.execute(getInfo)
fetch = cursor.fetchone()
rating.set(fetch[0])
getInfo = "SELECT COUNT(hikeno) from HIKEPTS WHERE hikeno = '%d'" % (hikeno[index])
cursor.execute(getInfo)
fetch = cursor.fetchone()
legs.set(fetch[0])
getInfo = "SELECT note from HIKE WHERE hikeno = '%d'" % (hikeno[index])
cursor.execute(getInfo)
fetch = cursor.fetchone()
noteText.config(state=NORMAL)
noteText.delete(1.0, END)
noteText.insert(INSERT, fetch[0])
noteText.config(state=DISABLED)
# clear everything if multiple selected
else:
location.set("")
comment.set("")
rating.set("")
legs.set("")
noteText.config(state=NORMAL)
noteText.delete(1.0, END)
noteText.config(state=DISABLED)
# displays the hike in google maps
def mapIt():
select = hikes.curselection();
allHikes = []
for item in select:
# get the ones selected in the list
index = int(item[0])
# get the fileno and ptnos to reference the WAYPTS table
getInfo = "SELECT DISTINCT fileno from HIKEPTS WHERE hikeno = '%d'" % (hikeno[index])
cursor.execute(getInfo)
fetch = cursor.fetchone()
tempFileno = fetch[0]
getInfo = "SELECT ptno from HIKEPTS WHERE hikeno = '%d' AND fileno = '%d'" % (hikeno[index], tempFileno)
cursor.execute(getInfo)
fetch = cursor.fetchall()
# get the lat/lon with information from the WAYPTS table
mapData = []
for item in fetch:
tempPtno = int(item[0])
coordinate = []
# get the latitude
getLat = "SELECT lat from WAYPTS where fileno = '%d' AND ptno = '%d'" % (tempFileno, tempPtno)
cursor.execute(getLat)
temp = cursor.fetchone()
coordinate.append(temp[0])
# get the longitude
getLon = "SELECT lon from WAYPTS where fileno = '%d' AND ptno = '%d'" % (tempFileno, tempPtno)
cursor.execute(getLon)
temp = cursor.fetchone()
coordinate.append(temp[0])
mapData.append(coordinate)
# add the hike to the list
allHikes.append(mapData)
# generate the map
if len(select) > 0:
# calculate average lat/lon
lat = 0
lon = 0
noCoords = 0
for thing in allHikes:
for item in thing:
lat = lat + item[0]
lon = lon + item[1]
noCoords = noCoords + 1
avgLat = lat / noCoords
avgLon = lon / noCoords
# make the map, centre it at the average lat/lon
gMap = GMapData("hello world", [avgLat, avgLon], 10)
count = 0
for thing in allHikes:
start = count
points = 0
for item in thing:
gMap.addPoint(item)
gMap.addOverlay(count, 1, 0)
count = count + 1
points = points + 1
gMap.addOverlay(start, points, 1)
gMap.serve("public_html/index.html")
launchBrowser("http://localhost:49099/")
# determines the shortest hike in a specific location
def handleQ1():