#!/usr/bin/python ##################################### # Yes I know I program Python like C # its not an insult when I am C man. ##################################### import os import sys import glob import subprocess import re import urllib import cStringIO from PIL import Image from struct import unpack from decimal import Decimal ################################################ # Overview: # Draw a map of all places that I drank beer in! # Assumptions: # see ~Documents/Tips/iPhoto.txt for details ################################################ ### See http://hci574.blogspot.com/2010/04/using-google-maps-static-images.html def get_static_google_map(filename_wo_extension, center=None, zoom=3, imgsize="500x500", imgformat="jpeg", maptype="roadmap", markers=None ): """retrieve a map (image) from the static google maps server See: http://code.google.com/apis/maps/documentation/staticmaps/ Creates a request string with a URL like this: http://maps.google.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=14&size=512x512&maptype=roadmap &markers=color:blue|label:S|40.702147,-74.015794&sensor=false""" # assemble the URL request = "http://maps.google.com/maps/api/staticmap?" # base URL, append query params, separated by & # if center and zoom are not given, the map will show all marker locations if center != None: #request += "center=%s&" % center #request += "center=%s&" % "40.714728, -73.998672" # latitude and longitude (up to 6-digits) #request += "center=%s&" % "50011" # could also be a zipcode, request += "center=%s&" % "Munich, Germany" # or a search term if center != None: request += "zoom=%i&" % zoom # zoom 0 (all of the world scale ) to 22 (single buildings scale) request += "size=%ix%i&" % (imgsize) # tuple of ints, up to 640 by 640 request += "format=%s&" % imgformat request += "maptype=%s&" % maptype # roadmap, satellite, hybrid, terrain # add markers (location and style) if markers != None: for marker in markers: request += "%s" % marker #request += "mobile=false&" # optional: mobile=true will assume the image is shown on a small screen (mobile device) request += "sensor=false&" # must be given, deals with getting loction from mobile device print request urllib.urlretrieve(request, filename_wo_extension+"."+imgformat) # Option 1: save image directly to disk # Option 2: read into PIL web_sock = urllib.urlopen(request) imgdata = cStringIO.StringIO(web_sock.read()) # constructs a StringIO holding the image try: PIL_img = Image.open(imgdata) # if this cannot be read as image that, it's probably an error from the server, except IOError: print "IOError:", imgdata.read() # print error (or it may return a image showing the error" # show image else: PIL_img.show() #PIL_img.save(filename_wo_extension+".jpg", "JPEG") # save as jpeg ################################# # Function: find_program ################################# def find_program(prog_filename, error_on_missing=False): bdirs = ['$HOME/Environment/local/bin/', '$HOME/bin/', '/share/apps/bin/', '/usr/local/bin/', '/usr/bin/'] paths_tried = [] for d in bdirs: p = os.path.expandvars(os.path.join(d, prog_filename)) paths_tried.append(p) if os.path.exists(p): return p if error_on_missing: raise Exception("*** ERROR: '%s' not found on:\n %s\n" % (prog_filename, "\n ".join(paths_tried))) else: return None ################################# # Misc functions ################################# def toBytes(value): return unpack('%sB' % len(value), value) def is_ascii(s): return all(ord(c) < 128 for c in s) ################################# ## Function: get_coordinates ## param: file_name ## ## Get coordinates long,lat from the file ################################# def get_coordinates(file_name): # global mdls_path global marker_list #print "MDLS path %s " % (mdls_path) lat_res = None long_res = None try: p = subprocess.Popen("'%s' -raw -name kMDItemLatitude '%s'" % (mdls_path, file_name), stdout=subprocess.PIPE, shell=True) except OSError, e: if e.errno == 2: ##No such file or directory print "Error running mdls command \n" return; else: #reraise the exception raise lat_res = '' (lat_res, err) = p.communicate() p_status = p.wait() if p_status != 0: print "Error running latitude with error %s " % (err) return; p = subprocess.Popen("'%s' -raw -name kMDItemLongitude '%s'" % (mdls_path, file_name), stdout=subprocess.PIPE, shell=True) long_res = '' (long_res, err) = p.communicate() p_status = p.wait() if p_status != 0: print "Error running longitude with error %s " % (err) return; #print "latitude len is: ", len(lat_res) #print "Error : ", err #print toBytes(lat_res) if re.search('null', lat_res): print "FOUND NULL!\n" else: #all these strings have "&number" Remove the first character #only 6 digits after decimal are allowed dec_lat_res = Decimal(lat_res.lstrip('&')) temp_lat_res = Decimal(float(dec_lat_res)).quantize(Decimal('0e-6')) print " 6 decimal places: %f \n" % temp_lat_res print format(temp_lat_res, '.6f') marker_list.append("%s," % (temp_lat_res)) dec_long_res = Decimal(long_res.lstrip('&')) temp_long_res = Decimal(float(dec_long_res)).quantize(Decimal('0e-6')) print " 6 decimal places: %f \n" % temp_long_res print format(temp_long_res, '.6f') marker_list.append("%s|" % (temp_long_res)) print "[ %s ] Lat: %s Long: %s" % (file_name, temp_lat_res, temp_long_res) return; ################################# # Main function ################################# marker_list = [] mdls_path = find_program('mdls', False) if mdls_path is None: print "Error finding mdls, is it installed? " os.Exit else: print "Found MDLS and its available in %s " % (mdls_path) marker_list.append("zoom=3&markers=size:mid|label:B|color:0xFFFF00|") files = [f for f in os.listdir('.') if os.path.isfile(f)] number_processed = 1 for f in files: if f.endswith(".jpg"): number_processed += 1 get_coordinates(f); if f.endswith(".jpeg"): number_processed += 1 get_coordinates(f); if f.endswith(".JPG"): number_processed += 1 get_coordinates(f); if f.endswith(".JPEG"): number_processed += 1 get_coordinates(f); #endfor print "Number of files processed:", number_processed print(" All done!") # define a series of location markers and their styles # syntax: markers=markerStyles|markerLocation1|markerLocation2|... etc. ##Manually generate image.. #marker_list.append("markers=color:blue|label:S|11211|11206|11222") # blue S at several zip code's centers #marker_list.append("markers=size:mid|color:red|label:6|Brooklyn+Bridge,New+York,NY") # mid-sized red 6 at search location # see http://code.google.com/apis/maps/documentation/staticmaps/#Markers #one last & to separate the fields marker_list.append('&') # make map that shows all the markers get_static_google_map("Europe_beer_2015", imgsize=(640,640), center="Munich, Germany", zoom=5, imgformat="png", markers=marker_list ) ### This URL works # http://maps.google.com/maps/api/staticmap?size=640x640&format=png&maptype=roadmap&zoom=5&markers=size:mid|label:B|color:0xFFFF00|41.903786666,12.4610916666666|50.0852555,14.432505|&sensor=false&