forked from QCaudron/Twitter-GoogleMaps
-
Notifications
You must be signed in to change notification settings - Fork 2
/
pygmaps.py
391 lines (349 loc) · 17.1 KB
/
pygmaps.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
import math
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
#This is a modified pygmaps.py version, authored by
# Radhika Saksena (radhikasaksena@gmail.com) based on
# the original Pygmaps-0.1.1, authored by Yifei Jiang
#(jiangyifei@gmail.com). The code has been modified
#to draw filled radpoints, polylines with arrows, etc.
#
###########################################################
## Google map python wrapper V0.1
##
############################################################
class maps:
def __init__(self, centerLat, centerLng, zoom ):
self.center = (float(centerLat),float(centerLng))
self.zoom = int(zoom)
self.grids = None
self.paths = []
self.points = []
self.radpoints = []
self.gridsetting = None
self.coloricon = 'http://chart.apis.google.com/chart?cht=mm&chs=12x16&chco=FFFFFF,XXXXXX,000000&ext=.png'
def setgrids(self,slat,elat,latin,slng,elng,lngin):
self.gridsetting = [slat,elat,latin,slng,elng,lngin]
def addpoint(self, lat, lng, color = '#FF0000', title = None):
self.points.append((lat,lng,color[1:],title))
#def addpointcoord(self, coord):
# self.points.append((coord[0],coord[1]))
def addradpoint(self, lat,lng,rad,color = '#0000FF'):
radpoint = {'pt':(lat,lng), 'rad':rad, 'color':color}
self.radpoints.append(radpoint)
def addpath(self,path, color = '#FF0000', fillcolor='#FF0000', opacity=False):
path = {'path':path, 'strokeColor':color, 'fillColor':fillcolor, 'opacity':opacity,
'arrows':False}
self.paths.append(path)
def addpatharrows(self,path, color = '#FF0000', fillcolor='#FF0000', opacity=False):
path = {'path':path, 'strokeColor':color, 'fillColor':fillcolor, 'opacity':opacity,
'arrows':True}
self.paths.append(path)
#create the html file which inlcude one google map and all points and paths
def draw(self, htmlfile):
f = open(htmlfile,'w')
f.write('<html>\n')
f.write('<head>\n')
f.write('<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />\n')
f.write('<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>\n')
f.write('<title>Google Maps - pygmaps </title>\n')
f.write('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>\n')
f.write('<script type="text/javascript">\n')
f.write('\tfunction initialize() {\n')
self.drawmap(f)
self.drawgrids(f)
self.drawpoints(f)
self.drawradpoints(f)
self.drawpaths(f,self.paths)
f.write('\t}\n')
f.write('</script>\n')
f.write('</head>\n')
f.write('<body style="margin:0px; padding:0px;" onload="initialize()">\n')
f.write('\t<div id="map_canvas" style="width: 100%; height: 100%;"></div>\n')
f.write('</body>\n')
f.write('</html>\n')
f.close()
#create the html file which inlcude one google map and all points and paths
#use satellite map as background.
def drawsat(self, htmlfile):
f = open(htmlfile,'w')
f.write('<html>\n')
f.write('<head>\n')
f.write('<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />\n')
f.write('<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>\n')
f.write('<title>Google Maps - pygmaps </title>\n')
f.write('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>\n')
f.write('<script type="text/javascript">\n')
f.write('\tfunction initialize() {\n')
self.drawmapsat(f)
self.drawgrids(f)
self.drawpoints(f)
self.drawradpoints(f)
self.drawpaths(f,self.paths)
f.write('\t}\n')
f.write('</script>\n')
f.write('</head>\n')
f.write('<body style="margin:0px; padding:0px;" onload="initialize()">\n')
f.write('\t<div id="map_canvas" style="width: 100%; height: 100%;"></div>\n')
f.write('</body>\n')
f.write('</html>\n')
f.close()
#create the html file which inlcude one google map and all points and paths
#use satellite map as background.
def drawterr(self, htmlfile):
f = open(htmlfile,'w')
f.write('<html>\n')
f.write('<head>\n')
f.write('<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />\n')
f.write('<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>\n')
f.write('<title>Google Maps - pygmaps </title>\n')
f.write('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>\n')
f.write('<script type="text/javascript">\n')
f.write('\tfunction initialize() {\n')
self.drawmapterr(f)
self.drawgrids(f)
self.drawpoints(f)
self.drawradpoints(f)
self.drawpaths(f,self.paths)
f.write('\t}\n')
f.write('</script>\n')
f.write('</head>\n')
f.write('<body style="margin:0px; padding:0px;" onload="initialize()">\n')
f.write('\t<div id="map_canvas" style="width: 100%; height: 100%;"></div>\n')
f.write('</body>\n')
f.write('</html>\n')
f.close()
def drawgrids(self, f):
if self.gridsetting == None:
return
slat = self.gridsetting[0]
elat = self.gridsetting[1]
latin = self.gridsetting[2]
slng = self.gridsetting[3]
elng = self.gridsetting[4]
lngin = self.gridsetting[5]
self.grids = []
r = [slat+float(x)*latin for x in range(0, int((elat-slat)/latin))]
for lat in r:
self.grids.append([(lat+latin/2.0,slng+lngin/2.0),(lat+latin/2.0,elng+lngin/2.0)])
r = [slng+float(x)*lngin for x in range(0, int((elng-slng)/lngin))]
for lng in r:
self.grids.append([(slat+latin/2.0,lng+lngin/2.0),(elat+latin/2.0,lng+lngin/2.0)])
for line in self.grids:
self.drawPolyline(f,line,strokeColor = "#000000")
def drawpoints(self,f):
for point in self.points:
self.drawpoint(f,point[0],point[1],point[2],point[3])
def drawradpoints(self, f):
for rpoint in self.radpoints:
path = self.getcycle(rpoint['pt'],rpoint['rad'])
#self.drawPolygon(f,path,strokeColor = rpoint['color'])
self.drawPolygon(f,path,strokeColor=rpoint['color'], fillColor=rpoint['color'], fillOpacity=0.8)
def getcycle(self,center,radius):
cycle = []
lat, lng = center
rad = radius #unit: meter
d = (rad/1000.0)/6378.8;
lat1 = (math.pi/180.0)* lat
lng1 = (math.pi/180.0)* lng
r = [x*30 for x in range(12)]
for a in r:
tc = (math.pi/180.0)*a;
y = math.asin(math.sin(lat1)*math.cos(d)+math.cos(lat1)*math.sin(d)*math.cos(tc))
dlng = math.atan2(math.sin(tc)*math.sin(d)*math.cos(lat1),math.cos(d)-math.sin(lat1)*math.sin(y))
x = ((lng1-dlng+math.pi) % (2.0*math.pi)) - math.pi
cycle.append( ( float(y*(180.0/math.pi)),float(x*(180.0/math.pi)) ) )
return cycle
def drawpaths(self, f, paths):
for path in paths:
if not path['opacity']:
#fill is false
if(path['arrows']):
self.drawPolylineArrows(f,path['path'], strokeColor = path['strokeColor'])
else:
#self.drawPolyline(f,path['path'], strokeColor = path['strokeColor'])
self.drawPolyline(f,path['path'], strokeColor = path['strokeColor'])
else:
self.drawPolygon(f,path['path'],strokeColor=path['strokeColor'], fillColor=path['fillColor'], fillOpacity=path['opacity'])
#############################################
# # # # # # Low level Map Drawing # # # # # #
#############################################
def drawmap(self, f):
f.write('\t\tvar centerlatlng = new google.maps.LatLng(%f, %f);\n' % (self.center[0],self.center[1]))
f.write('\t\tvar myOptions = {\n')
f.write('\t\t\tzoom: %d,\n' % (self.zoom))
f.write('\t\t\tcenter: centerlatlng,\n')
#use satellite map as background.
f.write('\t\t\tmapTypeId: google.maps.MapTypeId.ROADMAP\n')
f.write('\t\t};\n')
f.write('\t\tvar map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);\n')
f.write('\n')
def drawmapsat(self, f):
f.write('\t\tvar centerlatlng = new google.maps.LatLng(%f, %f);\n' % (self.center[0],self.center[1]))
f.write('\t\tvar myOptions = {\n')
f.write('\t\t\tzoom: %d,\n' % (self.zoom))
f.write('\t\t\tcenter: centerlatlng,\n')
f.write('\t\t\tmapTypeId: google.maps.MapTypeId.SATELLITE\n')
f.write('\t\t};\n')
f.write('\t\tvar map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);\n')
f.write('\n')
def drawmapterr(self, f):
f.write('\t\tvar centerlatlng = new google.maps.LatLng(%f, %f);\n' % (self.center[0],self.center[1]))
f.write('\t\tvar myOptions = {\n')
f.write('\t\t\tzoom: %d,\n' % (self.zoom))
f.write('\t\t\tcenter: centerlatlng,\n')
f.write('\t\t\tmapTypeId: google.maps.MapTypeId.TERRAIN\n')
f.write('\t\t};\n')
f.write('\t\tvar map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);\n')
f.write('\n')
def drawpoint(self,f,lat,lon,color,title):
f.write('\t\tvar latlng = new google.maps.LatLng(%f, %f);\n'%(lat,lon))
f.write('\t\tvar img = new google.maps.MarkerImage(\'%s\');\n' % (self.coloricon.replace('XXXXXX',color)))
f.write('\t\tvar marker = new google.maps.Marker({\n')
if title !=None:
f.write('\t\ttitle: "'+str(title)+'",\n')
f.write('\t\ticon: img,\n')
f.write('\t\tposition: latlng\n')
f.write('\t\t});\n')
f.write('\t\tmarker.setMap(map);\n')
f.write('\n')
def drawPolyline(self,f,path,\
clickable = False, \
geodesic = True,\
strokeColor = "#FF0000",\
strokeOpacity = 1.0,\
strokeWeight = 2
):
f.write('var PolylineCoordinates = [\n')
for coordinate in path:
f.write('new google.maps.LatLng(%f, %f),\n' % (coordinate[0],coordinate[1]))
f.write('];\n')
f.write('\n')
f.write('var Path = new google.maps.Polyline({\n')
f.write('clickable: %s,\n' % (str(clickable).lower()))
f.write('geodesic: %s,\n' % (str(geodesic).lower()))
f.write('path: PolylineCoordinates,\n')
f.write('strokeColor: "%s",\n' %(strokeColor))
f.write('strokeOpacity: %f,\n' % (strokeOpacity))
f.write('strokeWeight: %d\n' % (strokeWeight))
f.write('});\n')
f.write('\n')
f.write('Path.setMap(map);\n')
f.write('\n\n')
def drawPolylineArrows(self,f,path,\
clickable = False, \
geodesic = True,\
strokeColor = "#FF0000",\
strokeOpacity = 1.0,\
strokeWeight = 2
):
f.write('var PolylineCoordinates = [\n')
for coordinate in path:
f.write('new google.maps.LatLng(%f, %f),\n' % (coordinate[0],coordinate[1]))
f.write('];\n')
f.write('\n')
f.write('var lineSymbol = {\n')
f.write('path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,\n')
f.write('scale: 3,\n')
f.write('};\n')
f.write('\n')
f.write('var Path = new google.maps.Polyline({\n')
f.write('clickable: %s,\n' % (str(clickable).lower()))
f.write('geodesic: %s,\n' % (str(geodesic).lower()))
f.write('path: PolylineCoordinates,\n')
f.write('strokeColor: "%s",\n' %(strokeColor))
f.write('strokeOpacity: %f,\n' % (strokeOpacity))
f.write('strokeWeight: %d,\n' % (strokeWeight))
f.write('icons: [{\n')
f.write('icon: lineSymbol,\n')
f.write("offset: '100%' \n")
f.write('}],\n')
f.write('});\n')
f.write('\n')
f.write('Path.setMap(map);\n')
f.write('\n\n')
def drawPolygon(self,f,path,\
clickable = False, \
geodesic = True,\
fillColor = "#000000",\
fillOpacity = 0.0,\
strokeColor = "#FF0000",\
strokeOpacity = 1.0,\
strokeWeight = 1
):
f.write('var coords = [\n')
for coordinate in path:
f.write('new google.maps.LatLng(%f, %f),\n' % (coordinate[0],coordinate[1]))
f.write('];\n')
f.write('\n')
f.write('var polygon = new google.maps.Polygon({\n')
f.write('clickable: %s,\n' % (str(clickable).lower()))
f.write('geodesic: %s,\n' % (str(geodesic).lower()))
f.write('fillColor: "%s",\n' %(fillColor))
f.write('fillOpacity: %f,\n' % (fillOpacity))
f.write('paths: coords,\n')
f.write('strokeColor: "%s",\n' %(strokeColor))
f.write('strokeOpacity: %f,\n' % (strokeOpacity))
f.write('strokeWeight: %d\n' % (strokeWeight))
f.write('});\n')
f.write('\n')
f.write('polygon.setMap(map);\n')
f.write('\n\n')
if __name__ == "__main__":
########## CONSTRUCTOR: pygmaps(latitude, longitude, zoom) ##############################
# DESC: initialize a map with latitude and longitude of center point
# and map zoom level "15"
# PARAMETER1: latitude (float) latittude of map center point
# PARAMETER2: longitude (float) latittude of map center point
# PARAMETER3: zoom (int) map zoom level 0~20
# RETURN: the instant of pygmaps
#========================================================================================
mymap = pygmaps(37.428, -122.145, 16)
########## FUNCTION: setgrids(start-Lat, end-Lat, Lat-interval, start-Lng, end-Lng, Lng-interval) ######
# DESC: set grids on map
# PARAMETER1: start-Lat (float), start (minimum) latittude of the grids
# PARAMETER2: end-Lat (float), end (maximum) latittude of the grids
# PARAMETER3: Lat-interval (float) grid size in latitude
# PARAMETER4: start-Lng (float), start (minimum) longitude of the grids
# PARAMETER5: end-Lng (float), end (maximum) longitude of the grids
# PARAMETER6: Lng-interval (float) grid size in longitude
# RETURN: no returns
#========================================================================================
mymap.setgrids(37.42, 37.43, 0.001, -122.15, -122.14, 0.001)
########## FUNCTION: addpoint(latitude, longitude, [color])#############################
# DESC: add a point into a map and dispaly it, color is optional default is red
# PARAMETER1: latitude (float) latitude of the point
# PARAMETER2: longitude (float) longitude of the point
# PARAMETER3: color (string) color of the point showed in map, using HTML color code
# HTML COLOR CODE: http://www.computerhope.com/htmcolor.htm
# e.g. red "#FF0000", Blue "#0000FF", Green "#00FF00"
# RETURN: no return
#========================================================================================
mymap.addpoint(37.427, -122.145, "#0000FF")
########## FUNCTION: addradpoint(latitude, longitude, radius, [color])##################
# DESC: add a point with a radius (Meter) - Draw cycle
# PARAMETER1: latitude (float) latitude of the point
# PARAMETER2: longitude (float) longitude of the point
# PARAMETER3: radius (float), radius in meter
# PARAMETER4: color (string) color of the point showed in map, using HTML color code
# HTML COLOR CODE: http://www.computerhope.com/htmcolor.htm
# e.g. red "#FF0000", Blue "#0000FF", Green "#00FF00"
# RETURN: no return
#========================================================================================
mymap.addradpoint(37.429, -122.145, 95, "#FF0000","hello")
########## FUNCTION: addpath(path,[color])##############################################
# DESC: add a path into map, the data struceture of Path is a list of points
# PARAMETER1: path (list of coordinates) e.g. [(lat1,lng1),(lat2,lng2),...]
# PARAMETER2: color (string) color of the point showed in map, using HTML color code
# HTML COLOR CODE: http://www.computerhope.com/htmcolor.htm
# e.g. red "#FF0000", Blue "#0000FF", Green "#00FF00"
# RETURN: no return
#========================================================================================
path = [(37.429, -122.145),(37.428, -122.145),(37.427, -122.145),(37.427, -122.146),(37.427, -122.146)]
mymap.addpath(path,"#00FF00")
########## FUNCTION: addpath(file)######################################################
# DESC: create the html map file (.html)
# PARAMETER1: file (string) the map path and file
# RETURN: no return, generate html file in specified directory
#========================================================================================
mymap.draw('./mymap.html')