Exemplo n.º 1
0
def find_traffic(hours, minutes):
    addresses = []
    gmaps = Client('AIzaSyCaQlauoQ1njrABzhVCliY49DaByZNYkTY')
    cassie_work = '3237 S 16th St, Milwaukee, WI 53215'
    joey_work = '1550 Innovation Way, Hartford, WI 53027'
    with open('address.txt') as f:
        addresses = f.readlines()
    file = open('times.csv', 'a')
    day = datetime.datetime.today().weekday()
    for addr_newline in addresses:
        addr = addr_newline.rstrip()
        directions_cassie = None
        directions_joey = None
        if (hours < 8):
            directions_cassie = gmaps.directions(addr, cassie_work)
            directions_joey = gmaps.directions(addr, joey_work)
        else:
            directions_cassie = gmaps.directions(cassie_work, addr)
            directions_joey = gmaps.directions(joey_work, addr)
        file.write(
            str(addr) + ',' + format_time(hours, minutes) + ',Cassie,' +
            str(directions_cassie[0]['legs'][0]['duration']['value']) +
            ',Joey,' +
            str(directions_joey[0]['legs'][0]['duration']['value']) + ',' +
            str(day) + '\n')
    file.close()
Exemplo n.º 2
0
def getDirections(start = "Sinclair Secondary School, Whitby, Ontario, Canada", end = "University of Windsor, Windsor, Ontario, Canada"):
    gmaps = Client(key = 'AIzaSyDYYj3lEniXBaV0wQCO4tnkkXl_OnxrdE0')
    dirs = gmaps.directions(start, end, units = 'metric', mode = "driving")
    #print (dirs)
    directions = []
    distance = []
    for step in dirs:
        if type(step) is dict:
            for i in step:
                if type(step[i] is list):
                    try:
                        for stepNumber in step[i]:
                            if (type(stepNumber) is dict):
                                for key in stepNumber:
                                    if key == "steps":
                                        for stepInstruction in stepNumber["steps"]:
                                            directions.append(stepInstruction.get("html_instructions"))
                                            distance.append(stepInstruction.get("distance").get("text"))
                    except: Exception

    for i in range(0, len(directions)):
        directions[i] = directions[i].replace("<b>", "")
        directions[i] = directions[i].replace("</b>", "")
        directions[i] = directions[i].replace('<div style=\"font-size:0.9em">', " [")
        directions[i] = directions[i].replace("</div>", "] ")
    return directions, distance
Exemplo n.º 3
0
def gmaps_parser(start_point="Feuerbergstrasse 6, Hamburg",
                 end_point="Bundesstrasse 53, Hamburg",
                 mode="bicycling"):
    """
    Obtain the track using the google maps api
    """
    from googlemaps import Client
    api_key = os.environ['MAPS_API_KEY']
    gmaps = Client(api_key)
    directions = gmaps.directions(start_point, end_point, mode=mode)

    lat_bike = np.array([
        step['start_location']['lat']
        for step in directions[0]['legs'][0]['steps']
    ])
    lon_bike = np.array([
        step['start_location']['lng']
        for step in directions[0]['legs'][0]['steps']
    ])
    time = np.array([
        step['duration']['value'] for step in directions[0]['legs'][0]['steps']
    ])
    dtime_bike = np.cumsum(pd.to_timedelta(time, unit='s'))

    return lon_bike, lat_bike, dtime_bike
Exemplo n.º 4
0
def get_transit_times(origin, destination):
    key = application.config['GOOGLE_MAPS']
    c = Client(key)
    d = c.directions(origin, destination, mode='transit', alternatives=True)

    results = set()
    for route in d:
        duration = route['legs'][0]['duration']['text']
        steps = route['legs'][0]['steps']
        transit_details = [x for x in steps if x.get('travel_mode') == 'TRANSIT'][0]['transit_details']
        depart_stop = transit_details['departure_stop']['name']
        depart_stop = depart_stop.replace('Subway', '')
        depart_stop = depart_stop.replace('Station', '')
        depart_stop = depart_stop.replace('Atlantic Avenue', '')
        line = transit_details['line']['short_name']
        try:
            icon = transit_details['line']['icon']
        except KeyError:
            icon = transit_details['line']['vehicle']['icon']

        status, text = morning.get_line_status(line)
        icon_html = '<img src="{}">'.format(icon)
        # results.add((line, depart_stop, duration, icon, status, text))
        results.add((icon_html, depart_stop, duration, status, text))
    return sorted(list(results), key=lambda x: x[2])
class Maps():
	def __init__(self,key):
		self.key=key
		self.con = Client(key=self.key)
	def getDirections(self,origin,destination,mode='walking'):
		r,a=self.con.directions(origin,destination,mode=mode)[0]['legs'][0]['steps'],[]
		for i in r:
			a.append(i['html_instructions'])
		return a
	def textToLatLng(self,text):
		r=self.con.geocode(text,language='ES-MX')[0]['geometry']['location']
		return '%s,%s'%(r['lat'],r['lng'])
	def getReferenceOnLocation(self,latLngAsString):
		lat,lng=latLngAsString.split(',')
		nearbyS='$MAPS_API?key=%s&location=%s&rankby=distance'%(self.key,latLngAsString)
		return json.loads(requests.get(nearbyS).text)['results'][0]['name']

	def getKeyWords(self,string,start='<b>',end='</b>'): 
		words=[]
		for i in (lambda x:(i for i in xrange(0,x.count(start))))(string):
			string=string[string.find(start)+3:]
			words.append(string[:string.find(end)])
		return words
	def getRouteLine(self,line,route=None, stop=None):
		k = self.getKeyWords(line)
		if route and stop: 
			return 'Continua hasta %s y abordas la ruta %s en la %s '%(k[0], route, stop)
		elif stop: 
			return 'Desciende en la %s'%stop
		else:		
			if len(k)>2:
				return 'Voltea hacia el %s, camina desde %s hacia %s '%(k[0],k[1],k[2])
			else:
				return 'Dirigete hacia %s '%k[0]
Exemplo n.º 6
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'])
Exemplo n.º 7
0
def directions_result(request):
    if 'origin' in request.POST:
        origin = request.POST['origin']
    if 'destination' in request.POST:
        destination = request.POST['destination']
    if 'waypoints' in request.POST:
        waypoints = request.POST['waypoints']
    if 'alternatives' in request.POST:
        alternatives = request.POST['alternatives']
    else:
        alternatives = False

    print 'alternatives -> ', alternatives

    if origin and destination:
        c = Client(api_key)
        dirs = c.directions(
            origin=origin,
            destination=destination,
            alternatives=alternatives,
            waypoints=waypoints)
    else:
        dirs = ''

    pprint(len(dirs))
    return render(request, 'directions_result.html', {
                  'directions': dirs
                  })
Exemplo n.º 8
0
def generationParcours(longitudeDepart, latitudeDepart, longitudeArrivee, latitudeArrivee, api_key, blnSavetoCSV):
    #Output panda dataframe: #1: lng | #2: lat | #3: distance | #4: duration | #5: vitesse moyenne
    # Liste de listes. Pour chaque liste, 1er élément = latitude, 2e = longitude, 3e = vitesse max    
    # route = [[latitudeDepart, longitudeDepart, 90],[65.000,45.000,130],[latitudeArrivee, longitudeArrivee, 50]]
    routemode='driving'; routealternatives=False; routelanguage='Fr'
    googlemap = Client(api_key)
    parcours = googlemap.directions((latitudeDepart, longitudeDepart), (latitudeArrivee, longitudeArrivee), mode=routemode, alternatives=routealternatives, language=routelanguage)
    if len(parcours) > 0:
        #ErreurParcours = str(parcours[0]['summary'])
        etapes = parcours[0]['legs'][0]['steps']
        ParcoursEtapes=[]           
        for numetape in range(0, len(etapes)):
            ParcoursEtape= []
            etape = etapes[numetape]
            #print numetape, etape['start_location']['lat'], etape['start_location']['lng'], etape['end_location']['lat'], etape['end_location']['lng'], etape['distance']['value'], etape['duration']['value']
            if etape['duration']['value'] != 0:
                vitmoyms = float(etape['distance']['value'] / etape['duration']['value']) # metres par seconde
                vitmoykmh = float(3.6*vitmoyms) # kilomètre par heure
            #print numetape, vitmoyms, vitmoykmh
            ParcoursEtape.append(etape['start_location']['lat'])
            ParcoursEtape.append(etape['start_location']['lng'])
            ParcoursEtape.append(etape['distance']['value']) # eb mètres
            ParcoursEtape.append(etape['duration']['value']) # en secondes
            ParcoursEtape.append(vitmoykmh)
            ParcoursEtapes.append(ParcoursEtape)
        if(blnSavetoCSV == True):
            pd.DataFrame(ParcoursEtapes, columns=('lat', 'lng', 'distance', 'duration', 'vit.moy')).to_csv("generationParcours.csv", sep='\t', encoding='utf-8')
        return pd.DataFrame(ParcoursEtapes, columns=('lat', 'lng', 'distance', 'duration', 'vit.moy') )
    else: return False
def createRoutewithwaypoints(client, dangerpoint, waypoints, aclocations, sp, ep):
    #print("WE ARE CURRENTLY ENTERING CREATEROUTEWWAYP")
    k = 25 # in meters
    dirs = []  
    pathlist = []
    waypoints_inner = []
    waypointslist = []
    dirs.append((1,1))
    dirs.append((1,-1))
    dirs.append((-1,1))
    dirs.append((1,-1))
    for dir in dirs:
        #print("This is the dangerpoint")
        #print(dangerpoint)        
        adj_point = getdistfm(dangerpoint[0],dangerpoint[1],k,dir)
        waypoints_inner = waypoints + [adj_point]
        waypointslist.append(waypoints_inner);
        #print("This is the waypoints")
        #print(waypoints_inner)
        directionsObject = client.directions(origin=sp, destination=ep, mode='walking', waypoints=waypoints_inner, alternatives = True)
        if(len(directionsObject) >= 1):           
           pathlist.append(decode(directionsObject[0]['overview_polyline']['points']))
           #print("The pathlist is -----------------------------------------------------------------------------------------> \n")
           #print(pathlist)
        else:
            print("WE ARE GETTING 000000! ---------------------------------------------------------------------------------->\n")

    newpath, wp = choose_best_path(pathlist,dangerpoint,waypointslist)
    #print("This is NEW PATH -----------------------------------------------************************************************---------------->")
    #print(newpath)
    return createRoute(client, sp, ep, newpath, wp , aclocations)
Exemplo n.º 10
0
	def google_directions( self ):

		# initalize a googlemaps object
		googmap = Client(google_api_key)

		print '\n\n'

		# call the .directions() funciton on Client, save in a list
		# See if we should use waypoint optimixzing?

		list_of_maps = [ googmap.directions( pitstop[0], pitstop[1] ) for pitstop in self.trip ]

		print "\n\n\n******************************\n\n\n"


		# print directions['Directions']['Distance']["meters"]
		# for thing in list_of_maps:
		# 	print "\n\n\n\n"
		# 	print thing

		total_distance = 0
		for count, gmap in enumerate(list_of_maps): 
			# Iterate through the list
			if gmap[0]['legs'][0]['distance']['text'][-2:] == "ft":
				total_distance = 0.10
			else:
				
				total_distance += round(   float(gmap[0]['legs'][0]['distance']['text'].replace( ' mi', ''))  ,  2 )
			steps =  gmap[0]['legs'][0]['steps'] 
			display = []
			turn = 0
			leg = 0
			for step in steps:
				to_go = step['distance']['text']
				# total_distance += int(to_go)
				turn = turn + 1
				words = step['html_instructions']
				words = words.replace( '<b>' , ' ')
				words = words.replace( '</b>' , ' ')
				words = words.replace( '<div style="font-size:0.9em">' , '')
				words = words.replace( '</div>' , ' ' )
				display.append([turn,  to_go, words])
			# print display

			tabs = ["Turn", "Distance", "Instruction"]

			tab = tabulate(display, headers = tabs, tablefmt = "simple")
			print "LEG # " , count , "\n"
			print tab
			final = []
			final.append(tab)
			# print tab
		# return directions
		print "\n\nDistance: ", total_distance
		print "\n\n\n******************************\nEnd of google_directions().\n\n"
		# return final
		return total_distance
def getDirections(current_location, transportation_mode, shop_preference):
  """Return a list of directions that the user should take to
    get from their current location to the ClickTime office while
    stopping for donuts and coffee along the way."""

  # Init API Clients
  google_places = GooglePlaces(GOOGLE_API_KEY)
  google_maps = Client(key=GOOGLE_API_KEY)

  # Get the coordinates of the nearest donut shop to the ClickTime office.
  query_result = google_places.nearby_search(
      lat_lng=CLICKTIME_LOCATION,
      name='donut',
      types='food',
      rankby=shop_preference)

  donut_shop_name = query_result.places[0].name
  donut_shop_location = query_result.places[0].geo_location

  # Get directions from current location to donut shop.
  # Had issues with waypoints so I broke the route into
  # two different pieces.
  directions_api_result = google_maps.directions(
      current_location,
      donut_shop_location, 
      mode=transportation_mode)

  directions = []
  for step in directions_api_result[0]['legs'][0]['steps']:
    directions.append(step['html_instructions'])
  directions.append('<font color="green">Arrived at ' 
      + donut_shop_name + '!</font>')

  # Get directions from the donut shop to the ClickTime office.
  directions_api_result = google_maps.directions(
      donut_shop_location,
      CLICKTIME_LOCATION, mode=transportation_mode)

  for step in directions_api_result[0]['legs'][0]['steps']:
    directions.append(step['html_instructions'])  
  directions.append('<font color="green">Arrived at ClickTime!</font>')
  
  return directions
Exemplo n.º 12
0
def Directions(start, end):
	try:
		mapService = Client('AIzaSyDddi5KttOYGnCalNu8M54DUsc1kCKVCrA')

		directions = mapService.directions(start, end)
		x=[]
		for value in directions[0]['legs'][0]['steps']:
			x.append(strip_tags(value['html_instructions']))
		return x	

	except:
		return 'Error'
Exemplo n.º 13
0
def get_directions(start,end):
	
	mapService= Client('AIzaSyDpo931DWDqeeHXeaNAvydQH4isieEHc9s')

	directions=mapService.directions(start,end)

	#print each step in directions to console
	#print json.dumps(directions,indent=4,sort_keys=True)

	for step in directions[0]['legs'][0]['steps']:
    		print step['html_instructions']
    		print 
Exemplo n.º 14
0
def createRoute(startpoint, endpoint, aclocations):
    client = \
        googlemaps.Client(key='AIzaSyDAszXFz4LjQQ6Itr4o7O90RUJhUhhnXXI')
    finalRoute = []
    directionsObject = client.directions(origin=startpoint,
            destination=endpoint, mode='walking')
    mainPath = decode(directionsObject[0]['overview_polyline']['points'])
    i = 0
    for point in mainPath:
        i = i+1
        if checkIfSafe(point, aclocations) == True:
            finalRoute.append(point)
            #print finalRoute
        else:
            '''
            print(aclocations)
            print("\n")
            print mainPath
            print("We have reached to point" + str(point))
            print("The point before this is: " + str(mainPath[i-2]))
            print("The point after this is: " + str(mainPath[i]))
            '''
            tup1 = []
            tup1.append(mainPath[i-2][1])
            tup1.append(mainPath[i-2][0])
            tup2 = []
            tup2.append(mainPath[i][1])
            tup2.append(mainPath[i][0])

            #print mainPath[i-1]
            #print mainPath[i+1]
            #finalRoute.append(createRoute(mainPath[point-1], mainPath[point+1], aclocations))
            #print("The point in the mainpoints that has an issue is: " + str(point))
            #finalRoute.append(createRoute(mainPath[i-2], mainPath[i], aclocations))
            directionsObject2 = client.directions(origin = tup1, destination = tup2, mode = 'walking', alternatives = True)
            routeAgain = decode(directionsObject2[0]['overview_polyline']['points'])
            for point in routeAgain:
                finalRoute.append(point)
    return finalRoute
Exemplo n.º 15
0
def get_driving_directions(start_address, end_address, api_key):
    '''
	Get driving direction steps from start and destination address
	'''
    result = []
    gmaps = Client(api_key)
    directions = gmaps.directions(start_address, end_address)
    for step in directions[0]['legs'][0]['steps']:
        start = step['start_location']
        end = step['end_location']
        direction = [(start['lng'], start['lat']), (end['lng'], end['lat'])]
        result.append(direction)

    return result
def main():
    startAddress = sys.argv[1]
    endAddress = sys.argv[2]
    aclocations = []
    aclocations = readInJSON()
    aclocations = aclocations + [[40.11351,-88.22807]] + [[40.11449,-88.2243]];

    client = \
        googlemaps.Client(key='AIzaSyDAszXFz4LjQQ6Itr4o7O90RUJhUhhnXXI')
    finalRoute = []
    waypoints = []
    directionsObject = client.directions(origin=startAddress,
            destination=endAddress, mode='walking', alternatives = True)
    mainPath = decode(directionsObject[0]['overview_polyline']['points'])
    theRoute = createRoute(client, startAddress, endAddress, mainPath, [], aclocations)
    print (theRoute)                                 
Exemplo n.º 17
0
def main():
    # Initialize the API object
    gmaps = Client(api_key_maps)
    route_map = Client(api_key_route)

    # origin = raw_input('Where are you starting? (please enter a valid address) ')
    # dest = raw_input('Where are you going? (please enter a valid address) ')
    origin = 'Ogunquit, ME'
    dest = 'Coral Gables, FL'

    lat0, lng0 = gmaps.geocode(origin)[0]['geometry']['location'].values()
    print 'start: ', lat0, lng0

    lat1, lng1 = gmaps.geocode(dest)[0]['geometry']['location'].values()
    print 'end: ', lat1, lng1

    routes = route_map.directions(origin, dest)

    lats = []
    longs = []
    times = []

    for i, step in enumerate(routes[0]['legs'][0]['steps']):
        lats.append(step['start_location']['lat'])
        longs.append(step['start_location']['lng'])
        if i == len(routes[0]['legs'][0]['steps']) - 1:
            lats.append(step['end_location']['lat'])
            longs.append(step['end_location']['lng'])

        times.append(step['duration']['value'])

    new_times = [sum(times[:i]) for i in range(len(times) + 1)]
    travel_route = zip(lats, longs)
    markers = fifteen_mile_markers(zip(lats, longs))

    # Dan - Test
    # print markers
    print[i[2] for i in segment_times(travel_route, new_times, markers)]

    gmap_plt = gmplot.GoogleMapPlotter((lat0 + lat1) / 2.0,
                                       (lng0 + lng1) / 2.0, 16)

    gmap_plt.plot([i[0] for i in markers], [i[0] for i in markers], 'r')
    gmap_plt.plot(lats, longs)
    gmap_plt.plot([mark[0] for mark in markers], [mark[1] for mark in markers])
    gmap_plt.draw("mymap.html")
    return
Exemplo n.º 18
0
def generationParcours(longitudeDepart, latitudeDepart, longitudeArrivee,
                       latitudeArrivee, api_key, blnSavetoCSV):
    #Output panda dataframe: #1: lng | #2: lat | #3: distance | #4: duration | #5: vitesse moyenne
    # Liste de listes. Pour chaque liste, 1er élément = latitude, 2e = longitude, 3e = vitesse max
    # route = [[latitudeDepart, longitudeDepart, 90],[65.000,45.000,130],[latitudeArrivee, longitudeArrivee, 50]]
    routemode = 'driving'
    routealternatives = False
    routelanguage = 'Fr'
    googlemap = Client(api_key)
    parcours = googlemap.directions((latitudeDepart, longitudeDepart),
                                    (latitudeArrivee, longitudeArrivee),
                                    mode=routemode,
                                    alternatives=routealternatives,
                                    language=routelanguage)
    if len(parcours) > 0:
        #ErreurParcours = str(parcours[0]['summary'])
        etapes = parcours[0]['legs'][0]['steps']
        ParcoursEtapes = []
        for numetape in range(0, len(etapes)):
            ParcoursEtape = []
            etape = etapes[numetape]
            #print numetape, etape['start_location']['lat'], etape['start_location']['lng'], etape['end_location']['lat'], etape['end_location']['lng'], etape['distance']['value'], etape['duration']['value']
            if etape['duration']['value'] != 0:
                vitmoyms = float(
                    etape['distance']['value'] /
                    etape['duration']['value'])  # metres par seconde
                vitmoykmh = float(3.6 * vitmoyms)  # kilomètre par heure
            #print numetape, vitmoyms, vitmoykmh
            ParcoursEtape.append(etape['start_location']['lat'])
            ParcoursEtape.append(etape['start_location']['lng'])
            ParcoursEtape.append(etape['distance']['value'])  # eb mètres
            ParcoursEtape.append(etape['duration']['value'])  # en secondes
            ParcoursEtape.append(vitmoykmh)
            ParcoursEtapes.append(ParcoursEtape)
        if (blnSavetoCSV == True):
            pd.DataFrame(ParcoursEtapes,
                         columns=('lat', 'lng', 'distance', 'duration',
                                  'vit.moy')).to_csv("generationParcours.csv",
                                                     sep='\t',
                                                     encoding='utf-8')
        return pd.DataFrame(ParcoursEtapes,
                            columns=('lat', 'lng', 'distance', 'duration',
                                     'vit.moy'))
    else:
        return False
def get_direction(api_key, from_address, to_address, travelling_mode):
    """Returns all the direction informations between two points

    Arguments:
        - api_key         : (str) googlemaps API key
        - from_address    : (str) departure location
        - to_address      : (str) arrival location
        - travelling_mode : (str) conveyance

    Returns:
        - client.directions(...) : (list) information
                                          about the journey
    """
    client = Client(api_key)
    return client.directions(from_address,
                             to_address,
                             mode=travelling_mode,
                             departure_time=datetime.now())
def get_directions():
	gmaps=Client(key='AIzaSyB7hXzGzrXUuQuPReZlERvxZO9YFakIzVw')
	now = datetime.now()
	direction_result = gmaps.directions("A-10,JIIT Noida, sector-62, Noida","9, Vaibhav Khand, Indirapuram, Ghaziabad, Uttar Pradesh 201014, India",mode="transit",departure_time=now)
	##print direction_result
	distance=direction_result[0]['legs'][0]['distance']
	end_address=direction_result[0]['legs'][0]['end_address']
	travel_mode=direction_result[0]['legs'][0]['steps'][0]['travel_mode']
	instructions=direction_result[0]['legs'][0]['steps'][0]['html_instructions']
	duration=direction_result[0]['legs'][0]['steps'][0]['duration']
	print distance['text'],duration['text']
	## Directions
	num_steps=len(direction_result[0]['legs'][0]['steps'][0]['steps'])
	str1=''
	for i in range(0,num_steps):
		str1+=str(direction_result[0]['legs'][0]['steps'][0]['steps'][i]['html_instructions'])+'\n'
		#print direction_result[0]['legs'][0]['steps'][0]['steps'][i]['distance']
		#print direction_result[0]['legs'][0]['steps'][0]['steps'][i]['duration']
	return str1 
Exemplo n.º 21
0
def google_maps_request(addr, key):
    gmaps = Client(key=key)

    # Geocoding an address
    geocode_result = gmaps.geocode(addr)
    print('geocode_result={}'.format(geocode_result))

    #  Look up an address with reverse geocoding
    reverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452))
    print('reverse_geocode_result={}'.format(reverse_geocode_result))

    # Request directions via public transit
    now = datetime.now()
    directions_result = gmaps.directions(
        origin="Sydney Town Hall",
		destination="Parramatta, NSW",
		mode="transit",
		departure_time=now
	)
    print('directions_result={}'.format(directions_result))
Exemplo n.º 22
0
def get_directions(place, dest):
    gmaps = Client(key='AIzaSyB7hXzGzrXUuQuPReZlERvxZO9YFakIzVw')
    now = datetime.now()
    direction_result = gmaps.directions(place,
                                        dest,
                                        mode="transit",
                                        departure_time=now)
    ##print direction_result
    distance = direction_result[0]['legs'][0]['distance']
    end_address = direction_result[0]['legs'][0]['end_address']
    travel_mode = direction_result[0]['legs'][0]['steps'][0]['travel_mode']
    instructions = direction_result[0]['legs'][0]['steps'][0][
        'html_instructions']
    duration = direction_result[0]['legs'][0]['steps'][0]['duration']
    str1 = ''
    num_steps = len(direction_result[0]['legs'][0]['steps'][0]['steps'])
    for i in range(0, num_steps):
        str1 += str(direction_result[0]['legs'][0]['steps'][0]['steps'][i]
                    ['html_instructions']) + '\n'
    return distance['text'] + ' ' + duration['text'] + ' ' + str1
Exemplo n.º 23
0
    def __init__(self, apiKey: str):
        """
        コンストラクタ

        Parameters
        ----------
        apiKey : str
            Google Mapsクライアントに接続するAPI key

        Notes
        -----
        (32 + 31 + ... + 2 + 1)回Google Maps APIを実行して通信を行う
        """

        # 各店舗間の経路情報の行列の初期化
        self._directions = []

        # Google Mapsクライエントの初期化
        client = Client(key=apiKey)

        # Google Maps APIを用いて、各店舗間の経路情報の行列をセット
        for i in range(len(Sawayaka._ADDRESSES)):
            directions_tmp = []

            for j in range(len(Sawayaka._ADDRESSES)):
                if i < j:
                    # 上三角成分の場合は、Google Maps APIを実行して追加
                    result = client.directions(
                        origin=Sawayaka._ADDRESSES[i],
                        destination=Sawayaka._ADDRESSES[j],
                        mode="driving",
                        alternatives=False)
                    directions_tmp.append(result[0]['legs'][0])
                elif i > j:
                    # 下三角成分の場合は、上三角成分をそのままコピー
                    directions_tmp.append(self._directions[j][i])
                else:
                    # 対角成分の場合は、Noneを追加
                    directions_tmp.append(None)

            self._directions.append(directions_tmp)
Exemplo n.º 24
0
def main():
    # Initialize the API object
    gmaps = Client(api_key_maps)
    route_map = Client(api_key_route)


    # origin = raw_input('Where are you starting? (please enter a valid address) ')
    # dest = raw_input('Where are you going? (please enter a valid address) ')
    # origin = '12 emery lane 07677'
    # dest = '431 riverside drive 10027'
    origin = 'New York City'
    dest = 'Miami'
    

    lat0, lng0 = gmaps.geocode(origin)[0]['geometry']['location'].values()
    print 'start: ', lat0, lng0

    lat1, lng1 = gmaps.geocode(dest)[0]['geometry']['location'].values()
    print 'end: ', lat1, lng1

    routes = route_map.directions(origin, dest)

    lats = []
    longs = []

    for i, step in enumerate(routes[0]['legs'][0]['steps']):
        lats.append(step['start_location']['lat'])
        longs.append(step['start_location']['lng'])
        lats.append(step['end_location']['lat'])
        longs.append(step['end_location']['lng'])

    travel_route = zip(lats, longs)
    markers = fifteen_mile_markers(travel_route)

    gmap_plt = gmplot.GoogleMapPlotter((lat0 + lat1) / 2.0, (lng0 + lng1) / 2.0, 16)

    # gmap_plt.plot(lats, longs)
    gmap_plt.scatter([mark[0] for mark in markers], [mark[1] for mark in markers], 'r', marker=True)
    gmap_plt.draw("mymap.html")
    return
def main():
    sp = sys.argv[1]
    ep = sys.argv[2]
    totalCrimes = readInJSON()
    ac = []
    vt = []
    ac = totalCrimes[0]
    vt = totalCrimes[1]  
    
    #aclocations = aclocations + [[40.11351,-88.22807]] + [[40.11449,-88.2243]];
    # + [[40.1136,-88.22725]]
    #print(aclocations)
    #sp = '331 E Stoughton Stoughton Champaign IL'
    #ep = '208 N. Harvey Urbana IL 61801'
    #sp = '610 E Stoughton Champaign IL 61820'
    client = \
        googlemaps.Client(key='AIzaSyDAszXFz4LjQQ6Itr4o7O90RUJhUhhnXXI')
    finalRoute = []
    waypoints = []
    directionsObject = client.directions(origin=sp,
            destination=ep, mode='walking', alternatives = True)
    mainPath = decode(directionsObject[0]['overview_polyline']['points'])
    theRoute = createRoute(client, sp, ep, mainPath, [], ac, vt) 
    print(theRoute)                                
Exemplo n.º 26
0
 
 #helper function used in _encode_coords
def _encode_value(value):
    # Step 2 & 4
    value = ~(value << 1) if value < 0 else (value << 1)
    
    # Step 5 - 8
    chunks = _split_into_chunks(value)
    
    # Step 9-10
    return (chr(chunk + 63) for chunk in chunks)
 


#actually calling the directions method on the origin and destinatino 
directions = client.directions(origin = '201 N. Goodwin Avenue Urbana IL 61801', destination = '208 N. Harvey Urbana IL 61801', mode = "walking", alternatives = True)

#parsing the directions object (JSON) so we can return a list of lat/lon points 
point_str = (directions[0]['overview_polyline']['points'])
points = []

#function that decodes the unicode string that Google Maps returns as the encoded lat/lon route 
def decode(point_str):
    '''Decodes a polyline that has been encoded using Google's algorithm
    http://code.google.com/apis/maps/documentation/polylinealgorithm.html
    
    This is a generic method that returns a list of (latitude, longitude) 
    tuples.
    
    :param point_str: Encoded polyline string.
    :type point_str: string
Exemplo n.º 27
0
class GoogleMapsWrapper(object):
    """Class wraps the GoogleMaps API with convenient functions for our purposes.
    It is singleton because only one client is necessary globally."""
    def __init__(self):
        # could raise a ValueError/NotImplementedError if key is wrong
        self._client = Client(settings.GOOGLE_API_KEY)

    def get_address_coords(self, address):
        """Returns the coordinates for a given address.

        Could raise InvalidAddressException, MultipleResultsForAddressException
        or UnexpectedAPIResultsException."""
        res = self._client.geocode(address)
        if not res:
            raise InvalidAddressException()
        if 1 < len(res):
            raise MultipleResultsForAddressException()
        info_obj = res[0]
        try:
            return (info_obj['geometry']['location']['lng'], info_obj['geometry']['location']['lat'])
        except KeyError:
            raise UnexpectedAPIResultsException()

    def get_directions_coords(self, from_addr, to_addr):
        """Returns the list of coordinates for driving directions between two addresses."""
        res = self._client.directions(from_addr, to_addr)
        return self._decode_google_polyline(res[0]['overview_polyline']['points'])

    def _decode_google_polyline(self, points):
        """Returns a list of coordinates by decoding a Google Polyline string.

        This format is explained at:
        https://developers.google.com/maps/documentation/utilities/polylinealgorithm

        Adapted from https://gist.github.com/signed0/2031157
        """
        coord_chunks = [[]]
        for char in points:
            value = ord(char) - 63
            split_after = not (value & 0x20)
            value &= 0x1F
            coord_chunks[-1].append(value)
            if split_after:
                    coord_chunks.append([])
        del coord_chunks[-1]

        coords = []
        for coord_chunk in coord_chunks:
            coord = 0
            for i, chunk in enumerate(coord_chunk):
                coord |= chunk << (i * 5)
            if coord & 0x1:
                coord = ~coord #invert
            coord >>= 1
            coord /= 100000.0
            coords.append(coord)

        points = []
        prev_x = 0
        prev_y = 0
        for i in xrange(0, len(coords) - 1, 2):
            if 0 ==  coords[i] and 0 == coords[i + 1]:
                continue

            prev_x += coords[i + 1]
            prev_y += coords[i]
            points.append((round(prev_x, 6), round(prev_y, 6)))

        return points
Exemplo n.º 28
0
class WalkingRoute:
    SHIFT_MAX = 360  # in degrees
    SHIFT_STEP = 45  # in degrees
    SHIFT_START = 0  # in degrees

    DEFAULT_DIRECTION_MODE = "walking"
    DEFAULT_DIRECTION_AVOID = ["highways", "tolls", "ferries"]

    CAST_TO_MILES = app.config['CAST_TO_MILES']
    CAST_TO_KM = 1000  #

    CORRELATION_FACTOR = 1
    EARTH_RADIUS_KM = 6371

    CENTER = 360
    NORTH = 0
    NORTHEAST = 45
    EAST = 90
    SOUTHEAST = 135
    SOUTH = 180
    SOUTHWEST = 225
    WEST = 270
    NORTHWEST = 215

    DIRECTIONS = {
        'center': CENTER,
        'north': NORTH,
        'northeast': NORTHEAST,
        'east': EAST,
        'southeast': SOUTHEAST,
        'south': SOUTH,
        'southwest': SOUTHWEST,
        'west': WEST,
        'northwest': NORTHWEST,
    }

    DEFAULT_DIRECTION = 'center'

    def __init__(self, coordinates, distance, direction=None):
        self.coordinates = coordinates
        self.distance = distance
        self.direction = self.get_direction(direction)
        self.direction_degrees = self.DIRECTIONS.get(
            direction.lower() if direction else self.DEFAULT_DIRECTION)
        self.radius = self.distance / (2 * math.pi) * self.CORRELATION_FACTOR

        self.gmaps = Client(app.config['GOOGLE_MAPS_API_KEY'])  # geoCoding
        self.dirs = Client(app.config['GOOGLE_MAPS_API_KEY'])  # directions
        logger.debug(' Initialize request with coordinates {} '.format(
            self.coordinates))

    def get_direction(self, direction):
        direction = direction if direction else self.DEFAULT_DIRECTION
        direction_degree = self.DIRECTIONS.get(direction)
        return list(zip((direction, ), (direction_degree, )))

    @staticmethod
    def flatten(items):
        return [value for deep_list in items for value in deep_list]

    def load_point_data(self):
        coordinates = self.coordinates
        if hasattr(self, 'center_coordinates'):
            coordinates = self.center_coordinates
        points = self.__find_lap_points(coordinates)
        points_info = []
        for i, point in enumerate(points):
            if WalkingRoute.__is_last(points, point):
                points_info.append(self._compute_direction(point, points[0]))
            else:
                points_info.append(
                    self._compute_direction(point, points[i + 1]))
        flattened = WalkingRoute.flatten(points_info)
        return WalkingRouteItem(
            flattened, WalkingRoute.__compute_overall_distance(flattened),
            self.coordinates)

    def load_for_map(self):
        return ",\n".join([
            "{{lat: {lat}, lng: {lng}}}".format(lat=point.lat, lng=point.lng)
            for point in self.load_point_data().points
        ])

    @staticmethod
    def _get_way_point(coordinates, shift, radius):
        # https://www.movable-type.co.uk/scripts/latlong.html - see here for more details
        """
        Formula:
            φ2 = asin( sin φ1 ⋅ cos δ + cos φ1 ⋅ sin δ ⋅ cos θ )
            λ2 = λ1 + atan2( sin θ ⋅ sin δ ⋅ cos φ1, cos δ − sin φ1 ⋅ sin φ2 )
                where φ is latitude, λ is longitude, θ is the bearing (clockwise from north), δ is the angular distance d/R; d being the distance travelled, R the earth’s radius
        """
        radius = radius / WalkingRoute.EARTH_RADIUS_KM
        shift = math.radians(shift)

        lat = math.radians(coordinates[0])  # get lat
        lng = math.radians(coordinates[1])  # get lng

        lat_shift = math.asin(
            math.sin(lat) * math.cos(radius) +
            math.cos(lat) * math.sin(radius) * math.cos(shift))

        lng_shift = lng + math.atan2(
            math.sin(shift) * math.sin(radius) * math.cos(lat),
            math.cos(radius) - math.sin(lat) * math.sin(lat_shift))
        if not isinstance(lat_shift, float) \
                or not isinstance(lng_shift, float):
            return False

        return [math.degrees(lat_shift), math.degrees(lng_shift)]

    def __find_lap_points(self, coordinates):
        logger.debug(' Find base points for coordinates {} '.format(
            self.coordinates))
        points = []
        shift = self.SHIFT_START
        while shift <= self.SHIFT_MAX:
            new_way_point = self._get_way_point(coordinates, shift,
                                                self.radius)
            points.append(new_way_point)
            shift += self.SHIFT_STEP
        return points

    @staticmethod
    def __compute_overall_distance(points_info):
        return sum(float(point.distance)
                   for point in points_info) / WalkingRoute.CAST_TO_KM

    @deprecated('This method was deprecated')
    def __overall_to_miles(self, points):
        return WalkingRoute.__compute_overall_distance(
            points) * self.CAST_TO_MILES

    @staticmethod
    def __is_last(existing_list, current):
        return existing_list[-1] == current

    @deprecated("Use __compute_direction from child class")
    def _compute_direction(self, start, end):
        """
        Load information from Google Maps Directions for each route point
        :param start:
        :param end:
        :return:
        """
        route_info = self.dirs.directions(start,
                                          end,
                                          mode=self.DEFAULT_DIRECTION_MODE,
                                          avoid=self.DEFAULT_DIRECTION_AVOID)

        dp = Point(
            lat=start[0],
            lng=start[1],
            street=route_info[0]['legs'][0]['start_address'],
            distance=route_info[0]['legs'][0]['distance']['value'],
        )
        return [dp]

    @staticmethod
    def _go_round_points(way_points):
        points = []
        for way_point in way_points:
            for steps in way_point['legs'][0]['steps']:
                dp = Point(address=way_point['legs'][0]['start_address'],
                           **steps)
                points.append(dp)
        logger.debug(' Found waypoints: {} '.format(points))
        return points
Exemplo n.º 29
0
api_key_route = 'AIzaSyDJJGsUGU96GMLYUdeOdufkoIG-x2Soo9s'
api_key_maps = 'AIzaSyDg-yjmIEndzcGRaHxH8-Jx2UNAerk7430'
gmaps = Client(api_key_maps)
route_map = Client(api_key_route)


origin = raw_input('Where are you starting? (please enter a valid address) ')
dest = raw_input('Where are you going? (please enter a valid address) ')

lat0, lng0 = gmaps.geocode(origin)[0]['geometry']['location'].values()
print lat0, lng0

lat1, lng1 = gmaps.geocode(dest)[0]['geometry']['location'].values()
print lat1, lng1

routes = route_map.directions(origin, dest)

lats = []
longs = []

for i, step in enumerate(routes[0]['legs'][0]['steps']):
    lats.append(step['start_location']['lat'])
    longs.append(step['start_location']['lng'])
    lats.append(step['end_location']['lat'])
    longs.append(step['end_location']['lng'])

travel_route = zip(lats, longs)

gmap_plt = gmplot.GoogleMapPlotter((lat0 + lat1) / 2.0, (lng0 + lng1) / 2.0, 16)

gmap_plt.plot(lats, longs)
Exemplo n.º 30
0
# Google Maps Api testing 
from googlemaps import Client
import gmplot

api_key_route = 'AIzaSyDJJGsUGU96GMLYUdeOdufkoIG-x2Soo9s'

api_key_maps = 'AIzaSyDg-yjmIEndzcGRaHxH8-Jx2UNAerk7430'
gmaps = Client(api_key_maps)


address = '431 Riverside Drive, New York, NY 10027'
lat, lng = gmaps.geocode(address)[0]['geometry']['location'].values()
print lat, lng

route_map = Client(api_key_route)
routes = route_map.directions('330 West 72, New York 10023', '3198 Old Post Drive, Baltimore, 21208')


lats = []
longs = []

for i, step in enumerate(routes[0]['legs'][0]['steps']):
    lats.append(step['start_location']['lat'])
    longs.append(step['start_location']['lng'])
    lats.append(step['end_location']['lat'])
    longs.append(step['end_location']['lng'])

gmap_plt = gmplot.GoogleMapPlotter(lat, lng, 16)

gmap_plt.plot(lats, longs)
gmap_plt.draw("mymap.html")
Exemplo n.º 31
0
#Python Get Directions Script

#API_KEY value
API_KEY="AIzaSyDVYcV4L2bOFuiEvjgvtTWsVieX7nZfzeo"

#import statements
from googlemaps import Client

#create GoogleMaps object
mapService = Client(API_KEY)

#get directions from google
directions = mapService.directions('texarkana', 'atlanta')
for key in  directions:
    print(key)
Exemplo n.º 32
0
def main(end, qtyy, blood):
    gmaps = GoogleMaps('AIzaSyBFcX4qpaWNXjHm7FoUm7OUMV11K8-QKdY')
    d = []
    t = []
    time = []
    bldgrp = []
    bbname = []
    index = []
    i = 0
    cursor = Availability.objects.all()
    for row in cursor:

        #print ("NAME = ", row[0])
        start = row.location
        dirs = gmaps.directions(start, end)

        #print(dirs)
        dirs1 = dirs[0]
        #d.append(dirs1['legs'][0]['distance']['text'])
        t = dirs1['legs'][0]['duration']['text']
        #t1=t[0]
        #print(t)
        tmin = converttomin(t)
        if blood == "A+":
            qty = row.Apos
        if blood == "A-":
            qty = row.Aneg

        if blood == "B+":
            qty = row.Bpos
        if blood == "B-":
            qty = row.Bneg

        if blood == "AB+":
            qty = row.ABpos
        if blood == "AB-":
            qty = row.ABneg

        if blood == "O+":
            qty = row.Opos
        if blood == "O-":
            qty = row.Oneg
        name = row.location
        time.append(tmin)
        bldgrp.append(qty)
        bbname.append(name)
        index.append(i)
        i += 1
    result = dict(zip(time, bldgrp))
    result1 = dict(zip(time, index))
    result3 = dict(zip(index, bbname))
    ans = OrderedDict(sorted(result.items(), key=itemgetter(0)))
    ans1 = OrderedDict(sorted(result1.items(), key=itemgetter(0)))
    #print (result)
    #print (result1)
    j = 0
    qt = 0
    for i, v in ans.items():
        if v >= int(qtyy):
            qt = v
            #print (v)
            break
        j += 1
    k = 0
    id = -1
    for i, v in ans1.items():
        if k == j:
            #print("Nearest Blood Bank is ","\n",i)
            id = v
            break
        k += 1
    for i, v in result3.items():
        if id == i:
            #print("Nearest Blood Bank is ",v)
            #print("Amount Available : ",qt)
            break
    if id == -1:
        return ("", 0)
    return (v, qt)
Exemplo n.º 33
0
def Geocode(df, combs):
    '''
        Description: Geocodes the records that were not found in
        GBAT using Google API.
        By default all the years are in the exclude list so that 
        we don't redo any years and don't pay Google twice.
    '''

    # Get the date and time for directions from the form.
    dt_formatted = datetime.strptime(dep_time.get().strip(), '%Y-%m-%d %H:%M')

    status.set("Status: began retreiving direction data.")
    google_api_key2 = ents[0][1].get()

    try:
        gmaps = Client(key=google_api_key2)
    except:
        try:
            config = RawConfigParser()
            config.read('./API_Keys.cfg')
            google_api_key = config.get('Google', 'QCEW_API_Key')
            gmaps = Client(key=google_api_key)
        except:
            messagebox.showinfo(
                "Can't Connect to Google", "Oups! Please check \
that your API key is valid, doesn't have leading/trailing spaces, and you are \
connected to internet! \nYour API key looks like vNIXE0xscrmjlyV-12Nj_BvUPaw")
            return None

    # test
    try:
        transit_result = gmaps.directions(
            "Indepenent Buget Office, New York, NY 10003",
            "309 W 84 st, new york, ny",
            mode='driving',
            departure_time=datetime.now())
        # print(geocode_result[0]['geometry']['location']['lat'],
        #      geocode_result[0]['geometry']['location']['lng'])
        print("Google Connection Test Completed successfully.")
    except:
        print("Google Connection Test Failed.")
    # print(geocode_result)
    # print("DFrame\n\n", df.head())
    # Dictionary of boros to be used in for Addresses.
    Boros = {
        1: 'Manhattan',
        2: 'Bronx',
        3: 'Brooklyn',
        4: 'Queens',
        5: 'Staten Island',
        9: 'New York'
    }

    df.fillna('')
    # trade2 is trade name when available, and legal name when not.
    for i in range(1, 3):
        if combs[9][i].get() == "" and combs[10][i].get() == "":
            df['trade2%s' % i] = ""
            #   trade
            if combs[0][i].get() != "":
                df.loc[df[combs[0][1].get()].fillna('') != '',
                       'trade2%s' % i] = df[combs[0][i].get()]
                #   legal
                if combs[1][i].get() != "":
                    df.loc[df[combs[0][i].get()].fillna('') == '',
                           'trade2%s' % i] = df[combs[1][i].get()]
                else:
                    df.loc[df[combs[0][i].get()].fillna('') == '',
                           'trade2%s' % i] = ""
            else:
                df['trade2%s' % i] = ""

            # Handle missing fields.
            if combs[2][i].get() == '' and (combs[3][i].get() == ''
                                            or combs[4][i].get() == ''):
                messagebox.showinfo(
                    "No Address!",
                    "Either 'Street Address' or ''Street Number' and 'Street Name'' are required."
                )
                return None
            elif combs[3][i].get() != '' or combs[4][i].get() != '':
                df['Generated_streetaddress%s' %
                   i] = df[combs[3][i].get()] + " " + df[combs[4][i].get()]
            else:
                df['Generated_streetaddress%s' % i] = df[combs[2][i].get()]

            if combs[7][i].get() == '':
                if combs[5][i].get() == '':
                    df['no_boro%s' % i] = 1
                    vals = combs[7][i]['values'] + ('no_boro%s' % i, )
                    combs[7][i]['values'] = sorted(vals, key=keyfunction)
                    choose_default(7, i, vals, 'no_boro%s' % i)
                    df['no_city%s' % i] = 'New York'
                else:
                    df['no_city%s' % i] = df[combs[5][i].get()]
                    df['no_boro%s' % i] = ''
            else:
                try:
                    to_numeric(df[combs[7][i].get()], errors='raise')
                except:
                    messagebox.showinfo(
                        "Error: Non-numeric Boro Codes!",
                        "Boro code is needs to be a number\
between 1 and 5. Either choose a different field or no field at all. \n\nChoosing no field will \
result in 'New York City' assumed for all addresses.")
                    return None
                df['no_boro%s' % i] = df[combs[7][i].get()]
                df['no_city%s' % i] = df['no_boro%s' % i].map(Boros)

            if combs[6][i].get() == '':
                df['no_zip%s' % i] = ''
                vals = combs[7][i]['values'] + ('no_zip%s' % i, )
                combs[6][i]['values'] = sorted(vals, key=keyfunction)
                choose_default(6, i, vals, 'no_zip%s' % i)
            else:
                if issubdtype(df[combs[6][i].get()].dtype, number):
                    df['no_zip%s' % i] = df[combs[6][i].get()].round(0)
                else:
                    df['no_zip%s' % i] = df[combs[6][i].get()]

            if combs[8][i].get() == '':
                df['no_state%s' % i] = 'NY'
                vals = combs[7][i]['values'] + ('no_state%s' % i, )
                combs[6][i]['values'] = sorted(vals, key=keyfunction)
                choose_default(6, i, vals, 'no_state%s' % i)
            else:
                df['no_state%s' % i] = df[combs[8][i].get()]

            # trade(or legal) name + Original Address + City, State, Zip
            df['temp_add%s' % i] = ""
            #   originaladdress field
            df['Generated_streetaddress%s' %
               i] = df['Generated_streetaddress%s' % i].replace(
                   '*** NEED PHYSICAL ADDRESS ***', '')
            df.loc[df['Generated_streetaddress%s' % i].fillna('') != '',
                   'temp_add%s' %
                   i] = df['Generated_streetaddress%s' % i].fillna('') + ', '
            # the last bit maps boro code to borough name
            df['NameAddress%s' %
               i] = (df['trade2%s' % i].fillna('') + ', ' +
                     df['temp_add%s' % i] + df['no_city%s' % i] + ', ' +
                     df['no_state%s' % i] + ' ' +
                     df['no_zip%s' % i].apply(str))
            df['Address%s' % i] = (df['temp_add%s' % i] + df['no_city%s' % i] +
                                   ', ' + df['no_state%s' % i] + ' ' +
                                   df['no_zip%s' % i].apply(str))
            df['NameAddress%s' % i].head()
            print(df.head())

            # drop some temp fields.
            df.drop([
                'temp_add%s' % i,
                'no_boro%s' % i,
                'no_zip%s' % i,
                'no_city%s' % i,
                'no_state%s' % i
            ],
                    axis=1,
                    inplace=True)
        else:
            if combs[9][i].get() == "" or combs[10][i].get() == "":
                messagebox.showerror(
                    title='Both Latitude and Longitude Needed!',
                    message='Enter both Latitude and Longitude or neither')
                return
            else:
                df['Address%s' % i] = df[combs[9][i].get()].apply(
                    str) + ',' + df[combs[10][i].get()].apply(str)
                df['Generated_streetaddress%s' % i] = df['Address%s' % i]

    df = df.fillna('')

    # Run google API twice, for the Address only and Name+Address.
    df.reset_index(inplace=True)
    df['Goog_ID'] = df.index
    if (second_run_state.get() is True and combs[0][1].get() != ""
            and combs[1][1].get() != ""):
        add_list = ['Address', 'NameAddress']
        # Create a dataframe with unique observations on add_list
        df_unique = df[[
            'Address2', 'NameAddress2', 'Generated_streetaddress2', 'Address1',
            'NameAddress1', 'Generated_streetaddress1', 'Goog_ID'
        ]].copy()
        df_unique.drop_duplicates(
            subset=['Address1', 'NameAddress1', 'Address2', 'NameAddress2'],
            keep="first",
            inplace=True)
        df_unique.reset_index(inplace=True)
        merge_set = ['Address1', 'NameAddress1', 'Address2', 'NameAddress2']

        obs = len(df_unique.index) * 2
        print('There are %s unique observations to process...' % (obs))
    else:
        add_list = ['Address']
        # Create a dataframe with unique observations on add_list
        df_unique = df[[
            'Address1', 'Generated_streetaddress1', 'Address2',
            'Generated_streetaddress2', 'Goog_ID'
        ]].copy()
        df_unique.drop_duplicates(subset=['Address1', 'Address2'],
                                  keep="first",
                                  inplace=True)
        df_unique.reset_index(inplace=True)
        merge_set = ['Address1', 'Address2']
        obs = len(df_unique.index)
        print('There are %s unique observations to process...' % (obs))

    i = -1
    # print(add_list)
    startTime = time.time()

    directory = path.dirname(output.get())
    count_query = 0

    # Finally we can get directions.
    for var in add_list:
        print('Started checking variable ', var)
        i += 1
        for index, row in df_unique.iterrows():
            # set index <= len(df_unique.index) to process all observations.
            if index <= len(df_unique.index) and not (
                    var in ['Address'] and
                (row['Generated_streetaddress1'] == ''
                 or row['Generated_streetaddress2'] == '')):
                if arrival_state.get() == 1:
                    transit_result = gmaps.directions(
                        row["%s1" % var],
                        row["%s2" % var],
                        mode=tm_combo.get(),
                        arrival_time=dt_formatted)
                else:
                    transit_result = gmaps.directions(
                        row["%s1" % var],
                        row["%s2" % var],
                        mode=tm_combo.get(),
                        departure_time=dt_formatted)
                count_query += 1
                # print(json.dumps(transit_result, indent=4))
                status.set("Status: looking up observation %s of %s" %
                           (count_query, obs))
                # if Google doesn't find any routes, the api returns an empty list, which causes index errors.
                try:
                    temp_df0 = json_normalize(transit_result[0]['legs'])
                    temp_df0['Goog_ID'] = row['Goog_ID']
                    temp_df1 = json_normalize(
                        transit_result[0]['legs'][0]['steps'])
                    temp_df1['Goog_ID'] = row['Goog_ID']
                except:
                    print(row["%s1" % var], row["%s2" % var], tm_combo.get(),
                          dt_formatted)
                    temp_df0 = DataFrame(index=range(len(transit_result)),
                                         columns=['Goog_ID', 'dump_error'])
                    temp_df1 = DataFrame(index=range(len(transit_result)),
                                         columns=['Goog_ID', 'dump_error'])
                    temp_df0['dump_error'] = transit_result
                    temp_df0['Goog_ID'] = row['Goog_ID']
                    temp_df1['dump_error'] = transit_result
                    temp_df1['Goog_ID'] = row['Goog_ID']
                # print(temp_df1)
                #temp_df0.merge(temp_df1, left_on='id', right_on='id', how='outer')
                try:
                    dfLegs = dfLegs.append(temp_df0, ignore_index=True)
                    dfSteps = dfSteps.append(temp_df1, ignore_index=True)
                    # print('here:\n', index, row['Goog_ID'])
                except NameError:
                    dfLegs = temp_df0.copy()
                    dfSteps = temp_df1.copy()
                    #print('There:\n', dfLegs.head())

                if index % 500 == 0:
                    writer = ExcelWriter(
                        path.join(directory,
                                  "GOOGLE_recovery.xlsx").encode().decode())
                    dfLegs.to_excel(writer, 'Sheet1')
                    writer.save()
                    print(
                        "Recovery File GOOGLE_recovery.xlsx Saved when index was %s at %s"
                        % (index, datetime.now()))
                # Make sure that we are getting the results of the correct query saved.
                transit_result = None
            else:
                print('ERROR:', index, index <= len(df_unique.index),
                      row['Generated_streetaddress1'],
                      row['Generated_streetaddress2'])

    # Save The Results
    # Merge back unique addresses with geocodes with original df.
    results0 = merge(df_unique, dfLegs, on='Goog_ID', how='outer')
    result = merge(df, results0, on=merge_set, how='outer')
    # steps are saved separately
    result.drop(['index_x', 'steps'], axis=1, inplace=True)

    # Drop the temporary variables.
    try:
        result.drop(
            ['Generated_streetaddress1_x', 'Generated_streetaddress2_x'],
            axis=1,
            inplace=True)
        result.drop(
            ['Generated_streetaddress1_y', 'Generated_streetaddress2_y'],
            axis=1,
            inplace=True)
    except:
        None
    try:
        result.drop(['NameAddress1_x', 'NameAddress2_x'], axis=1, inplace=True)
        result.drop(['NameAddress1_y', 'NameAddress2_y'], axis=1, inplace=True)
    except:
        None
    # # Update Google output fields with new values if they already existed on the file.
    # for col in ['Gformatted_address0', 'Glat0', 'Glon0', 'GPartial0', 'Gtypes0', 'Gformatted_address1',
    #             'Glat1', 'Glon1', 'GPartial1', 'Gtypes1', 'Borough0', 'Borough1', 'Gzip0', 'Gzip1',
    #             'Gnumber0', 'Gnumber1', 'Gstreet0', 'Gstreet1', 'Both_Run_Same']:
    #     # print(col)
    #     if (col + '_y' in result.columns.values) and (col + '_x' in result.columns.values):
    #         result[col] = result[col + '_y'].fillna(result[col + '_x'])
    #         result.drop([col + '_y', col + '_x'], axis=1, inplace=True)

    # ExcelFile(output.get())
    try:
        writer = ExcelWriter(output.get())
        writerSteps = ExcelWriter(output.get().replace(".xls", "_steps.xls"))
        result.to_excel(writer, 'wTransit')
        dfSteps.to_excel(writerSteps, 'Transit_Steps')
        writerSteps.save()
        writer.save()
        message = output.get(
        ) + "\n was successfully saved!\n There were %s queries made to Google Directions API" % (
            count_query)
    except:
        writer = ExcelWriter(
            path.join(
                directory, "wGoogle_Transit" + time.strftime("%Y%m%d-%H%M%S") +
                ".xlsx").encode().decode())
        writerSteps = ExcelWriter(
            path.join(
                directory, "wGoogle_TransitSteps" +
                time.strftime("%Y%m%d-%H%M%S") + ".xlsx").encode().decode())
        result.to_excel(writer, 'With_Transit')
        dfSteps.to_excel(writerSteps, 'Transit_Steps')
        writerSteps.save()
        writer.save()
        message = (
            "Couldn't write to " + output.get() + "\n saved Google_Geocoded_" +
            time.strftime("%Y%m%d-%H%M%S") +
            ".xlsx to the same directory.\n There were %s queries made to Google Directions API"
            % (count_query))
#   remove the recovery file.

    remove(path.join(directory, "GOOGLE_recovery.xlsx").encode().decode())
    print('Processed data and saved: ', output.get())

    endTime = time.time()
    t = (endTime - startTime) / 60
    status.set('Status: Done. It took %s minutes to make %s queries.' %
               (round(t, 2), count_query))
    print('Took %s minutes to run.' % round(t, 2))

    messagebox.showinfo('Success!', message)
Exemplo n.º 34
0
def calc_distance(destination, target):
    gmaps = Client(key='SomeSecretKey')
    route = gmaps.directions(destination, target)
    legs = route[0]['legs']
    distance = legs[0]['distance']
    return distance['value'] / 1000.0
Exemplo n.º 35
0
from googlemaps import Client
from datetime import datetime

api_key = 'yourkey'
gmaps = Client('a key')
dir(gmaps)
whitehouse = '1600 Pennsylvania Avenue, Washington, DC'
whitehouse_geoloc = gmaps.geocode(whitehouse)
print whitehouse_geoloc

destination = gmaps.reverse_geocode((38.897096, -77.036545))
print destination

now = datetime.now()
directions_result = gmaps.directions("Sydney Town Hall",
                                     "Parramatta, NSW",
                                     mode="transit",
                                     departure_time=now)

lat_long = (gmaps.geocode(
    '326 Perkins Library, Durham, NC 27708')[0]['geometry']['location']['lat'],
            gmaps.geocode('326 Perkins Library, Durham, NC 27708')[0]
            ['geometry']['location']['lng'])
print lat_long
duke = gmaps.reverse_geocode(lat_long)[0]['formatted_address']
print duke

local = gmaps.places('restaurant near ' + duke)
print local['results'][0]['formatted_address']
print local['results'][0]['name']

directions = gmaps.directions(duke, whitehouse)
Exemplo n.º 36
0
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')

# Look up an address with reverse geocoding
reverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452))

# # Request directions via public transit
# now = datetime.now()
# directions_result = gmaps.directions((23.7846429,90.376789),
#                                      (23.775885, 90.723063),
#                                      mode="driving",
#                                      departure_time=now)

now = datetime.now()
directions_result = gmaps.directions(
    "ShewraPara Bus Stand, Begum Rokeya Ave, Dhaka 1216",
    "Mohakhali Bus Stop, Dhaka 1205",
    mode="driving",
    departure_time=now)

now = datetime.now()
directions_result1 = gmaps.directions("Monipuripara মনিপুরিপাড়া",
                                      "Mohakhali Bus Stop, Dhaka 1205",
                                      mode="driving",
                                      departure_time=now)

directions_result2 = gmaps.directions("Bijoy Sarani, Dhaka",
                                      "Mohakhali Bus Stop, Dhaka 1205",
                                      mode="driving",
                                      departure_time=now)

directions_result3 = gmaps.directions("Gulshan 1, Dhaka 1212",
Exemplo n.º 37
0
 if os.path.exists(arcpath) and (int(node_number*(node_number-1)/2))==file_len(arcpath):  #tests to see if the file already exists, if it does and is correct will skip this.
     print('Arc data for '+str(Method)+' at '+str(Start_Times_Tuple[arrivltme_list.index(arrivltme)])+' already exists!')
     continue
 g = open(arcpath,"w")
 
 while z<len(api_keys):
     gmaps = Client(api_keys[z])
     n = 0
     while n < (node_number):
         pnuc = Nodes[n]
         l = (n + 1)
         while l < node_number:
             snuc = Nodes[l]
             start_coords = str(str(pnuc[3])+" "+str(pnuc[4]))
             end_coords = str(str(snuc[3])+" "+str(snuc[4]))
             maps_output = gmaps.directions(start_coords, end_coords, mode=Method, arrival_time = arrivltme)
             if maps_output ==[]:
                 #No route between locations-gotta walk it but google doesn't do this intelligently for some reason
                 maps_output = gmaps.directions(start_coords, end_coords, mode='walking', arrival_time = arrivltme)
                 #Should proceed as normal after here: if the arc is so long it is unwalkable the algorith will discount it anyway
             timetaken = maps_output[0]['legs'][0]['duration']['value']
             tot_dist_traveled = maps_output[0]['legs'][0]['distance']['value']
             transport_boardings = 0
             walking_distance=int(tot_dist_traveled)
             walking_time=int(timetaken)
             
             if Method == 'transit':
                 for element in maps_output[0]['legs'][0]['steps']:
                     if element['travel_mode']=='TRANSIT':
                         transport_boardings+=1
                         walking_distance-=int(element['distance']['value'])
Exemplo n.º 38
0
class TrafficInformation(object):
    """

    """

    def __init__(self):
        config_read = ConfigRead("config.ini")
        gmaps_conf = config_read.read_googlemaps_config()
        self.gmaps = Client(key=gmaps_conf["token"])
        self.home = gmaps_conf["home"]
        self.work = gmaps_conf["work"]

    def current_address(self, gl_tuple):
        """

        :return:
        """
        adress_dict = dict()
        address_list = self.gmaps.reverse_geocode(gl_tuple)

        for addr_data in address_list[0]['address_components']:
            if addr_data['types'][0] == 'street_number':
                adress_dict['number'] = addr_data['long_name']
            if addr_data['types'][0] == 'route':
                adress_dict['street'] = addr_data['long_name']
            if addr_data['types'][0] == 'political':
                adress_dict['neibor'] = addr_data['long_name']
            if addr_data['types'][0] == 'locality':
                adress_dict['city'] = addr_data['long_name']
            if addr_data['types'][0] == 'country':
                adress_dict['country'] = addr_data['long_name']
            if addr_data['types'][0] == 'postal_code':
                adress_dict['postal_code'] = addr_data['long_name']

        return adress_dict

    def home_and_work_info(self, to_home=True):
        """

        :param to_home:
        :return:
        """
        info_dict = dict()

        if to_home:
            destination, departure = self.home, self.work
        else:
            destination, departure = self.work, self.home

        now = datetime.now()

        dt_info = self.gmaps.directions(
            departure,
            destination,
            mode='driving',
            departure_time=now
        )
        info_dict['distance'] = dt_info[0]['legs'][0]['distance']['text']
        info_dict['duration'] = dt_info[0]['legs'][0]['duration_in_traffic']['text']

        return info_dict

    def time_to_somewhere(self, from_addr, to_addr):
        """

        :param from_addr:
        :param to_addr:
        :return:
        """

        now = datetime.now()
        info_dict = dict()
        dt_info = self.gmaps.directions(
            from_addr,
            to_addr,
            mode='driving',
            departure_time=now
        )
        info_dict['distance'] = dt_info[0]['legs'][0]['distance']['text']
        info_dict['duration'] = dt_info[0]['legs'][0]['duration_in_traffic']['text']

        return info_dict
Exemplo n.º 39
0
from googlemaps import Client
from datetime import datetime

api_key = 'your key'
gmaps = Client(api_key)
dir(gmaps)
whitehouse = '1600 Pennsylvania Avenue, Washington, DC'
whitehouse_geoloc = gmaps.geocode(whitehouse)
print whitehouse_geoloc

destination = gmaps.reverse_geocode((38.897096, -77.036545))
print destination

now = datetime.now()
directions_result = gmaps.directions("Sydney Town Hall",
                                     "Parramatta, NSW",
                                     mode="transit",
                                     departure_time=now)

lat_long = (gmaps.geocode(
    '326 Perkins Library, Durham, NC 27708')[0]['geometry']['location']['lat'],
            gmaps.geocode('326 Perkins Library, Durham, NC 27708')[0]
            ['geometry']['location']['lng'])
print lat_long
duke = gmaps.reverse_geocode(lat_long)[0]['formatted_address']
print duke

local = gmaps.places('restaurant near ' + duke)
print local['results'][0]['formatted_address']
print local['results'][0]['name']

directions = gmaps.directions(duke, whitehouse)
Exemplo n.º 40
0
    def __init__(self):
        self.reset()
        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.feed(html)
    return s.get_data()


#Get Directions from googlemaps
directions = gmaps.directions(argv[1], argv[2])  #('texarkana','atlanta')

#print each step in directions to console
#print int(directions['Directions'])#['Routes']['seconds'][0]['Steps']
#for step in directions:#['Directions']['Routes'][0]['Steps']:
#	print step[u'html_instructions']
for step in directions[0]['legs'][0]['steps']:  #['seconds'][0]['Steps']:
    print strip_tags(step['html_instructions'])

#output to text file
with open('directions.txt', 'w') as f:
    for step in directions[0]['legs'][0]['steps']:  #['seconds'][0]['Steps']:
        f.write(strip_tags(step['html_instructions'] + '\r\n'))