def test_local_search(self): """Test googlemaps local_search().""" gmaps = GoogleMaps(GMAPS_API_KEY, referrer_url='http://www.google.com/') local = gmaps.local_search('sushi san francisco, ca') result = local['responseData']['results'][0] self.assertEqual(result['titleNoFormatting'], 'Sushi Groove') results = gmaps.local_search('Starbucks Los Angeles, CA', numresults=GoogleMaps.MAX_LOCAL_RESULTS) self.assertEqual(results['responseStatus'], googlemaps.STATUS_OK) self.assertNotEqual(results['responseData'], None) self.assertNotEqual(results['responseData']['cursor'], None) results = results['responseData']['results'] self.assertEqual(len(results), GoogleMaps.MAX_LOCAL_RESULTS) for result in results: self.assertEqual(result['GsearchResultClass'], 'GlocalSearch') self.assert_(result['titleNoFormatting'].lower().find('starbucks') >= 0) self.assertEqual(result['region'], 'CA')
def FindPizza(): print "Enter in an address to find Pizza places near it" address = raw_input() gmaps = GoogleMaps("AIzaSyA5R4PnzAcoe2vpVRKyWWby-d6RrMmIwtQ") lat, lng = gmaps.address_to_latlng(address) destination = gmaps.latlng_to_address(lat, lng) Pizza = gmaps.local_search('pizza near ' + destination) directions = gmaps.directions(address, destination) print "The nearest Pizza place is " + Pizza['responseData']['results'][0]['titleNoFormatting'] for step in directions['Directions']['Routes'][0]['Steps']: print step['descriptionHtml']
def test_local_search(self): """Test googlemaps local_search().""" gmaps = GoogleMaps(GMAPS_API_KEY, referrer_url='http://www.google.com/') local = gmaps.local_search('sushi san francisco, ca') result = local['responseData']['results'][0] self.assertEqual(result['titleNoFormatting'], 'Sushi Groove') results = gmaps.local_search('Starbucks Los Angeles, CA', numresults=GoogleMaps.MAX_LOCAL_RESULTS) self.assertEqual(results['responseStatus'], googlemaps.STATUS_OK) self.assertNotEqual(results['responseData'], None) self.assertNotEqual(results['responseData']['cursor'], None) results = results['responseData']['results'] self.assertEqual(len(results), GoogleMaps.MAX_LOCAL_RESULTS) for result in results: self.assertEqual(result['GsearchResultClass'], 'GlocalSearch') self.assert_( result['titleNoFormatting'].lower().find('starbucks') >= 0) self.assertEqual(result['region'], 'CA')
def get_distance_from_railways(self, address, max_distance=3, retry_wait=1): attempts = 0 results = [] while (True): gmaps = GoogleMaps() try: lat, lng = gmaps.address_to_latlng(address) local_search = gmaps.local_search('railway near ' + address) except GoogleMapsError: # Some sort of error occurred! Either the address is malformed, # or the server is having some sort of issue. We'll wait a little bit # and try again if attempts < self.max_attempts: attempts += 1 # Wait 1 seconds before trying again time.sleep(retry_wait) logger.debug("... ... ... Failed to parse the address. Trying again. Attempt #" + attempts) continue else: logger.debug("... ... ... Failed all attempts. Skipping.") return None # Get our results for result in local_search['responseData']['results']: # Probably not accurate over this point... Weird things # can get in if int(result['accuracy']) > 5: continue distance = self.haversine(lng, lat, float(result["lng"]), float(result["lat"])) data = { 'line_name': result['titleNoFormatting'], 'distance': round(distance, 2) } if (distance < max_distance): results.append(data) return results
def get_places(): place_types = {'yoga': 'yoga', 'pole': 'pole dancing', 'coffee':'coffee shop', 'beer': 'brew pub', 'strip': 'strip club', 'bikes': 'bicycle shop', 'meditate': 'meditation', 'tattoo': 'tattoo'} gmaps = GoogleMaps(api_key) for place_type in place_types: local = gmaps.local_search('%s near portland, or' % place_types[place_type], numresults=GoogleMaps.MAX_LOCAL_RESULTS) for result in local['responseData']['results']: kwargs={'name': result['titleNoFormatting'].encode('utf-8'), 'address': result['streetAddress'].encode('utf-8')} try: p = Place.objects.get(**kwargs) except Place.DoesNotExist: p = Place(**dict((k,v) for (k,v) in kwargs.items() if '__' not in k)) p.static_map=result['staticMapUrl'].encode('utf-8') p.point=Point(float(result['lng']), float(result['lat'])) p.place_type=place_type p.save() print "saved %s" % p.name
from googlemaps import GoogleMaps api_key = 'AIzaSyA5nMPOn0fpv824YiL2sab5-NZejD9lXvA' gmaps = GoogleMaps(api_key) whitehouse = '1600 Pennsylvania Avenue, Washington, DC' lat, lng = gmaps.address_to_latlng(whitehouse) print lat, lng destination = gmaps.latlng_to_address(38.897096, -77.036545) print destination dlat, dlng = gmaps.address_to_latlng('326 Perkins Library, Durham, NC 27708') print dlat, dlng duke = gmaps.latlng_to_address(dlat, dlng) print duke local = gmaps.local_search('restaurant near ' + duke) print local['responseData']['results'][0]['titleNoFormatting'] directions = gmaps.directions(duke, whitehouse) print directions['Directions']['Distance']['meters'] for step in directions['Directions']['Routes'][0]['Steps']: print step['descriptionHtml'] embassies = [[38.917228,-77.0522365], [38.9076502, -77.0370427], [38.916944, -77.048739] ] # TODO: write code to answer the following questions: # which embassy is closest to the White House in meters? how far? # what is its address?
from googlemaps import GoogleMaps gmaps = GoogleMaps('AIzaSyCK5s0DXmGKoZ_CgwFMQ6G0dN1UcDBDv14') f = open('escondido_list.txt', 'r') for line in f: #lat, lng = gmaps. if line[:3] != '***': local = gmaps.local_search(line + ' near 94305') lat, lng = gmaps.address_to_latlng(local['responseData']['results'][0]['streetAddress']) print lat
def xls_to_orm(self, columns=None): row_excluded = [] file = self.attach errors = [] #se seleccionan las columnas segun la decision del usuario. En caso de no elegir al menos una en particular el sistema importa la totalidad de las columnas if columns: columns = self.column_set.filter(pk__in=columns) else: columns = self.column_set.all() self.delete_old_values() src = self.open_source() for column in columns: #Para cada columna que el usuario haya seleccionado para importar, se recorren todos sus valores creando objetos del tipo ValueX donde X es el tipo del valor que se esta recorriendo col_tp = src.col_types(column.csv_index,start_rowx=1) for i, val in enumerate(src.col_values(column.csv_index,start_rowx=1)): #Para cada valor asociado a la columna seleccionada (column) se crea una instancia del tipo Valor if col_tp[i] == 1 and column.data_type=='point': value = ValuePoint() elif col_tp[i] == 1 and column.data_type=='area': value = ValueArea() elif col_tp[i] == 1 and column.data_type!='area' and column.data_type!='point': value = ValueText() elif col_tp[i] == 2: value = ValueFloat() elif col_tp[i] == 3: value = ValueDate() elif col_tp[i] == 4: value = ValueBool() value.value = val value.data_type = col_tp[i] value.column = column try: row_obj = Row.objects.filter(datasource=self,csv_index=i+1).first() except: #Se crea una nueva instancia de fila row_obj = Row(datasource=self,csv_index=i+1) row_obj.save() value.row = row_obj value.save() search_term = slugify(value.value) self.geopositionated = False #SI LOS DATOS SON GEOPOSICIONADOS if column.data_type == 'point': gmaps = GoogleMaps(settings.GOOGLEMAPS_API_KEY) self.geopositionated = True #se debe hacer primero una consulta a la base local results = MaapPoint.objects.filter(slug=search_term) if len(results) >= 1: #En este caso quiere decir que la consulta a la base local fue exitosa for point in results: value.point = point value.map_url = point.static_url value.save() if len(results) < 1: #Este caso quiere decir que la consulta a la base local no fue exitosa y por lo tanto se procede a buscarlo via web. Aca se debe controlar solo el caso que sea unico. Ahora esta asi porque hay muchos MaapPoint iguales results = gmaps.local_search('%s, cordoba, argentina' %value.value )['responseData']['results'] for result in results: latlng = [float(result.get('lng')), float(result.get('lat'))] point = MaapPoint( geom=Point(latlng).wkt, name=value.value, ) point.static_url = result.get('staticMapUrl', None) point.save() value.point = point value.map_url = point.static_url value.save() #SI LOS DATOS SON GEOPOSICIONADOS if column.data_type == 'area': self.geopositionated = True barrio = MaapArea.objects.filter(slug=search_term) if len(barrio) == 1: value.area = barrio[0] value.save() if len(errors) == 0: self.is_dirty = False self.save() if self.geopositionated: values_geo = Value.objects.filter(column__datasource=self,column__has_geodata=True) for t in values_geo: qs = Value.objects.filter(column__datasource=self,column__has_geodata=False,row=t.row) for u in qs: u.area = t.area u.save() print errors return self.get_absolute_url()
api_key = "your api key from developers.google.com" gmaps = GoogleMaps(api_key) whitehouse = "1600 Pennsylvania Avenue, Washington, DC" lat, lng = gmaps.address_to_latlng(whitehouse) print lat, lng destination = gmaps.latlng_to_address(38.897096, -77.036545) print destination dlat, dlng = gmaps.address_to_latlng("326 Perkins Library, Durham, NC 27708") print dlat, dlng duke = gmaps.latlng_to_address(dlat, dlng) print duke local = gmaps.local_search("restaurant near " + duke) print local["responseData"]["results"][0]["titleNoFormatting"] directions = gmaps.directions(duke, whitehouse) print directions["Directions"]["Distance"]["meters"] for step in directions["Directions"]["Routes"][0]["Steps"]: print step["descriptionHtml"] embassies = [[38.917228, -77.0522365], [38.9076502, -77.0370427], [38.916944, -77.048739]] # TODO: write code to answer the following questions: # which embassy is closest to the White House in meters? how far? # what is its address? # if I wanted to hold a morning meeting there, which cafe would you suggest? # if I wanted to hold an evening meeting there, which bar would you suggest?
print check except: print "Wystapil nieznany blad! Przepraszamy." elif wybor == 2: try: cel1 = raw_input('Czego poszukujesz?: ') address3 = raw_input('W jakiej okolicy?: ') if address3 == "" or cel1 == "": print "" print "Prosze podac poprawne nazwy miejscowosci i punkty docelowe." else: lat3, lng3 = gmaps.address_to_latlng(cel1 + ' ' + address3) lat6, lng6 = gmaps.address_to_latlng(address3) miejsce = gmaps.latlng_to_address(lat6, lng6) destination3 = gmaps.latlng_to_address(lat3, lng3) local = gmaps.local_search(cel1 + ' ' + address3) print local['responseData']['results'][0]['titleNoFormatting'] if miejsce != destination3: print destination3 else: pass except: print "Wystapil nieznany blad! Przepraszamy." elif wybor == 3: try: address4 = raw_input('Podaj nazwe miejscowosci startowej: ') cel2 = raw_input('Czego poszukujesz?: ') address5 = raw_input('Podaj miejscowosc, w ktorej szukac: ') if address4 == "" or address5 == "" or cel2 == "": print "" print "Prosze podac poprawne nazwy miejscowosci i punkty docelowe."
def xls_to_orm(self, columns=None): row_excluded = [] file = self.attach errors = [] #se seleccionan las columnas segun la decision del usuario. En caso de no elegir al menos una en particular el sistema importa la totalidad de las columnas if columns: columns = self.column_set.filter(pk__in=columns) else: columns = self.column_set.all() self.delete_old_values() src = self.open_source() for column in columns: #Para cada columna que el usuario haya seleccionado para importar, se recorren todos sus valores creando objetos del tipo ValueX donde X es el tipo del valor que se esta recorriendo col_tp = src.col_types(column.csv_index, start_rowx=1) for i, val in enumerate( src.col_values(column.csv_index, start_rowx=1)): #Para cada valor asociado a la columna seleccionada (column) se crea una instancia del tipo Valor if col_tp[i] == 1 and column.data_type == 'point': value = ValuePoint() elif col_tp[i] == 1 and column.data_type == 'area': value = ValueArea() elif col_tp[ i] == 1 and column.data_type != 'area' and column.data_type != 'point': value = ValueText() elif col_tp[i] == 2: value = ValueFloat() elif col_tp[i] == 3: value = ValueDate() elif col_tp[i] == 4: value = ValueBool() value.value = val value.data_type = col_tp[i] value.column = column try: row_obj = Row.objects.filter(datasource=self, csv_index=i + 1).first() except: #Se crea una nueva instancia de fila row_obj = Row(datasource=self, csv_index=i + 1) row_obj.save() value.row = row_obj value.save() search_term = slugify(value.value) self.geopositionated = False #SI LOS DATOS SON GEOPOSICIONADOS if column.data_type == 'point': gmaps = GoogleMaps(settings.GOOGLEMAPS_API_KEY) self.geopositionated = True #se debe hacer primero una consulta a la base local results = MaapPoint.objects.filter(slug=search_term) if len(results) >= 1: #En este caso quiere decir que la consulta a la base local fue exitosa for point in results: value.point = point value.map_url = point.static_url value.save() if len(results) < 1: #Este caso quiere decir que la consulta a la base local no fue exitosa y por lo tanto se procede a buscarlo via web. Aca se debe controlar solo el caso que sea unico. Ahora esta asi porque hay muchos MaapPoint iguales results = gmaps.local_search( '%s, cordoba, argentina' % value.value)['responseData']['results'] for result in results: latlng = [ float(result.get('lng')), float(result.get('lat')) ] point = MaapPoint( geom=Point(latlng).wkt, name=value.value, ) point.static_url = result.get('staticMapUrl', None) point.save() value.point = point value.map_url = point.static_url value.save() #SI LOS DATOS SON GEOPOSICIONADOS if column.data_type == 'area': self.geopositionated = True barrio = MaapArea.objects.filter(slug=search_term) if len(barrio) == 1: value.area = barrio[0] value.save() if len(errors) == 0: self.is_dirty = False self.save() if self.geopositionated: values_geo = Value.objects.filter(column__datasource=self, column__has_geodata=True) for t in values_geo: qs = Value.objects.filter(column__datasource=self, column__has_geodata=False, row=t.row) for u in qs: u.area = t.area u.save() print errors return self.get_absolute_url()