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']
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
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)
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)
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
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
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"
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'])
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 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)
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
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
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_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)
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
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
def find_restaurant(request, address, city, state): start = address + " " + city + " " + state for restaurant in Restaurant.objects.all(): api_key = "AIzaSyAUYyU_aUoW5iu_pZZ30U0V_bfdPHQMBQM" gmaps = GoogleMaps(api_key) end = restaurant.get_address() dirs = gmaps.directions(start, end) dist = dirs['Directions']['Distance']['meters'] print "Dist: " + str(dist) if dist < restaurant.max_radius: print restaurant return (True, restaurant) else: #print "getting false" return (False, "")
def test_directions(self): """Test googlemaps directions()""" gmaps = GoogleMaps(GMAPS_API_KEY) results = gmaps.directions('Constitution Ave NW & 10th St NW, Washington, DC', 'Independence and 6th SW, Washington, DC 20024, USA') self.assertEqual(results['Status']['code'], googlemaps.STATUS_OK) self.assert_(results['Directions']['Duration']['seconds'] in range(100, 130)) self.assert_(results['Directions']['Distance']['meters'] in range(1000, 1050)) routes = results['Directions']['Routes'] self.assert_(len(routes) >= 1) self.assertEqual(routes[0]['Duration'], results['Directions']['Duration']) self.assertEqual(routes[0]['Distance'], results['Directions']['Distance']) self.assert_(routes[0]['Steps'][0]['descriptionHtml'].find('Constitution Ave') >= 0) self.assert_(routes[0]['Steps'][1]['descriptionHtml'].find('7th St') >= 0) self.assert_(routes[0]['Steps'][2]['descriptionHtml'].find('Independence Ave') >= 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)
def findDistances(currentDirectory): gmaps = GoogleMaps('AIzaSyBeqGD2H871THYBWdlep9eY_jo9EU8dwGI') statesTsv = open(currentDirectory + '/states.tsv', 'r') states = [] # Get everything and populate the array with statesTsv as f: for line in f.readlines()[1:]: states.append(line.rstrip('\n').split('\t')) # Let's check that everything is ok for state in states: for i,key in enumerate(state): print i," - ",key # Let's keep going... # Open a new file to store everytthing statesDistancesTsv = open(currentDirectory + '/stateDistances.tsv', 'w') statesDistancesTsv.write("ids states time distance\n") # Find all the combinations for each state for index,stateCombination in enumerate(itertools.combinations(states, 2)): #For each combination, get their LAT/LONG and Query GOogle Maps on the distnace/time for that latLong1 = stateCombination[0][3]+ ", "+ stateCombination[0][4] latLong2 = stateCombination[1][3]+ ", "+ stateCombination[1][4] print latLong1 # Let's talk to GMaps dirs = gmaps.directions(latLong1, latLong2) time = dirs['Directions']['Duration']['seconds'] dist = dirs['Directions']['Distance']['meters'] print "From ",stateCombination[0][1], " to ", stateCombination[1][1], " -- ",((float(time)/60.0)/60.0)," hours / ",float(dist)/1000," km" # For every combination, populate a row in a file buildString = stateCombination[0][0] + ","+stateCombination[1][0] + "\t" buildString += stateCombination[0][1] + ","+stateCombination[1][1] + "\t" buildString += str(time) + "\t" buildString += str(dist) + "\t" buildString += "\n" print buildString statesDistancesTsv.write(buildString) statesDistancesTsv.close() print "findDistances - Done"
def verify_address(address_string): api_key = settings.GOOGLE_MAPS geo = GoogleMaps(api_key) components = address_string.split(" ") start = "902 Sedgefield Street, Durham, NC" try: directions = geo.directions(address_string, start) except: error = "Please enter a valid address." return (False, error) split = str(address_string).split(",") addr = split[0] city = split[1] state = split[2] return (True, addr, city, state)
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)
def test_directions(self): """Test googlemaps directions()""" gmaps = GoogleMaps(GMAPS_API_KEY) results = gmaps.directions( 'Constitution Ave NW & 10th St NW, Washington, DC', 'Independence and 6th SW, Washington, DC 20024, USA') self.assertEqual(results['Status']['code'], googlemaps.STATUS_OK) self.assert_( results['Directions']['Duration']['seconds'] in range(100, 130)) self.assert_( results['Directions']['Distance']['meters'] in range(1000, 1050)) routes = results['Directions']['Routes'] self.assert_(len(routes) >= 1) self.assertEqual(routes[0]['Duration'], results['Directions']['Duration']) self.assertEqual(routes[0]['Distance'], results['Directions']['Distance']) self.assert_(routes[0]['Steps'][0]['descriptionHtml'].find( 'Constitution Ave') >= 0) self.assert_( routes[0]['Steps'][1]['descriptionHtml'].find('7th St') >= 0) self.assert_(routes[0]['Steps'][2]['descriptionHtml'].find( 'Independence Ave') >= 0)
from googlemaps import GoogleMaps gmaps = GoogleMaps("AIzaSyCRDgKn8OlRrLCaiSKkrNjNPKCuqnsUa4o") start = 'Constitution Ave NW & 10th St NW, Washington, DC' end = 'Independence and 6th SW, Washington, DC 20024, USA' dirs = gmaps.directions(start, end) time = dirs['Directions']['Duration']['seconds'] print time
def dist_calc(from_add, to_add): my_map = GoogleMaps("") direct = my_map.directions(from_add, to_add) dist_meter = direct['Directions']['Distance']['meters'] return dist_meter
businesslist = list() print 'num business in this contect', ' ', len(js['businesses']) for business in js['businesses']: if business.get('gmaptime') is not None: businesslist.append(business) continue destlat = float(str(business['location']['coordinate']['latitude'])) destlong = float(str(business['location']['coordinate']['longitude'])) dest = gmap.latlng_to_address(destlat, destlong) originlat = float(context.attribute['lat']) originlong = float(context.attribute['long']) orig = gmap.latlng_to_address(originlat, originlong) directions = None try: directions = gmap.directions(orig, dest) except: print 'problem with ', ' ', orig, ' ', dest continue if directions is None: continue meters = directions['Directions']['Distance']['meters'] timesec = directions['Directions']['Duration']['seconds'] business['gmapdistance'] = meters business['gmaptime'] = timesec if timesec is not None: businesslist.append(business) time.sleep(3) sortedlist = sorted(businesslist, key=lambda busi: busi['gmaptime']) fh = open(
#Python Get Directions Script from googlemaps import GoogleMaps #create googlemaps object mapService = GoogleMaps() #Get Directions from googlemaps directions = mapService.directions('texarkana','atlanta') #print each step in directions to console for step in directions['Directions']['Routes'][0]['Steps']: print step['descriptionHtml']
del all_data[0] print all_data gmaps = GoogleMaps('gmaps api') i1 = 0 for i in all_data: row = [] i1 += 1 if i1 > 78: for j in all_data: if i == j: distance = 0 else: c1 = float(i[1]),float(i[2]) c2 = float(j[1]),float(j[2]) dirs = gmaps.directions(c1,c2) if not dirs: time.sleep(10) dirs = gmaps.directions(c1,c2) distance = float(dirs['Directions']['Distance']['meters']) distance = float(distance/1000) d1 = distance_points(float(dirs['Directions']['Routes'][0]['Steps'][0]['Point']['coordinates'][1]),float(dirs['Directions']['Routes'][0]['Steps'][0]['Point']['coordinates'][0]),float(i[1]),float(i[2])) d2 = distance_points(float(dirs['Directions']['Routes'][0]['End']['coordinates'][1]),float(dirs['Directions']['Routes'][0]['End']['coordinates'][0]),float(j[1]),float(j[2])) distance = distance + d1 + d2 print i,j else: distance = float(dirs['Directions']['Distance']['meters']) distance = float(distance/1000) d1 = distance_points(float(dirs['Directions']['Routes'][0]['Steps'][0]['Point']['coordinates'][1]),float(dirs['Directions']['Routes'][0]['Steps'][0]['Point']['coordinates'][0]),float(i[1]),float(i[2])) d2 = distance_points(float(dirs['Directions']['Routes'][0]['End']['coordinates'][1]),float(dirs['Directions']['Routes'][0]['End']['coordinates'][0]),float(j[1]),float(j[2])) distance = distance + d1 + d2
self.fed = [] def handle_data(self,d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLstripper() s.fed(html) return s.getdata() #create Google map object mapService = GoogleMaps() #mapservice will help in accessing function of GoogleMap Class #get direction from Google directions = mapService.directions(argv[1], argv[2]) #using GoogleMap Method i.e Direction and passing argument #Print each step in direction to Console with open('C:/Users/Supriya/Desktop/directions.txt','w') as f: for steps in directions['Directions']['Routes'][0] ['Steps']: f.write(print strip_tags(step['descriptionHtml'] + '\r\n'))
print "1. Pokaz trase" print "2. Pokaz w poblizu..." print "3. Pokaz trase do sprecyzowanego celu." wybor = input() cel = "" if wybor == 1: try: address1 = raw_input('Podaj nazwe miejscowosci startowej: ') address2 = raw_input('Podaj nazwe miejscowosci koncowej: ') if address1 == "" or address2 == "": print "" print "Prosze podac poprawne nazwy miejscowosci" else: print "" check = "" directions = gmaps.directions(address1,address2) print "Dystans: ", print float(directions['Directions']['Distance']['meters'])/1000, 'kilometrow' print "" print "Trasa: " for steps in directions['Directions']['Routes'][0]['Steps']: check = steps['descriptionHtml'] check = remove_html_tags(check) 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 == "":
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?
del all_data[0] print all_data gmaps = GoogleMaps('gmaps api') i1 = 0 for i in all_data: row = [] i1 += 1 if i1 > 78: for j in all_data: if i == j: distance = 0 else: c1 = float(i[1]), float(i[2]) c2 = float(j[1]), float(j[2]) dirs = gmaps.directions(c1, c2) if not dirs: time.sleep(10) dirs = gmaps.directions(c1, c2) distance = float(dirs['Directions']['Distance']['meters']) distance = float(distance / 1000) d1 = distance_points( float(dirs['Directions']['Routes'][0]['Steps'][0] ['Point']['coordinates'][1]), float(dirs['Directions']['Routes'][0]['Steps'][0] ['Point']['coordinates'][0]), float(i[1]), float(i[2])) d2 = distance_points( float(dirs['Directions']['Routes'][0]['End'] ['coordinates'][1]), float(dirs['Directions']['Routes'][0]['End']
def travelTime(start, dest): #return the travel time in seconds gmaps = GoogleMaps() directions = gmaps.directions(start, dest) time = directions['Directions']['Duration']['seconds'] return time
#!/usr/bin/python from googlemaps import GoogleMaps mapService = GoogleMaps() directions1 = mapService.directions('1940 Cappelletti Ct, Mountain View, CA','Verde Tea Cafe, Villa Street, Mountain View, CA') dist_meters = directions1['Directions']['Distance']['meters'] dist_miles = float(dist_meters / (1609.34)) dist_miles *= 100 dist_miles = int(dist_miles / 1) dist_miles = float(dist_miles) / 100 print "meters", dist_meters print "miles", dist_miles for step in directions1['Directions']['Routes'][0]['Steps']: print step['descriptionHtml']
def order_management(request): context = RequestContext(request) # Get the user profile of the session user = request.user # Still need to make sure that the current user is staff if user.is_staff: # Get today's date today = datetime.date.today()# + datetime.timedelta(days=1) # Current week will be this week unless it is Friday, Saturday, or Sunday current_week = datetime.date.today().isocalendar()[1] mon_date = today - datetime.timedelta(days=today.weekday()) if datetime.date.today().isocalendar()[2] == 5 or datetime.date.today().isocalendar()[2] == 6 or datetime.date.today().isocalendar()[2] == 7: current_week = datetime.date.today().isocalendar()[1] + 1 mon_date = today + datetime.timedelta(days=-today.weekday(), weeks=1) # List of all dates dates = [] # Place dates after monday into dates for i in range(0,7): dates.append(mon_date + datetime.timedelta(days=i)) # Initialize a list of all orders orders = [] # Initialize a directory of lat, lng tuples lat_lngs = [] # Initialize a list of tuples (time, location, distance, estimated delivery time, assigned) table_info = [] print today # Place all orders from today into that list for order in Order.objects.all(): if order.entry.date == today: orders.append(order) address = order.user_profile.address city = order.user_profile.city state = order.user_profile.state addr_string = str(address) + " " + str(city) + " " + str(state) sleep(.1) api_key = "AIzaSyAUYyU_aUoW5iu_pZZ30U0V_bfdPHQMBQM" gmaps = GoogleMaps(api_key) geo = gmaps.directions(addr_string, addr_string) route = geo['Directions']['Routes'][0] lat, lng = route['Steps'][0]['Point']['coordinates'][1], route['Steps'][0]['Point']['coordinates'][0] tupe = (lat, lng) lat_lngs.append(tupe) restaurant_addr = str(order.restaurant.address1) + " " + str(order.restaurant.city) + " " + str(order.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) driver = "NO DRIVER AT THIS HOUR" assigned = False for do in DispatchOrder.objects.all(): if do.order == order: assigned = True if assigned == False: assign_order(order) for do in DispatchOrder.objects.all(): if do.order == order: driver = str(do.dispatch.driver.user.first_name)+str(do.dispatch.driver.user.last_name) tupe_to_add = (order.entry.start_time, address, in_miles_reformatted, time_reformatted, driver) table_info.append(tupe_to_add) gmap_code = generate_gmap_code(lat_lngs) return render_to_response("order_management.html", {'today':today, 'lat_lngs':lat_lngs, 'gmap_code':gmap_code, 'table_info':table_info}, context) return HttpResponse("No Permission")
G_GEO_UNAVAILABLE_ADDRESS : 'G_GEO_UNAVAILABLE_ADDRESS', G_GEO_BAD_KEY : 'G_GEO_BAD_KEY', G_GEO_TOO_MANY_QUERIES : 'G_GEO_TOO_MANY_QUERIES', } def __init__(self, status, url+None, response=None): Exception.__init__(self, status) self.status = status self.response = response self.url = url def __str__(self): if self.status in self.__STATUS_MESSAGES: if self.response is not None and 'responseDetails' in self.response: retrival = 'Error %d: %s' %(self.status, self.response['responseDetails']) else: retrival = 'Error %d: %s' % (self.status, status._STATUS_MESSAGES[self.status]) else: retrival = str(self.status) return retrival def __unicode__(self): return unicode(self.__str__()) mapService = GoogleMaps() #create GoogleMaps objects directions = mapService.directions(argv[1], argv[2]) #get directions from google for step in directions['Directions']['Routes'][0]['Steps']: #print each step in directions to console print strip_tags(step['descriptionHtml'])
print 'That is not an approved means... we will assume that you are driving yourself.' #collecting waypoint of user waypoint = [] sys.stdout.write("Would you like to use a waypoint? y/n \n") if raw_input().lower() == 'y': sys.stdout.write("Enter the place through which you would like to travel... \n") waypoint.append(raw_input().lower()) else: waypoint.append('') try: #making googlemaps directions request and finding the list of possible legs of travel primRoute = gmaps.directions(start, end, mode, waypoint) route = primRoute['routes'][0] legs = route['legs'] #some encouraging device print "\n \n***************************************************************************************************************" print "Hurry... we are routing you from " +start+ " to " +end+ ". Good luck!" #dealing with possible multiple legs due to utilization of a waypoint for trip in legs: #print primRoute['routes'][end_location] #printing time and distance of route routeTime = trip['duration']['value'] / 60 routeDist = trip['distance']['value'] * 0.000621371 print "\n\nThis route will take " +str(routeTime)+ " minutes to travel " +str(routeDist)+ " miles at legal speeds... think you can do better?" print "***************************************************************************************************************"
__author__ = 'lenny' """ I made this file so I can sample one piece of code at a time Jesse Fitzjarrell 6-29-15 """ #import statements from googlemaps import GoogleMaps #create Googlemaps object mapservice = GoogleMaps() #get directions from google directions = mapservice.directions("Portland", "Bend") #print each step in directions to console for step in directions['directions']["routes"][0]['steps']: print step['descriptionHtml']
miles = cursor.fetchone() trip_hash = hash_visits(day) if not miles or trip_hash != miles['hash']: # regenerate the distances gmaps = GoogleMaps(GDATA_API_KEY) cursor.execute("SELECT * FROM visits v, destinations d WHERE v.day = %s AND v.dest_id = d.id ORDER BY v.time ASC", [day]) meters = 0 trip_hash = 0 start = None miles = {'day':day} for visit in cursor.fetchall(): trip_hash = crc32(visit['address'], trip_hash) if not start: start = visit['address'] continue directions = gmaps.directions(start, visit['address']) meters += directions['Directions']['Distance']['meters'] start = visit['address'] miles['miles'] = int(meters * (1/1609.344)) miles['hash'] = trip_hash & 0xffffffff cursor.execute("INSERT INTO miles (day, miles, hash) VALUES(%%s, %(miles)d, %(hash)d) ON DUPLICATE KEY UPDATE miles = %(miles)d, hash = %(hash)d" % miles, [day]) else: miles['day'] = str(miles['day']) print "Content-type: application/json\r\n" print json.dumps(miles) elif args[0] == 'report.txt': print "Content-type: text/plain\r\n" #print "<title> MT Milage Report </title>" cursor.execute("SELECT * FROM miles m ORDER BY m.day ASC") stats = {'total':0, 'week':0}