Ejemplo n.º 1
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
Ejemplo n.º 2
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
                  })
Ejemplo n.º 3
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
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]
 def check_googleMap(self, location):
     gmaps = Client(key='AIzaSyDAALCs0fN4bo9GdYeplrjdkpg6Lc8LpiU')
     #lat,lan = gmaps.address_to_latlng(location)
     ginfo = gmaps.geocode(location)
     dic = ginfo[0]
     lat = dic.get('geometry').get('bounds').get('northeast').get('lat')
     lng = dic.get('geometry').get('bounds').get('northeast').get('lng')
     return [lat,lng]
Ejemplo n.º 6
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
Ejemplo n.º 7
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'
Ejemplo n.º 8
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 
Ejemplo n.º 9
0
    def save(self, *args, **kwargs):
        # only update timestamp when the object is first created
        # when id is not set yet
        if not self.id:
            self.timestamp = timezone.now()
        self.updated = timezone.now()
        self.slug = slugify(self.title)
        gmaps = Client(key="AIzaSyDPPebmy_mg8ho15JXng1WD2ByUsYrT7bY")
        results = gmaps.geocode(address=self.address + ", " + self.city, region="CA")
        if results:
            self.lat = results[0]['geometry']['location']['lat']
            self.lon = results[0]['geometry']['location']['lng']

        return super(Post, self).save(*args, **kwargs)
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)
Ejemplo n.º 11
0
def get_lat_lng():
    """ For user input (eg. 'Constitution Ave NW & 10th St NW, Washington, DC',

    'San Francisco, CA','Moscow, Russia')calculate geocode using Googlemaps API"""

    api_key = os.environ["GEOCODING_KEY"]
    gmaps = Client(api_key)
    address = request.args.get("address")

    for dictionary in gmaps.geocode(address):
        lat = dictionary["geometry"]["location"]["lat"]
        lng = dictionary["geometry"]["location"]["lng"]

    payload = {"lat": lat, "lon": lng}

    return payload
Ejemplo n.º 12
0
def update_gecode(ip, location):
    from googlemaps import Client
    # from django.conf import settings
    import json

    ip.latitude = location['latitude']
    ip.longitude = location['longitude']

    gmaps = Client(key=settings.GOOGLE_GEOCODE_KEY)
    result = gmaps.reverse_geocode(
        (location['latitude'], location['longitude']))
    ip.geocode = json.dumps(result)

    print result

    ip.save()
Ejemplo n.º 13
0
def locate(area: str = None) -> str:
    """Returns current location.

    area: Looks for specific details of an address while locating.
          Default: None

    Find and returns current global position using reverse lookup via Google Maps API.

    Note: Function uses Google Maps for retreiving latitude and longitude
    using Google Maps API. Hence it is necessary to generate the API key first
    before running this function.
    You can generate it here: https://console.developers.google.com

    Caution: If you run the function without passing valid API key, it will
    raise an exception.
    """
    import os
    from geocoder import osm
    from googlemaps import Client

    try:
        if check_internet():
            # Passing Google maps API key.
            gmaps = Client(key=os.environ.get('CHARLOTTE_MAPS_KEY'))
            # Finding current latitude and longitude details.
            current_coords = gmaps.geolocate()
            location = osm(list(current_coords['location'].values()),
                           method='reverse')
            if area is not None:
                try:
                    # Returns particular address detail only.
                    return location.json[area]
                except:
                    return _NO_RESPONSE
            else:
                try:
                    # Returns complete address.
                    return location.json['address']
                except:
                    return _NO_RESPONSE
        else:
            # Returns None if no internet connection is available.
            return None
    except Exception as error:
        print('An error occured while performing this operation because of'
              f' {error} in function "{stack()[0][3]}" on line'
              f' {exc_info()[-1].tb_lineno}.')
Ejemplo n.º 14
0
def find_locales_inside(gmaps: googlemaps.Client, au_suburbs: pd.DataFrame,
                        address: str):
    target = munchify(gmaps.geocode(address)[0])
    bounds = target.geometry.bounds
    return au_suburbs.loc[(au_suburbs.lat >= bounds.southwest.lat)
                          & (au_suburbs.lat <= bounds.northeast.lat) &
                          (au_suburbs.lon >= bounds.southwest.lng) &
                          (au_suburbs.lon <= bounds.northeast.lng)]
Ejemplo n.º 15
0
def _get_coords(location: Optional[Text] = None) -> Tuple:
    """Returns coords for the asked location.

    location: Location or the address to be converted to latitude and
              longitude.
              Default: None

    Find and returns current global position and the city using reverse
    lookup via Google Maps API.

    Note: Function uses Google Maps for retreiving latitude & longitude
    using it`s API. Hence it is necessary to generate the API key first
    before running this function.
    You can generate it here: https://console.developers.google.com

    Caution: If you run the function without passing valid API key, it
    will raise an exception.
    """
    import os
    from geocoder import osm
    from googlemaps import Client

    try:
        # Passing Google maps API key.
        map = Client(key=os.environ.get('CHARLOTTE_MAPS_KEY'))
        # Finding current latitude and longitude coordinates.
        if location:
            curr = map.geocode(location)
            coords = (curr[0]['geometry']['location']['lat'],
                      curr[0]['geometry']['location']['lng'])
        else:
            curr = map.geolocate()
            coords = (curr['location']['lat'], curr['location']['lng'])
        # Reverse mapping the coordinates to find out the city name.
        area = osm(coords, method='reverse')
        loc_list = ['city', 'town', 'suburb', 'state', 'region', 'country']
        for idx in loc_list:
            if area.json.get(idx, None) is not None:
                loc = area.json[idx]
                break
        return coords, loc
    except Exception as error:
        print('An error occured while performing this operation because of '
              f'{error} in function "{stack()[0][3]}" on line '
              f'{exc_info()[-1].tb_lineno}.')
        return (None, None), None
Ejemplo n.º 16
0
async def offer_park(ctx, *locations):
    location = ""
    for place in locations:
        location = location + place
    gmaps = Client('AIzaSyA0QJJKbsee6MVN7DAiVSeTUOV2F-V0rRs')
    latitude = gmaps.geocode(location)[0]['geometry']['location']['lat']
    longitude = gmaps.geocode(location)[0]['geometry']['location']['lng']
    results = findPlaces(latitude, longitude, "museum")
    MAX_RESULTS = 5
    curr_result = 0
    for result in results:
        if curr_result == MAX_RESULTS:
            return
        message = str(curr_result + 1) + ". Name: " + result[
            'name'] + "\n\tLocation: " + result['vicinity']
        await ctx.send(message)
        curr_result = curr_result + 1
Ejemplo n.º 17
0
def get_lat_lng():
    """ For user input (eg. 'Constitution Ave NW & 10th St NW, Washington, DC',

    'San Francisco, CA','Moscow, Russia')calculate geocode using Googlemaps API"""

    api_key = os.environ['GEOCODING_KEY']
    gmaps = Client(api_key)
    address = request.args.get("address")

    for dictionary in gmaps.geocode(address):
        lat = dictionary['geometry']['location']['lat']
        lng = dictionary['geometry']['location']['lng']

    payload = {'lat': lat,
               'lon': lng}

    return payload
Ejemplo n.º 18
0
def select(paras):
    a = time.time()
    gmaps = Client(key='AIzaSyAdtMHxfsESr0OuVdGuseM_VW_uiDtahJY')
    address = paras['street'] + ", " + paras['city'] + ", " + paras['state']
    latitude, longtitude = geofind(address)
    print "Location convertion: " + str(latitude) + str(longtitude)
    time_start_mon = int(paras['s_mon'])
    time_start_day = int(paras['s_day'])
    time_start_hour = int(paras['s_hou'])
    time_end_mon = int(paras['e_mon'])
    time_end_day = int(paras['e_day'])
    time_end_hour = int(paras['e_hou'])
    radius = paras['r']
    start_time = datetime.datetime(YEAR, time_start_mon, time_start_day,
                                   time_start_hour, 0)
    end_time = datetime.datetime(YEAR, time_end_mon, time_end_day,
                                 time_end_hour, 0)
    start_epoch_time = time.mktime(start_time.timetuple()) * 1000
    print "start" + str(start_epoch_time)
    end_epoch_time = time.mktime(end_time.timetuple()) * 1000
    distance = "3959*acos((sin({3}/57.29577951)*sin(latitude/57.29577951)+cos({3}/57.29577951)*cos(latitude/57.29577951)*cos(abs(longtitude-({2}))/57.29577951))) <{4}"
    querystr = (
        "select user, uid, feature, longtitude, latitude, time, size from Meta_data where time >= {0} and time <= {1} and "
        + distance + " order by user;").format(start_epoch_time,
                                               end_epoch_time, longtitude,
                                               latitude, radius)

    if (paras['r'] == '0'):
        querystr = (
            "select user, uid, feature, longtitude, latitude, time, size from Meta_data where time >= {0} and time <= {1} order by user;"
        ).format(start_epoch_time, end_epoch_time)
    print querystr
    con, cur = sql_execute(querystr)
    b = time.time()
    f = open('timestamp', 'w')
    f.write(str(b - a))
    f.close()
    data = []
    while True:
        dat = cur.fetchone()
        if dat == None:
            break
        data.append(dat)
    # print "paras['type']=" + paras['type'] # paras['type']=0
    if (paras['type'] == '0'):
        return top_k_similar(data, paras['option1'], paras['option2'],
                             paras['deadline'])
    if (paras['type'] == '1'):
        return mst.call_mst(data, paras['deadline'])
    if (paras['type'] == '2'):
        return kmeans_new.call_kmeans(data, paras['deadline'],
                                      int(paras['option1']))
    if (paras['type'] == '3'):
        return represent.call_represent(data, paras['deadline'],
                                        int(paras['option1']))
    else:
        return [], []
    pass
Ejemplo n.º 19
0
    def reverse_geocode_ipstore(self, queryset):
        """Reverse geocode the new ip to get more info from lat/longs

        Args:
            queryset (TYPE): Description

        Returns:
            TYPE: Description
        """
        from apps.warehouse.models import IPStore
        from googlemaps import Client
        from django.conf import settings
        import json

        gmaps = Client(key=settings.GOOGLE_GEOCODE_KEY)

        import datetime
        _now = datetime.datetime.now()

        for ip in IPStore.objects.filter(geocode__isnull=True):
            print '---'
            print ip.ip
            print '---'
            qs = queryset.filter(
                meta__at_ip=ip.ip).order_by('-added_on')
            print qs
            print '---'
            if qs.count() > 0:
                obj = qs[0]
            else:
                obj = None
            if obj:
                location = obj.meta['ip2geo']['location']
                ip.latitude = location['latitude']
                ip.longitude = location['longitude']
                result = gmaps.reverse_geocode((location['latitude'], location['longitude']))
                ip.geocode = result
                ip.save()
                print '---'
                print ip.ip
                print '---'
                print location
                print '---'
                print ip.geocode
                print '---'
Ejemplo n.º 20
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
Ejemplo n.º 21
0
    def update_gecode(self, ip, location):
        from googlemaps import Client
        from googlemaps.exceptions import Timeout
        from django.conf import settings
        import json

        ip.latitude = location['latitude']
        ip.longitude = location['longitude']

        try:
            gmaps = Client(key=settings.GOOGLE_GEOCODE_KEY)
            result = gmaps.reverse_geocode(
                (location['latitude'], location['longitude']))
            ip.geocode = result
        except Timeout:
            print 'unable to reverse geocode: %s' % (ip)

        ip.save()
Ejemplo n.º 22
0
def getRouteFromUserToBusinessByAppointmentId(aid):
    api_key = "AIzaSyCeHf-jcEx21QPuV7BZOUOukikZ-bQYxDA"
    google = GoogleMaps(api_key)
    route = AppointmentsHandler().getRouteFromUserToBusinessByAppointmentId(
        aid)
    originaddress = route[0] + ', ' + route[1]
    destaddress = route[2] + ', ' + route[3]
    geocode_origin_result = google.geocode(originaddress)
    geocode_dest_result = google.geocode(destaddress)
    originlatitude = geocode_origin_result[0]['geometry']['location']['lat']
    originlongitude = geocode_origin_result[0]['geometry']['location']['lng']
    destlatitude = geocode_dest_result[0]['geometry']['location']['lat']
    destlongitude = geocode_dest_result[0]['geometry']['location']['lng']
    return render_template('route.html',
                           originlongitude=originlongitude,
                           originlatitude=originlatitude,
                           destlongitude=destlongitude,
                           destlatitude=destlatitude)
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())
Ejemplo n.º 24
0
 def __init__(self, key=''):
     self.key = key
     self.lat = None
     self.lng = None
     self.country = ''
     self.is_us = False
     self.json = None
     if not self.key:
         raise AssertionError("There was no API keys specified.")
     self.client = GClient(key=self.key)
Ejemplo n.º 25
0
 def __init__(self, connection_string=None):
     self.client = Client(get_api_key())
     self.connection_string = connection_string
     self.engine = create_engine(connection_string)
     self.Session = sessionmaker(bind=self.engine)
     self.session = self.Session()
     self.from_addresses = []
     self.to_addresses = []
     self.results = []
     Base.metadata.create_all(bind=self.engine)
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 
Ejemplo n.º 27
0
def is_valid_config_entry(opp, logger, api_key, origin, destination):
    """Return whether the config entry data is valid."""
    origin = resolve_location(opp, logger, origin)
    destination = resolve_location(opp, logger, destination)
    client = Client(api_key, timeout=10)
    try:
        distance_matrix(client, origin, destination, mode="driving")
    except ApiError:
        return False
    return True
Ejemplo n.º 28
0
def is_valid_config_entry(hass, api_key, origin, destination):
    """Return whether the config entry data is valid."""
    origin = find_coordinates(hass, origin)
    destination = find_coordinates(hass, destination)
    client = Client(api_key, timeout=10)
    try:
        distance_matrix(client, origin, destination, mode="driving")
    except ApiError:
        return False
    return True
Ejemplo n.º 29
0
    def buscar(self):
        nombre_ubicacion = self.ui.txt_nombre_ubicacion.text().strip()

        if len(nombre_ubicacion):
            cliente = Client(key='AIzaSyDCugQUG_8vYlrXz2URJEUgYKuOF4miIcU')

            resultado = cliente.geocode(nombre_ubicacion)[0]

            self.ui.txt_ciudad.setText(nombre_ubicacion)
            self.ui.txt_nombre_completo_ubicacion.setText(
                resultado['formatted_address'])
            self.ui.txt_latitud.setText(
                str(resultado['geometry']['location']['lat']))
            self.ui.txt_longitud.setText(
                str(resultado['geometry']['location']['lng']))
        else:
            self.mensaje.setIcon(QMessageBox.Warning)
            self.mensaje.setText('El campo Nombre ubicación es obligatorio.')
            self.mensaje.exec_()
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
  def __query_INFO(search_parameter):
    
     gmaps = client(key = Extractor.__API_KEY)
     #Query google API by parameter_type
     query_DATA = []

     query_results = client.find_place(gmaps, ('+1' + search_parameter) , 'phonenumber', ['name', 'types'])        
     for item in query_results.items():
        query_DATA.append(item[1][0]['name'])
        query_DATA.append(item[1][0]['types'][0]) 
        return query_DATA
Ejemplo n.º 32
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))
Ejemplo n.º 33
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
Ejemplo n.º 34
0
 def __init__(self, lat, lng):
     # maps neighbor node to distance
     """
     a node representing a location on the map using latitude and longitude
     :param lat: latitude of this node
     :param lng: longitude
     """
     self.neighbors = dict()  # dict of node -> distance
     self.latitude = lat
     self.longitude = lng
     self.elevation = elevation(Client(key='AIzaSyCtnZS7miejfbAh1FsKUBhxil1VXa0EicY'), (lat, lng))[0]['elevation']
Ejemplo n.º 35
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)
Ejemplo n.º 36
0
def find_using_google(user_query, lat_long_coordinates, minimum_price=0, maximum_price=2, next_page_token=""):
        google_client = Client(app.config['GOOGLE_API_KEY'])
        radius = 500
        result_type_filter = 'restaurant'

        result = places.places(google_client, query=user_query, location=lat_long_coordinates, 
                               radius=radius, min_price=minimum_price, max_price=maximum_price, 
                               type=result_type_filter, page_token=next_page_token)
        formatted_results = format_google_return_list(result['results'])
        if 'next_page_token' in result:
            return {'resultList': formatted_results, 'nextPageToken': result['next_page_token']}
        return {'resultList': formatted_results, 'nextPageToken': None}
Ejemplo n.º 37
0
class Gmaps:
    def __init__(self, APIKey):
        self.key = APIKey
        self.Gmaps = GoogleMaps(self.key)

    def get_Region(self, address):
        try:
            Location = self.Gmaps.geocode(address)
            region = Location[0]["address_components"][7]["short_name"]
            return region
        except:
            return ""
Ejemplo n.º 38
0
    def say_hi(self):
        gmaps = Client('AIzaSyD0AJQRoThLlugn1lW_TgYhRBtRON34LDA')
        start = self.E1.get()
        finish = self.E2.get()

        url = 'http://maps.googleapis.com/maps/api/directions/json?%s' % urlencode(
            (('origin', start), ('destination', finish)))
        ur = urlopen(url)
        result = json.load(ur)
        for i in range(0, len(result['routes'][0]['legs'][0]['steps'])):
            j = result['routes'][0]['legs'][0]['steps'][i]['html_instructions']
            self.list1.insert(0, j)
Ejemplo n.º 39
0
class location(metaclass=Singleton):
    def __init__(self, s=""):
        self.api_key = 'AIzaSyAhb_rBwht_tVUC0VEFMiQIqelRESZgL_c'
        if s != "":
            self.api_key = s
        self.gmaps = GoogleMaps(self.api_key)

    def find_location_for(self, adr):
        l = self.gmaps.geocode(adr)
        lat = l[0]["geometry"]["location"]["lat"]
        lon = l[0]["geometry"]["location"]["lng"]
        return lat, lon
Ejemplo n.º 40
0
 def perform_create(self, serializer):
     gmaps = Client(key=os.environ['GOOGLE_MAPS_KEY'])
     origin_city = f"{serializer.validated_data['origin_city']}, {serializer.validated_data['origin_state']}"
     destination_city = f"{serializer.validated_data['destination_city']}, {serializer.validated_data['destination_state']}"
     origin_gmaps = gmaps.find_place(
         origin_city, 'textquery', fields=['geometry', 'formatted_address'])
     destination_gmaps = gmaps.find_place(
         destination_city,
         'textquery',
         fields=['geometry', 'formatted_address'])
     serializer.save(
         owner=self.request.user,
         origin_lat=origin_gmaps['candidates'][0]['geometry']['location']
         ['lat'],
         origin_lon=origin_gmaps['candidates'][0]['geometry']['location']
         ['lng'],
         destination_lat=destination_gmaps['candidates'][0]['geometry']
         ['location']['lat'],
         destination_lon=destination_gmaps['candidates'][0]['geometry']
         ['location']['lng'],
     )
Ejemplo n.º 41
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()
Ejemplo n.º 42
0
    def calcular_distancia(self):
        primera_ubicacion = self.ui.txt_primera_ubicacion.text().strip()

        if len(primera_ubicacion):
            segunda_ubicacion = self.ui.txt_segunda_ubicacion.text().strip()

            if len(segunda_ubicacion):
                cliente = Client(key='AIzaSyDCugQUG_8vYlrXz2URJEUgYKuOF4miIcU')

                resultado = cliente.distance_matrix(primera_ubicacion, segunda_ubicacion)

                distancia = resultado['rows'][0]['elements'][0]['distance']['text']

                self.ui.txt_distancia.setText(distancia)
            else:
                self.mensaje.setIcon(QMessageBox.Warning)
                self.mensaje.setText('El campo Segunda ubicación es obligatorio.')
                self.mensaje.exec_()
        else:
            self.mensaje.setIcon(QMessageBox.Warning)
            self.mensaje.setText('El campo Primera ubicación es obligatorio.')
            self.mensaje.exec_()
Ejemplo n.º 43
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
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)                                 
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)                                
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from urllib import urlopen  # <-------------
import requests
import json
from googlemaps import Client
from database import collection


# maxPages = int(sys.argv[1])  # numero di pagine da prendere
pageArray = []
gmaps = Client(key='AIzaSyDGGQRjUKv2HkqPzotZx9isbz-xXVDR0NQ')


# def metaSparkfunParse():
#     print 'get metadata sparkfun'

# for i in range(maxPages):
# for i in range(100, 105):
#     page = i
#     print(i)
#     try:
#         # pageArray.append(urllib.request.urlopen("https://data.sparkfun.com/streams/?page=" + str(page)))
#         pageArray.append(urlopen("https://data.sparkfun.com/streams/?page=" + str(page)))
#     except:
#         print (sys.exc_info()[0])
#         continue

pageArray.append(urlopen("https://data.sparkfun.com/streams/?page=105"))
Ejemplo n.º 47
0
from googlemaps import Client as GoogleMaps
from googlemaps import geocoding
from googlemaps import convert

API_Key="AIzaSyDVYcV4L2bOFuiEvjgvtTWsVieX7nZfzeo"

gmaps = GoogleMaps(API_Key)
address = raw_input("Enter a location: ")
coordinates = gmaps.geocode(address)
print coordinates
Ejemplo n.º 48
0
from googlemaps import Client as GoogleMaps
gmaps = GoogleMaps(api_key="YOUR KEY")
address = 'Constitution Ave NW & 10th St NW, Washington, DC'
lat, lng = gmaps.address_to_latlng(address)
print lat, lng
Ejemplo n.º 49
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)
Ejemplo n.º 50
0
#0.3 os package used to change directory
import os
#0.4 Client package from google maps used to query distances
from googlemaps import Client
#0.5 Import numpy
import numpy as np 
#-----------------------------------------------------------------

#-----------------------------------------------------------------
#1. Change directory
os.chdir('/Users/rodrigoazuero/Documents/DATAIDB2015/Clusters/FinalFiles/Python/Cluster8')
#-----------------------------------------------------------------

#-----------------------------------------------------------------
#2. Store the API key in the following variables
gmaps=Client('INSTERT-KEY-HERE')
gmaps=Client(key='INSTERT-KEY-HERE')

#-----------------------------------------------------------------

#-----------------------------------------------------------------
#3. Matrix definitions for distances. We need to replace
#the values with the corresponding rank for the matrices.
drivedistance= np.empty((10000,10000), dtype=np.object)
walkdistance= np.empty((10000,10000), dtype=np.object)

#3.1 Define the threshold variable. I will compute the google maps query exclusively
#for those schools within the value of threshold
threshold=10

#-----------------------------------------------------------------
Ejemplo n.º 51
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
Ejemplo n.º 52
0
def from_place_to_lati_longi(place):
  gmaps = Client(API_KEY)
  address = place
  lat_lng = gmaps.geocode(address)[0][u'geometry'][u'location']
  return lat_lng
	def __init__(self,key):
		self.key=key
		self.con = Client(key=self.key)
Ejemplo n.º 54
0
 def get_lat_long(self):
     gmaps = Client(key=settings.GMAPS_API_KEY)
     results = gmaps.geocode(address=self.address + ", " + self.city, region="CA")
     if results:
         lat_lng = results[0]['geometry']['location']
         return lat_lng
Ejemplo n.º 55
0
from datetime import timedelta
from datetime import datetime
from pytz import timezone
import re
from skiplagged import Skiplagged
from pushbullet import Pushbullet
from googlemaps import Client
from utils.pokemon import is_unique


        

if __name__ == '__main__':
    client = Skiplagged()
    pb = Pushbullet(os.getenv("PB_KEY"))
    gmaps = Client(os.getenv("GMAP_KEY"))


    #bounds = client.get_bounds_for_address('Isla Vista, CA')
    bounds = (
              (34.408359, -119.869816), # Lower left lat, lng
              (34.420923, -119.840293) # Upper right lat, lng
              )
    
    
    for channel in pb.channels:
        print channel
        if channel.channel_tag == '':
          my_channel = channel
    
    
Ejemplo n.º 56
0
def append_elevation(lat, lon, gmaps_api_key):
    request_google = Client(key=str(gmaps_api_key))
    location = (lat, lon)
    response = request_google.elevation(locations=location)
    elev = response[0]['elevation']
    return (lat, lon, elev)
Ejemplo n.º 57
0
def getGeocode(location):
	c = Client("AIzaSyAGfQB9o_UWdN6NNn9L0jv_6ppXgW4W-uo")
	return c.geocode(location)[0]["geometry"]["location"]
Ejemplo n.º 58
0
def getgeo(address):
    gmaps = Client('AIzaSyA3i4VXAqU2qmSXKQ3ve4htc_QNxLaJpW4')
    json_response = gmaps.geocode(address)
    dictionary= json_response[0]['geometry']['location']
    return dictionary[u'lat'],dictionary[u'lng']
Ejemplo n.º 59
0
#0.3 os package used to change directory
import os
#0.4 Client package from google maps used to query distances
from googlemaps import Client
#0.5 Import numpy
import numpy as np 
#-----------------------------------------------------------------
#Block of parameter definition. 
#-----------------------------------------------------------------
#1. Change directory
os.chdir('/Users/rodrigoazuero/Dropbox/gmapsdistance/gmapsdistancePython')
#-----------------------------------------------------------------

#-----------------------------------------------------------------
#2. Store the API key in the following variables
gmaps=Client('AIzaSyB2GpMeRX8FHzz0aVZApbnF8_wlw88eBK0')
gmaps=Client(key='AIzaSyB2GpMeRX8FHzz0aVZApbnF8_wlw88eBK0')

#-----------------------------------------------------------------

#-----------------------------------------------------------------
#3. Matrix definitions for distances. We need to replace
#the values with the corresponding rank for the matrices.
DISTANCEFINAL= np.empty((10000,10000), dtype=np.object)


#3.1 Define the threshold variable. I will compute the google maps query exclusively
#for those schools within the value of threshold
threshold=10

Ejemplo n.º 60
0
# -*- coding: utf8 -*-
import pandas as pd
import numpy as np
from pandas import Series, DataFrame
import re
import googlemaps
from googlemaps import Client



API_KEY = 'AIzaSyAcXNyjXepUbFyAf5auZq_RAF_CJJofG_E'

#create the Google maps client
gmaps = Client(key=API_KEY)
#mapp = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Paris&destinations=Poitier&mode=bicycling&language=fr-FR&key=AIzaSyAcXNyjXepUbFyAf5auZq_RAF_CJJofG_E'


# read the cities

cities = pd.read_csv('villes.csv')

origins = ["Perth, Australia", "Sydney, Australia",
                   "Melbourne, Australia", "Adelaide, Australia",
                   "Brisbane, Australia", "Darwin, Australia",
                   "Hobart, Australia", "Canberra, Australia"]

origins = list(cities['Ville'].values[0:10])
destinations = list(cities['Ville'].values[0:10])

matrix = gmaps.distance_matrix(origins, destinations)
matrix_train = gmaps.distance_matrix(origins, destinations,mode='walking')