当前位置: 首页>>代码示例>>Python>>正文


Python GoogleMaps.local_search方法代码示例

本文整理汇总了Python中googlemaps.GoogleMaps.local_search方法的典型用法代码示例。如果您正苦于以下问题:Python GoogleMaps.local_search方法的具体用法?Python GoogleMaps.local_search怎么用?Python GoogleMaps.local_search使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在googlemaps.GoogleMaps的用法示例。


在下文中一共展示了GoogleMaps.local_search方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_local_search

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import local_search [as 别名]
 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')
开发者ID:coxmediagroup,项目名称:py-googlemaps,代码行数:19,代码来源:test_googlemaps.py

示例2: FindPizza

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import local_search [as 别名]
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']
开发者ID:bscharfstein,项目名称:bscharfstein,代码行数:13,代码来源:location.py

示例3: get_distance_from_railways

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import local_search [as 别名]
    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
开发者ID:NervosaX,项目名称:reparser,代码行数:46,代码来源:gmaps.py

示例4: get_places

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import local_search [as 别名]
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
开发者ID:eknuth,项目名称:pimh,代码行数:24,代码来源:load.py

示例5: GoogleMaps

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import local_search [as 别名]
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? 
开发者ID:carlson9,项目名称:python-washu-2014,代码行数:33,代码来源:gmaps.py

示例6: GoogleMaps

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import local_search [as 别名]
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
开发者ID:Wesleyleung,项目名称:bahamas,代码行数:13,代码来源:location_script.py

示例7: xls_to_orm

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import local_search [as 别名]
    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()

#.........这里部分代码省略.........
开发者ID:apanruning,项目名称:sitseg.docus,代码行数:103,代码来源:models.py

示例8: GoogleMaps

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import local_search [as 别名]
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?
开发者ID:jaeheejung,项目名称:python-washu-2014,代码行数:32,代码来源:gmaps.py

示例9: raw_input

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import local_search [as 别名]
				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."
开发者ID:sylwekksiazek,项目名称:gmaps,代码行数:33,代码来源:gmaps.py


注:本文中的googlemaps.GoogleMaps.local_search方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。