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


Python GoogleMaps.directions方法代码示例

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


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

示例1: get_directions

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import directions [as 别名]
def get_directions():
    api_key = 'AIzaSyAyspF7tDu4Tv0X23RQDjoCoVewalLRv4Q'
    gmaps = GoogleMaps(api_key)
    start = ",".join(driver_start_latlng())
    end = ",".join(rider_start_latlng())
    start2 = ",".join(rider_end_latlng())
    end2 = ",".join(driver_end_latlng())
    dirs = gmaps.directions(start, end)
    time = dirs['Directions']['Duration']['seconds']
    dist = dirs['Directions']['Distance']['meters']
    route = dirs['Directions']['Routes'][0]
    dirs1 = gmaps.directions(end, start2)
    time1 = dirs1['Directions']['Duration']['seconds']
    dist1 = dirs1['Directions']['Distance']['meters']
    route1 = dirs1['Directions']['Routes'][0]
    dirs2 = gmaps.directions(start2, end2)
    time2 = dirs2['Directions']['Duration']['seconds']
    dist2 = dirs2['Directions']['Distance']['meters']
    route2 = dirs2['Directions']['Routes'][0]
    for step in route['Steps']:
        #print step['Point']['coordinates'][1], step['Point']['coordinates'][0]
        print step['descriptionHtml']
    for step in route1['Steps']:
        #print step['Point']['coordinates'][1], step['Point']['coordinates'][0]
        print step['descriptionHtml']
    for step in route2['Steps']:
       # print step['Point']['coordinates'][1], step['Point']['coordinates'][0]
        print step['descriptionHtml']
开发者ID:cryanperkins,项目名称:PublicCode,代码行数:30,代码来源:Poolryde.py

示例2: miles

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import directions [as 别名]
def miles(date):
    if not session.get('logged_in'):
        return redirect(url_for('register'))

    # look for any visits
    g.cursor.execute("SELECT * FROM visits v, destinations d WHERE v.day = %s AND v.dest_id = d.id AND v.user_id = %s ORDER BY v.time ASC", (date, g.user_id))
    visits = g.cursor.fetchall()

    if not visits:
        return jsonify(miles=0)

    gmaps = GoogleMaps(GDATA_API_KEY)

    # look for a cached count of the miles
    last_visit = None
    miles = 0.0
    for visit in visits:
        visit = decode_destination(visit)
        if last_visit is None:
            last_visit = visit
            continue
        g.cursor.execute("SELECT miles FROM miles WHERE start_dest_id = %s AND end_dest_id = %s", (last_visit['dest_id'], visit['dest_id']))
        trip_miles = g.cursor.fetchone()
        if trip_miles:
            miles += float(trip_miles['miles'])
        else:
            directions = gmaps.directions(last_visit['address'], visit['address'])
            trip_meters = directions['Directions']['Distance']['meters']
            trip_miles = int(trip_meters * (1/1609.344))
            miles += trip_miles
            g.cursor.execute("INSERT INTO miles (start_dest_id, end_dest_id, miles) VALUES(%s, %s, %s)", (last_visit['dest_id'], visit['dest_id'], trip_miles))
        last_visit = visit

    return jsonify(miles=miles)
开发者ID:adregner,项目名称:mile-tracker,代码行数:36,代码来源:mile-tracker.py

示例3: direcs

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import directions [as 别名]
def direcs(loc1, loc2):
    ret = ""
    gmaps = GoogleMaps()
    
    try:
        directions = gmaps.directions(loc1, loc2)
    except:
        return "At least one invalid address. Please try again."
    
    ret += "Will take about " + directions['Directions']['Duration']['html'] + "\n"
    
    for step in directions['Directions']['Routes'][0]['Steps']:
        if "Destination will be on the" in step['descriptionHtml']:
            idx = step['descriptionHtml'].index("Destination")
            s = step['descriptionHtml'][:idx] + "\n" + step['descriptionHtml'][idx:]
            ret += s
        else:
            ret += step['descriptionHtml'] + "\n"
            
    a = ""
    inBracks = False
    for i in range(len(ret)):
        if ret[i] == "<":
            inBracks = True
        elif ret[i] == ">":
            inBracks = False;
        else:
            if inBracks == False:
                a += ret[i]
    return a
开发者ID:jarjun,项目名称:textfordirections,代码行数:32,代码来源:TextForDirections.py

示例4: verify_restaurant

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import directions [as 别名]
def verify_restaurant(start):
	api_key = settings.GOOGLE_MAPS
	geo = GoogleMaps(api_key)
	error = "Unfortunately, we are not yet delivering in your area."
	wrong_addr = False

	for r in Restaurant.objects.all():
		end = r.get_address_string()
		try:
			dirs = geo.directions(start, end)
		except:
			wrong_addr = True
			error = "Please enter a valid address."

		dist = float("inf")

		if not wrong_addr:
			dist = dirs['Directions']['Distance']['meters']

		good_radii = ['LaSalle', 'lasalle', 'laSalle', 'LaSalle', 'Lasalle', 'Morreene']

		start_split = start.split(" ")

		for radius in good_radii:
			if radius in start_split:
				return (True, r)

		if dist < r.max_radius:
			return (True, r)

	return (False, error)
开发者ID:dsethan,项目名称:OverEasy,代码行数:33,代码来源:views.py

示例5: time_to_user_profile

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import directions [as 别名]
	def time_to_user_profile(self):
		api_key = settings.GOOGLE_MAPS
		gmaps = GoogleMaps(api_key)
		start = self.get_address_string
		stop = self.restaurant.get_address_string
		dirs = gmaps.directions(start, stop)
		time = dirs['Directions']['Duration']['seconds']
		return time
开发者ID:dsethan,项目名称:OverEasy,代码行数:10,代码来源:models.py

示例6: dist_to_restaurant

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import directions [as 别名]
	def dist_to_restaurant(self):
		api_key = settings.GOOGLE_MAPS
		gmaps = GoogleMaps(api_key)
		start = self.get_address_string
		stop = self.restaurant.get_address_string
		dirs = gmaps.directions(start, stop)
		dist = dirs['Directions']['Distance']['meters']
		dist_in_miles = float(dist*.000621371)
		return dist_in_miles
开发者ID:dsethan,项目名称:OverEasy,代码行数:11,代码来源:models.py

示例7: find_Path

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import directions [as 别名]
def find_Path(MAP, model):
    gmaps = GoogleMaps()
    
    home = raw_input("Enter your starting address: ")
    end =  raw_input("Enter your destination address: ")
    results = Geocoder.geocode(home)
    results2 = Geocoder.geocode(end)
    #results = Geocoder.reverse_geocode(41.96786329,-87.71349889)
    #results2 = Geocoder.reverse_geocode(41.763258, -87.61172601)

    print '---Finding Path from ', results, ' to ', results2

    dirs  = gmaps.directions(results, results2)

    time  = dirs['Directions']['Duration']['seconds']
    dist  = dirs['Directions']['Distance']['meters']
    route = dirs['Directions']['Routes'][0]
    
    PATH = []
    EVALUATION = []
    
    for step in route['Steps']:
        position = (step['Point']['coordinates'][1], step['Point']['coordinates'][0])
        if position in MAP:
            for i in range(4): PATH.append('H')
            PATH.append('no')
        else:
            for i in range(4):PATH.append('L')
            PATH.append('yes')
        
        #PREDICT FOR EACH CITY IN THE INTERMEDIATE STEPS
        with open("predict.arff", "a") as myfile:
            for elem in PATH:
                if elem == 'yes' or elem == 'no': myfile.write(elem)
                else: myfile.write(elem  + ',')
            myfile.write('\n')
        PATH = []

    EVALUATION = model.TestClassifier("predict.arff")
    #mark current place as SAFE since you're already at that location anyways
    EVALUATION[0] = 'yes'
    
    #Print Final Results At this Point
    k = 0
    for step in route['Steps']:
        position = (step['Point']['coordinates'][1], step['Point']['coordinates'][0])
        print step['Point']['coordinates'][1], step['Point']['coordinates'][0] ,  '===========================>SAFE? ', EVALUATION[k]
        print step['descriptionHtml']
        k +=1
    
    #UPDATE THE FILES
    delete("predict.arff")
    filename2 = "predict.arff"
    shutil.copy("predict_start.arff", filename2)
    if os.path.isfile (filename2): print "Have a Safe Journey"
    else: print "#####Problem Here: Error 99. Engineeer Will Fix the Bug ASAP"
开发者ID:cpatchava,项目名称:cs229,代码行数:58,代码来源:path.py

示例8: test_directions

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import directions [as 别名]
 def test_directions(self):
     gmaps = GoogleMaps(GMAPS_API_KEY)
     origin = 'Constitution Ave NW & 10th St NW, Washington, DC'
     destination = 'Independence and 6th SW, Washington, DC 20024, USA'
     results = gmaps.directions(origin, destination, units='metric')
     leg = results[0]['legs'][0]
     self.assertIn(leg['duration']['value'], range(300, 400))
     self.assertIn(leg['distance']['value'], range(2500, 3000))
     self.assertIn('Constitution Ave NW', leg['steps'][0]['html_instructions'])
     self.assertIn('Independence', leg['steps'][-1]['html_instructions'])
开发者ID:Polyconseil,项目名称:py-googlemaps,代码行数:12,代码来源:test_googlemaps.py

示例9: FindPizza

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

示例10: dist_from

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

示例11: time_from_coords

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import directions [as 别名]
def time_from_coords(src_coords, dst_coords):
    gmaps = GoogleMaps()
    src_addr = gmaps.latlng_to_address(*src_coords).encode('utf-8')
    dst_addr = gmaps.latlng_to_address(*dst_coords).encode('utf-8')
    
    dirs = gmaps.directions(src_addr,dst_addr)
    
    #returns - distance km, time min
    dist = dirs.get('Directions',{}).get('Distance',{}).get('html','')
    duration =  dirs.get('Directions',{}).get('Duration',{}).get('html','')
    
    return (dist,duration)
开发者ID:picklesman,项目名称:impatient_api,代码行数:14,代码来源:directions.py

示例12: get_travel_time_between

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import directions [as 别名]
    def get_travel_time_between(self, address1, address2):
        gmaps = GoogleMaps()
        try:
            directions = gmaps.directions(address1, address2)
        except GoogleMapsError:
            return None

        if directions:
            try:
                return directions["Directions"]["summaryHtml"]
            except KeyError:
                return None
开发者ID:NervosaX,项目名称:reparser,代码行数:14,代码来源:gmaps.py

示例13: pegar_coordenadas_rotas

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

示例14: get_directions

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import directions [as 别名]
	def get_directions(self):
		api_key = "AIzaSyAUYyU_aUoW5iu_pZZ30U0V_bfdPHQMBQM"
		gmaps = GoogleMaps(api_key)
		addr_string = str(self.address) + " " + str(self.city) + " " + str(self.state)
		restaurant_addr = str(self.restaurant.address1) + " " + str(self.restaurant.city) + " " + str(self.restaurant.state)
		dirs = gmaps.directions(restaurant_addr, addr_string)
		time = dirs['Directions']['Duration']['seconds']
		mins = time/60
		secs = time%60
		time_reformatted = str(mins)+":"+str(secs)
		dist = dirs['Directions']['Distance']['meters']
		in_miles = float(dist*.000621371)
		in_miles_reformatted = str(in_miles)
		return (time_reformatted, in_miles_reformatted)
开发者ID:dsethan,项目名称:tripping-dangerzone,代码行数:16,代码来源:models.py

示例15: listStates

# 需要导入模块: from googlemaps import GoogleMaps [as 别名]
# 或者: from googlemaps.GoogleMaps import directions [as 别名]
def listStates(source, destination):
    gmaps = GoogleMaps()
    stateList = []
    # Finding a route from the source to the destination address
    route = gmaps.directions(source, destination)
    for step in route['Directions']['Routes'][0]['Steps']:
        # For each step in the route, find the latitude-longitude coordinates
        latlong = Geocoder.reverse_geocode(step['Point']['coordinates'][1],step['Point']['coordinates'][0])
        # Finding the state corresponding to the lat-long coordinates
        state = latlong.state
        # Checking to avoid duplicates
        if state not in stateList:
            stateList.append(state)
            print state
开发者ID:nramya,项目名称:StateLister,代码行数:16,代码来源:StateLister.py


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