示例#1
0
    def find_destination(self, x1, y1, x2, y2):

        gmaps = GoogleMaps("AIzaSyAChNKxjgh7MmGPQ6CJOGa_-tjM8giIZe4")
        destination = gmaps.latlng_to_address(x2, y2)
        adress = gmaps.latlng_to_address(x1, y1)
        directions = gmaps.directions(address, destination)
        print(directions['Directions']['Distance']['meters'])
示例#2
0
    def main(argv):
        """
        Geocodes a location given on the command line.
        
        Usage:
            googlemaps.py "1600 amphitheatre mountain view ca" [YOUR_API_KEY]
            googlemaps.py 37.4219720,-122.0841430 [YOUR_API_KEY]
            
        When providing a latitude and longitude on the command line, ensure
        they are separated by a comma and no space.
        
        """

        if len(argv) < 2 or len(argv) > 4:
            print main.__doc__
            sys.exit(1)

        query = argv[1]
        if len(argv) == 3:
            api_key = argv[2]
        else:
            api_key = raw_input("Google Maps API key: ")

        gmap = GoogleMaps(api_key)
        try:
            result = gmap.geocode(query)
        except GoogleMapsError, err:
            sys.stderr.write('%s\n%s\nResponse:\n' % (err.url, err))
            json.dump(err.response, sys.stderr, indent=4)
            sys.exit(1)
示例#3
0
def main():
    keyfile = "MAP_KEY"
    MAP_KEY = ''

    # Get API key from a file
    try:
        with open(keyfile, 'r+') as fh:
            MAP_KEY = fh.readline()
    except FileNotFoundError:
        print('API key file does not exist. Exit the program.')
        exit()

    # Create gmaps
    try:
        gmaps = GoogleMaps(MAP_KEY)
    except ValueError:
        print('Invalid API key provided. Exit the program.')
        exit()

    # Get src_addr and dst_addr. Currently hardcoded. Need to be changed.
    src_addr = 'temple university'
    dst_addr = 'temple university ambler campus Learning Center Parking Lot'

    # Get distance and duration of src_addr and dst_addr
    # return format examples: {'text': '25.3 km', 'value': 25318}, {'text': '25.3 km', 'value': 25318}
    distance, duration = getLatLng(src_addr, dst_addr, gmaps)
    print(distance)
    print(duration)
    """
示例#4
0
    def getCoord(address):

        """ Get coordinates for location using Google Maps Geolocation API.

        Raises:
            serializers.ValidationError: Google Maps API could not find pair of
            coordinates suitable for address passed as input.

        Returns:
            dictionary: Geocoding information.
        """

        start_time = time.time()
        gmaps = GoogleMaps(os.getenv("GOOGLE_KEY"))
        geocode_result = gmaps.geocode(address)

        data = {'long': {}, 'short': {}, 'location': {}}

        if geocode_result:
            for geolist in geocode_result:
                for item in geolist['address_components']:
                    for category in item['types']:
                        data['long'].update([(category, item['long_name'])])
                        data['short'].update([(category, item['short_name'])])
                data['location'] = geolist['geometry']['location']
        else:
            e = serializers.ValidationError('GeoCoding Error: Could not parse coordinates')
            capture_message(e)
            raise e

        print('--- Tiempo de ejecucion getCoord: {} segundos ---'.format((time.time() - start_time)))

        return data
示例#5
0
    def create(self, request):
        """Add a new device location."""
        attrs = self.flatten_dict(request.POST)

        try:
            device = Device.objects.get(user=request.user,
                                        name=attrs['device_name'],
                                        mobile_id=attrs['device_id'])
        except Device.DoesNotExist:
            return rc.NOT_FOUND

        gmaps = GoogleMaps()
        try:
            address = gmaps.latlng_to_address(float(attrs['lat']),
                                              float(attrs['lon']))
        except GoogleMapsError:
            address = None

        device_location = DeviceLocation(device=device,
                                         address=address,
                                         lat=float(attrs['lat']),
                                         lon=float(attrs['lon']),
                                         created=datetime.datetime.now())
        device_location.save()

        return rc.CREATED
示例#6
0
def return_result(qid, q_type):
	global pending_photo, pending_task, active_queries
	
	temp_pending_photo = copy.deepcopy(pending_photo)
	for k,v in pending_photo[qid].iteritems():
        	if (os.path.exists('query/' + k)):
                        names = k.split('=')
                        pending_task[qid][names[0]].remove(names[1])
                        if (len(pending_task[qid][names[0]]) == 1):
                        	del pending_task[qid][names[0]]
	#if len(pending_task[qid]) > 0:
		#kill_users(pending_task[qid])
	
	ret_val = ''
	if (len(pending_photo[qid]) == 0):
        	ret_val += "<h2>No relevent results.</h2>"
 	        del pending_photo[qid]
		del pending_task[qid]
		del active_queries[qid]
		return ret_val
	#print "q_type = " + str(q_type) # q_type = 0U
	if (q_type[0] == '0'):
		ret_val += "Query Object: <br> </br><img src=\"data:image/jpg;base64,{0}\" width=205><br> </br>".format(open('QUERY_IMAGE/' + q_type[1:]).read().encode('base64').replace('\n', ''))

        ret_val += 'Result Objects: <br> </br> <table border=1 bordercolor=#999999 width=600><tr>'

        gmaps = GoogleMaps()
	while (len(pending_photo[qid]) > 0):
		(k, v) = max(pending_photo[qid].iteritems(), key=operator.itemgetter(1))
        	temp = k.split('=')
                ret_val += "<td width=205>"
                if (os.path.exists('query/' + k)):
                	ret_val += "<img src=\"data:image/jpg;base64,{0}\" width=205>".format(open('query/' + k).read().encode('base64').replace('\n', ''))
                else:
                	ret_val += "<b>Warning:</b> Photo failed to be uploaded on time."
                #temp = v.split(',')
                #dd = datetime.datetime.fromtimestamp(long(temp[len(temp) - 2])/1000)
                #tt = dd.isoformat(' ')
                #destination = "a, b, c, d, e, f, g"
                #destination = gmaps.latlng_to_address(float(temp[3]), float(temp[2]))
                #dest = destination.split(', ')
                #ret_val += "<p><b><pre>Location: </b>{0}</pre></p>".format(dest[0])
		ret_val += "<p><b><pre>Credit: </b>{0}</pre></p>".format(str(pending_photo[qid][k]))
                #del dest[0]
                #dest[-2] += ', ' + dest[-1]
                #del dest[-1]
   		#for dests in dest:
                #	ret_val += "<p><pre>            {0}</pre></p>".format(dests)
		ret_val += "<p><b><pre>Name: </b>{0}</pre></p>".format(k)
		del pending_photo[qid][k]
	ret_val += "</td>"
        del pending_photo[qid]
	del pending_task[qid]
	del active_queries[qid]
        print 'Finish response to ('+str(qid)+'). '
	print '    Now query set (' + str(active_queries)+')'
	print '    Pending photo ('+str(pending_photo)+')'
	print '    Pending task ('+str(pending_task)+')'
	return ret_val
示例#7
0
 def get_lat_long(self):
     from googlemaps import GoogleMaps
     gmaps = GoogleMaps(italian - 1489414695369)
     Address = self.address
     lat, lng = gmaps.address_to_latlng(address)
     self.latitude = lat
     self.longitude = lng
     save()
def main():
    gmaps = GoogleMaps()
    cr = csv.reader(open("mark.csv", "rb"))
    dic = dict()
    i = 0
    for row in cr:
        if not row[0]:
            break
        if i == 0:
            i += 1
            continue
        print row[2]
        #address=row[2]
        state = lookup(row[2])
        text = row[14]
        a = text.split('/')
        if int(a[0]) > 6:
            date = 'winter'
        else:
            date = 'summer'
        if state not in dic:
            dic[state] = dict()
        if date not in dic[state]:
            dic[state][date] = dict()
        if row[5] not in dic[state][date]:
            dic[state][date][row[5]] = list()
        if row[6] not in dic[state][date][row[5]]:
            dic[state][date][row[5]].append(row[6])

    for state in dic:
        print state,
        for date in dic[state]:
            print date
            for order in dic[state][date]:
                print dic[state][date][order]

    for state in dic:
        for date in dic[state]:
            if not state:
                state1 = 'statenotfoun'
            else:
                state1 = state
            if not date:
                date1 = 'datenotfound'
            else:
                date1 = date
            if not os.path.exists('./ir'):
                os.makedirs('./ir')
            f = open('./ir/' + state1 + date1 + '.txt', 'a')
            for order in dic[state][date]:
                i = 0
                while i < len(dic[state][date][order]):
                    f.write(dic[state][date][order][i])
                    f.write(' ')
                    i += 1
                f.write('\n')
示例#9
0
    def test_point_from_latlng(self):
        gmaps = GoogleMaps(settings.GOOGLEMAPS_API_KEY)
        latlng = gmaps.address_to_latlng(u'Jose javier Diaz 440, cordoba, argentina', )
        point=None
        try:
            point =  MaapPoint(geom=Point(latlng).wkt)
            point.save()            
        except Exception, e:

            self.assertIsNotNone(point, msg=e)
示例#10
0
 def getPlaceID(self, address_line1, address_line2, area, city, state,
                country, pincode):
     gmaps = GoogleMaps('AIzaSyBoy1plslvW_UTSM3JTWNLijJL1KjsKf60')
     address = str(address_line1) + ',' + str(address_line2) + ',' + str(
         area) + ',' + str(city) + ',' + str(state) + ',' + str(
             country) + ',' + str(pincode)
     geocode_result = gmaps.geocode(address)
     print(geocode_result[0]['formatted_address'])
     place_id = geocode_result[0]['place_id']
     return place_id
示例#11
0
def getLocation(address_line1,address_line2,area,city,state,country,pincode):
    gmaps = GoogleMaps('AIzaSyBoy1plslvW_UTSM3JTWNLijJL1KjsKf60')
    address = str(address_line1)+ ',' + str(address_line2)+ ',' + str(area) + ',' + str(city) + ',' + str(state) + ',' + str(country) + ',' + str(pincode)
    geocode_result = gmaps.geocode(address)
    lat = geocode_result[0]['geometry']['location'] ['lat']
    lon = geocode_result[0]['geometry']['location']['lng']
    print(lat,lon)
    location = "SRID=4326;POINT ("+str(lat) + " " + str(lon)+")"
    print(location)
    return location
示例#12
0
 def _geo_loc(self, cr, uid, ids, field_name, arg, context):
     result = {}
     gmaps = GoogleMaps(
         "http://maps.googleapis.com/maps/api/js?key=AIzaSyBwNE-vFDyyOb62ODaRiqpiL2kz8wR0aTc"
     )
     for partner in self.browse(cr, uid, ids):
         address = partner.street
         lat, lng = gmaps.address_to_latlng(address)
         latlng = str(lat) + "," + str(lng)
         result[partner.id] = str(latlng)
     return result
def compress(address):
    try:
        gmaps = GoogleMaps('AIzaSyAH-SEZ1C_8Kb1ACyPCZZpZAJKKDuWD3Ro')
        geocode_result = gmaps.geocode(address)
        return geocode_result[0]['geometry']['location'][
            'lat'], geocode_result[0]['geometry']['location']['lng']
    except IndexError:
        print("Address was wrong...")
        return "null", "null"
    except Exception as e:
        print("Unexpected error occurred.", e)
示例#14
0
def main():

    output = '/net/casfsb/vol/ssrchome/active_users/ceholden/img_names.txt'
    f = codecs.open(output, 'w', encoding='utf-8')

    #    refimg = '/net/casrs1/volumes/cas/landsat25/reference_images/catalog'
    #    os.chdir(refimg)

    # GoogleMaps API key
    apik = 'AIzaSyA2w-3WNR5joUnHa4K7WDs2eyC-nzjr3fE'
    gmaps = GoogleMaps(apik)
示例#15
0
def select(paras):
    gmaps = GoogleMaps()
    address = paras['street'] + ", " + paras['city'] + ", " + paras['state']
    latitude, longtitude = gmaps.address_to_latlng(address)
    print "Location convertion: " + str(latitude) + str(longtitude)
    time_start_mon = int(paras['s_mon'])
    time_start_day = int(paras['s_day'])
    time_start_hour = int(paras['s_hou'])
    time_end_mon = int(paras['e_mon'])
    time_end_day = int(paras['e_day'])
    time_end_hour = int(paras['e_hou'])
    radius = paras['r']
    start_time = datetime.datetime(2012, time_start_mon, time_start_day,
                                   time_start_hour, 0)
    end_time = datetime.datetime(2012, time_end_mon, time_end_day,
                                 time_end_hour, 0)
    start_epoch_time = time.mktime(start_time.timetuple()) * 1000
    end_epoch_time = time.mktime(end_time.timetuple()) * 1000
    distance = "3959*acos((sin({3}/57.29577951)*sin(latitude/57.29577951)+cos({3}/57.29577951)*cos(latitude/57.29577951)*cos(abs(longtitude-({2}))/57.29577951))) <{4}"
    querystr = (
        "select user, uid, feature, longtitude, latitude, time, size from Meta_data where time >= {0} and time <= {1} and "
        + distance + " order by user;").format(start_epoch_time,
                                               end_epoch_time, longtitude,
                                               latitude, radius)

    if (paras['r'] == '0'):
        querystr = (
            "select user, uid, feature, longtitude, latitude, time, size from Meta_data where time >= {0} and time <= {1} order by user;"
        ).format(start_epoch_time, end_epoch_time)
    print querystr
    con, cur = sql_execute(querystr)

    data = []
    while True:
        dat = cur.fetchone()
        if dat == None:
            break
        data.append(dat)
    if (paras['type'] == '0'):
        return top_k_similar(data, paras['option1'], paras['option2'],
                             paras['deadline'])
    if (paras['type'] == '1'):
        return mst.call_mst(data, paras['deadline'])
    if (paras['type'] == '2'):
        return kmeans_new.call_kmeans(data, paras['deadline'],
                                      int(paras['option1']))
    if (paras['type'] == '3'):
        return represent.call_represent(data, paras['deadline'],
                                        int(paras['option1']))
    else:
        return [], []
    pass
示例#16
0
def add_coordinate_info(df, api_key):
    gmaps = GoogleMaps(api_key)
    df['long'] = ""
    df['lat'] = ""
    long = []
    lat = []
    for location in progress_bar(df.location):
        long_, lat_ = get_lat_long(location, gmaps)
        long.append(long_)
        lat.append(lat_)
    df.long = long
    df.lat = lat
    return df.reset_index(drop=True)
示例#17
0
def pegar_coordenadas_rotas(arquivo_rotas):
    """
    Função que retorna uma lista contendo um dicionário com as informações 
    das rotas passada no arquivo, este dicionário contém as seguinte informações:
    
    'rotas' -> Contem 
    'distancia' -> Distância em metros entre a origem e o destino
    'tempo' -> Tempo em segundos entre a origem e o destino
    'origem' -> Origem
    'destino' -> Destino
    'velocidade' -> Velocidade em metros por segundos
    """
    
    maps = GoogleMaps()
    rotas = []
    
    try:
        with open(arquivo_rotas, 'r') as f:
            content = f.readlines()

        for i in content:
                
            try:
                source = re.search('from:(.*?)to:(.*)', i).group(1)
                dest = re.search('from:(.*?)to:(.*)', i).group(2)
                
            except:
                sys.stderr.write("Sintaxe do arquivo de rotas errada, verifique a documentação\n\n")
                sys.exit(0)
            
            try:
                info = maps.directions(source, dest)
                
                routes = info['Directions']['Routes'][0]['Steps']
                Distancia = info['Directions']['Distance']['meters']
                Tempo = info['Directions']['Duration']['seconds']
                Origem = info['Placemark'][0]['address']
                Destino = info['Placemark'][1]['address']
                corigem = info['Placemark'][0]['Point']['coordinates']
                cdestino = info['Placemark'][1]['Point']['coordinates']
                
                Velocidade = Distancia/Tempo
                rotas.append({'rotas':routes, 'distancia':Distancia, 'tempo':Tempo, 'origem':Origem, 'destino':Destino, 'velocidade':Velocidade, 'corigem': corigem, 'cdestino': cdestino})
                
            except:
                sys.stderr.write('Rota inexistente para: Origem: {} Destino: {}\n'.format(source, dest))
        
    except IOError:
        sys.stderr.write('Não foi possível abrir o arquivo de rotas\n')        
    
    return rotas
def get_coordinates(address: str, api_key: str) -> tuple:
    """ 
    Takes in a string address and Google API key.
    Returns a tuple with latitude and longitude.
    """
    gmaps = GoogleMaps(api_key)
    geocode_result = gmaps.geocode(address)
    try:
        lat = geocode_result[0]['geometry']['location']['lat']
        long = geocode_result[0]['geometry']['location']['lng']
        return lat, long
    except IndexError:
        print(f'Error: coordinates not found for location: {address}')
        return 0, 0
示例#19
0
def get_lat_lng(address, silent=False):
    """
    address(unicode)からlat, lngを検索して返す
    silent = Trueだとエラーを出さない
    """
    addr_utf8 = smart_str(address)
    try:
        gmaps = GoogleMaps(GOOGLE_MAPS_API_KEY)
        lat, lng = gmaps.address_to_latlng(addr_utf8)
    except GoogleMapsError:
        if silent:
            return None, None
        raise
    return str(lat), str(lng)
示例#20
0
def get_coord_dir(direction):
    load_dotenv()

    G_KEY = os.getenv("KEY_GOOGLE")
    gmaps = GoogleMaps(G_KEY)
    geocode_result = gmaps.geocode(direction)
    try:
        lat = geocode_result[0]["geometry"]["location"]["lat"]
        lon = geocode_result[0]["geometry"]["location"]["lng"]
        return lat, lon
    except:
        lat = None
        lon = None
        print('At least I tried')
示例#21
0
def dist_from(destination, location):
    gmaps = GoogleMaps(
        'ABQIAAAAAPMmDP4HCUrLtqjxnhTeXRQV_yMSNSvbo2tmQzi3qOzMvFrzcRTFTor1bOkU8NE2pW1HDlgjEDlcIQ'
    )
    try:
        origin = location
        destination = '6224 Agricultural Road Vancouver, B.C. CA V6T 1Z1'
        dirs = gmaps.directions(origin, destination, mode='walking')
        time = dirs['Directions']['Duration']['html']
        dist = dirs['Directions']['Distance']['meters']
        route = dirs['Directions']['Routes'][0]
        return dist
    except GoogleMapsError:
        return 10000
示例#22
0
def getCoord(location):
    start_time = time.time()
    msj = ''
    gmaps = GoogleMaps(os.getenv("GOOGLE_KEY"))

    wk = []
    for key in location.keys():
        if 'name' not in key:
            wk.append(key)
    address = normalizeWord(re.sub(',', '', ', '.join(value for value in dict(zip(wk, [location[k] for k in wk])).values() if value), 1))

    print(f"ADDRESS: {address}")

    geocode_result = gmaps.geocode(address)

    data = {'long': {}, 'short': {}, 'location': {}}

    if geocode_result:
        for geolist in geocode_result:
            for item in geolist['address_components']:
                for category in item['types']:
                    data['long'].update([(category, item['long_name'])])
                    data['short'].update([(category, item['short_name'])])
            data['location'] = geolist['geometry']['location']
    else:
        msj = 'Coordinates not found. Please check Address sent'

    try:
        data['long']['administrative_area_level_1'] = getLocal('provincias', [dict(nombre=data.get('long').get('administrative_area_level_1'))]).get('nombre', None)
    except IndexError:
        raise serializers.ValidationError('Could not validate Locality')

    # print('location country: {} - gmaps country: {}'.format(location['country'], data.get('long').get('country')))
    # print('gmaps route: {}'.format(data.get('short').get('route')))
    print(f"DATA: {data['long']['administrative_area_level_1']}")

    if data.get('long').get('country') == location['country'] and normalizeWord(data.get('long').get('administrative_area_level_1')) == normalizeWord(location['province']):
        if data.get('short').get('route'): location['street'] = data.get('short').get('route')
        if data.get('short').get('locality'): location['city'] = data.get('short').get('locality')
        location['province'] = data.get('long').get('administrative_area_level_1')
        location['latitude'] = data.get('location').get('lat')
        location['longitude'] = data.get('location').get('lng')
    else:
        msj = 'Address not Validated'

    print(data['long']['administrative_area_level_1'])
    print('--- Tiempo de ejecucion getCoord: {} segundos ---'.format((time.time() - start_time)))
    return location, msj

    return location, msj
示例#23
0
def query_obs(location):
    """
    Query information about a given location.
    
    'CFHT Hawaii'
    'Roque de los muchachos, Canary Islands'
    'Siding Spring, Australia'
    
    """
    
    print "Where the f**k is", location
    gmaps  = GoogleMaps()
    result = gmaps.geocode(location)
    
    pprint.pprint(result['Placemark'][0])
示例#24
0
 def storeloc(self, x):
     try:
         message = " "
         api_key = 'YOUR-API-KEY'
         gmaps = GoogleMaps(api_key)
         geocode_result = gmaps.geocode(x)[0]
         lat = geocode_result["geometry"]["location"]["lat"]
         lng = geocode_result["geometry"]["location"]["lng"]
         store = gmaps.places_nearby(location=(lat, lng), type='store', radius=500)
         for i in range(0, 5):
             message = message + str(store["results"][i]["name"] + "\n")
         return message
     except:
         message = "You have Entered a invalid input please try again!"
         return message
示例#25
0
def getLocationByResourceId(r_id):
    class Map:
        def __init__(self, name, lat, lng):
            self.name = name
            self.lat = lat
            self.lng = lng

    api_key = "AIzaSyCeHf-jcEx21QPuV7BZOUOukikZ-bQYxDA"
    google = GoogleMaps(api_key)
    location = ResourcesHandler().getLocationByResourceId(r_id)
    geocode_result = google.geocode(location + ', Puerto Rico')
    lat = geocode_result[0]['geometry']['location']['lat']
    lng = geocode_result[0]['geometry']['location']['lng']
    map = Map(location, lat, lng)
    return render_template('map.html', map=map)
def get_location(address):
    """def get_location(address)
    Descripció: Cerca la latitud i longitud d'un adreça.
    Entrada:    String amb l'adreça.
    Sortida:    String amb la latitud i longitud o codi d'error
                segons el resultat de la cerca.
    """
    try:
        gmaps = GoogleMaps(API_KEY)
        geocode_result = gmaps.geocode(address)[0]
        lat = geocode_result["geometry"]["location"]['lat']
        lng = geocode_result["geometry"]["location"]['lng']
        address_lat_lng = (str(lat) + ", " + str(lng))
        return address_lat_lng
    except IndexError:
        return ADDRESS_NOT_FOUND_CODE
示例#27
0
def directions(start, end, unsafe=False):

    api_key = 'Your API Key'

    mapService = GoogleMaps(api_key)

    url = 'http://maps.googleapis.com/maps/api/directions/json?%s' % urlencode(
        (('origin', start), ('destination', end)))
    ur = urllib.urlopen(url)
    result = json.load(ur)

    for i in range(0, len(result['routes'][0]['legs'][0]['steps'])):
        j = result['routes'][0]['legs'][0]['steps'][i]['html_instructions']
        print strip_tags(j)

    return
示例#28
0
def hello_monkey():
    def chooseSymbol(line):
        if 'head' in line:
            return "head"
        elif 'roundabout' in line:
            return 'roundabout'
        elif 'right' in line:
            return "right"
        elif 'left' in line:
            return "left"
        elif 'merge' in line:
            return "merge"
        else:
            return 'none'

    body_message = str(request.values.get('Body', None))
    latitude = body_message.split('_')[0]
    longitude = body_message.split('_')[1]
    destination = body_message.split('_')[2]
    mapService = GoogleMaps()
    directions = mapService.directions('RG7 5ND', 'RG7 5NN')
    message = ""
    #for step in directions['Directions']['Routes'][0]['Steps']:
    #	message = message + step['descriptionHtml']
    mapsUrl = 'https://maps.googleapis.com/maps/api/directions/json?origin=' + str(
        latitude) + ',' + str(longitude) + '&destination=' + str(
            destination) + '&mode=walking'
    response = urllib.urlopen(mapsUrl)

    data = yaml.load(response.read())
    leg = data.get('routes')[0].get('legs')[0]
    general_data = leg.get('distance').get('text') + '_' + leg.get(
        'duration').get('text')
    stepMessage = ""
    stepsArray = leg.get('steps')
    for step in stepsArray:
        line = step.get('html_instructions')
        stepMessage = stepMessage + line + '_' + step.get('distance').get(
            'text') + '_' + chooseSymbol(line) + '/n'

    #message = str(directions)[0:100]
    #message = "Latitude: " + str(latitude) + " Longitude: " + str(longitude) + " Destination: " + str(destination)
    message = str(stepMessage)
    resp = twilio.twiml.Response()
    resp.message(message)
    return str(resp)
示例#29
0
def get_address_latlng(location):
    """
    Requests the latitude and longitude for the given location's address.

    Uses the Google Maps API, but could be extended to use a different API.
    """
    address = u"%s, %s, %s %s" % (location.street_address, location.city,
                                  location.state, location.postal_code)
    try:
        return GoogleMaps().address_to_latlng(address)
    except GoogleMapsError:
        raise LocationEncodingError(_("Google reported an error!"))
    except URLError:
        raise LocationEncodingError(_("Hmm, network error. Please try again."))
    except Exception, e:
        raise LocationEncodingError(_("Unknown error: %s, %s" %
                                      (Exception, e)))
示例#30
0
def main():
    # connect to gmail server
    print 'connecting to gmail server...'
    username = raw_input("Gmail username: "******"google_maps_key.txt", "r").read()
    GMAPS = GoogleMaps(GOOGLE_API_KEY)
    rides = []
    for receipt in receipts:
        ride = receipt.to_ride().set_distance(GMAPS)
        rides.append(ride)

    print 'done.'

    # put data in array, insert into database
    print 'filling database...'
    data = [(r.distance, r.price, r.bonus, r.time) for r in rides]
    conn = build_db(data)
    print 'done.'

    # query for results
    print 'running queries...'
    results = run_queries(conn)
    print 'done.'

    # plot charts
    print 'plotting charts...'
    plt = plot_data(results)
    plt.show()
    print 'done.'

    # dump coordinates data to json file
    print 'exporting coordinates...'
    export = export_coordinates(rides)
    print 'done.'