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
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
def travelTime(location1, location2): distance = float(''.join([ x for x in distance_matrix(gmaps, location1, location2, mode="walking") ["rows"][0]["elements"][0]["distance"]["text"] if (x.isdigit() or x == '.') ])) return timeConvert(distance * 1000 // walkingSpeed)
def update(self): """Get the latest data from Google.""" options_copy = self._config_entry.options.copy() dtime = options_copy.get(CONF_DEPARTURE_TIME) atime = options_copy.get(CONF_ARRIVAL_TIME) if dtime is not None and ":" in dtime: options_copy[CONF_DEPARTURE_TIME] = convert_time_to_utc(dtime) elif dtime is not None: options_copy[CONF_DEPARTURE_TIME] = dtime elif atime is None: options_copy[CONF_DEPARTURE_TIME] = "now" if atime is not None and ":" in atime: options_copy[CONF_ARRIVAL_TIME] = convert_time_to_utc(atime) elif atime is not None: options_copy[CONF_ARRIVAL_TIME] = atime self._resolved_origin = find_coordinates(self.hass, self._origin) self._resolved_destination = find_coordinates(self.hass, self._destination) _LOGGER.debug( "Getting update for origin: %s destination: %s", self._resolved_origin, self._resolved_destination, ) if self._resolved_destination is not None and self._resolved_origin is not None: self._matrix = distance_matrix( self._client, self._resolved_origin, self._resolved_destination, **options_copy, )
def update(self): """Get the latest data from Google.""" options_copy = self._config_entry.options.copy() dtime = options_copy.get(CONF_DEPARTURE_TIME) atime = options_copy.get(CONF_ARRIVAL_TIME) if dtime is not None and ":" in dtime: options_copy[CONF_DEPARTURE_TIME] = convert_time_to_utc(dtime) elif dtime is not None: options_copy[CONF_DEPARTURE_TIME] = dtime elif atime is None: options_copy[CONF_DEPARTURE_TIME] = "now" if atime is not None and ":" in atime: options_copy[CONF_ARRIVAL_TIME] = convert_time_to_utc(atime) elif atime is not None: options_copy[CONF_ARRIVAL_TIME] = atime # Convert device_trackers to google friendly location if hasattr(self, "_origin_entity_id"): self._origin = get_location_from_entity(self.hass, _LOGGER, self._origin_entity_id) if hasattr(self, "_destination_entity_id"): self._destination = get_location_from_entity( self.hass, _LOGGER, self._destination_entity_id) self._destination = resolve_zone(self.hass, self._destination) self._origin = resolve_zone(self.hass, self._origin) if self._destination is not None and self._origin is not None: self._matrix = distance_matrix(self._client, self._origin, self._destination, **options_copy)
def calculate_distances(location_id): from carpool_matcher.models import Location, Distance location = Location.objects.get(pk=location_id) gclient = googlemaps.Client(key=settings.GOOGLE_MAPS_API_KEY) location_objects = Location.objects.filter(pk__lt=location.pk) if location_objects: locations = [l.get_location_tuple for l in location_objects] distance_matrix_response = distance_matrix(gclient, location.get_location_tuple, locations) assert distance_matrix_response['status'] == 'OK', 'Bad response from google maps API:\n{}'.format(distance_matrix_response) elements = distance_matrix_response['rows'][0]['elements'] for i, l in enumerate(location_objects): distance = elements[i]['distance']['value'] duration = elements[i]['duration']['value'] Distance.objects.create( start_point=location, end_point=l, distance=distance, time=duration, ) location.all_distances_calculated = True location.save()
def get_commute_details(commute_starting_address, commute_ending_address): """Get commute time and distance from Google Maps Arguments: commute_starting_address (str): Any address that can be geocoded by Google Maps for distance and directions. Where possible, store the ``formatted_address`` from a Google Maps geocode operation. commute_ending_address (str): Any address that can be geocoded by Google Maps for distance and directions. Where possible, store the ``formatted_address`` from a Google Maps geocode operation. Returns: dict: ``{"duration_seconds": int, "distance_meters": int}`` or None if Google Maps can't create directions for these addresses. """ api_result = distance_matrix.distance_matrix(MAPS_CLIENT, commute_starting_address, commute_ending_address) api_result = api_result['rows'][0]['elements'][0] if api_result['status'] != "OK": return None return { "duration_seconds": api_result['duration']['value'], "distance_meters": api_result['distance']['value'] }
def gmapcalc(location1, location2, apiuse): api_key = 'AIzaSyAn6U1F6NJIJx226L8sK5my_ECvHm7k18o' gmaps = Client(api_key) data = distance_matrix(gmaps, location1, location2) timeaway = data['rows'][0]['elements'][0]['duration']['text'] global apiusecounter apiusecounter += 1 return (timeaway)
def get_traffic(): gmaps = gmapClient(gm_key) distance = distance_matrix(gmaps, home_address, work_address, arrival_time=time.strptime( arrival_time, '%I:%M%p')) return distance['rows'][0]['elements'][0]['duration']['text']
def get_times(destinations): #Takes in a list of addresses client = googlemaps.Client(key = keys.google) matrix = distance_matrix(client = client, origins = destinations, #Makes it a symmetrical 2D array destinations = destinations, mode = 'driving', #If methods change, or want added funcionality, mode goes here language = 'english', units = 'imperial') #Same goes for units(metric) return build_matrix(matrix)
def get(self): # add if to check whether rider is groupHost or not driver = DriverModel.query.filter_by(id=self.args['driver_id']).first() rider = RiderModel.query.filter_by(id=driver.selected_rider).first() group = RiderModel.query.filter_by(groupHost=rider.groupHost).all() numRiders = len(group) # check to see if driver exists if driver is None: abort(502, 'Driver was not found in the database') # check to see if driver has a current rider elif driver.selected_rider is None: abort(502, 'Driver does not have a currently selected rider') # check to see if rider has a currently selected destination (maybe check this when rider added to driver) elif rider.destination is None: abort(502, 'Rider does not have a currently selected destination') # check to see if rider has a currently set location elif rider.long is None or rider.lat is None: abort(502, 'Riders location is not properly set') # find the distance between the riders location and his destionation and set a price accordingly else: try: # Need to add the functionality with Google's API #Origins will be passed as longitude/latitude and destinations will be passed as a physical address origins = rider.lat, rider.long destination = rider.destination #call the client function and provide API gmaps = client.Client( key="AIzaSyDJpvTBLUVor9hgDQyT3rp6jxzWUzFdD2Q") #Distance is calculated in meters, converted to miles, and multiplied by 1.50 (cost of driving a mile) distance = distance_matrix.distance_matrix( gmaps, origins, destination, mode='driving' )["rows"][0]["elements"][0]["distance"]["value"] distance = distance * 0.000621371 cost = distance * 1.50 indCost = cost / numRiders #cost for individual rider in group for groupMember in group: groupMember.outstandingBalance = indCost print(groupMember.name) db.session.commit() return jsonify(num_rider=numRiders, cost=cost, cost_per_rider=indCost) except: abort(502, 'Rider' 's charge could not be determined')
def create(self, places, data=u"duration"): """ Creates a new distance matrix :param places: :param data: :return: """ # Make sure, we have list of entries if not isinstance(places, list): return None # Make sure, that we use a valid metric supported by Google Maps if not unicode(data) in [u"duration", u"distance"]: return None # Response is HTTP from Google response = dm.distance_matrix(self.client, places, places) # Check if response was successful if response[u"status"] == u"OK": # Variable for return value matrix = dict() # Iterate over each place and its corresponding row in the response for start, row in izip(places, response[u"rows"]): # Wrap dict # start = GoogleDistanceMatrixFactory.Place(start) # Create entry for starting place matrix[start] = dict() # Iterate over all possible destinations and their indvidual responses for dest, element in izip(places, row[u"elements"]): # Check if a path was found if element[u"status"] != u"OK": return None # Create entry for start and destination matrix[start][dest] = element[unicode(data)][u"value"] return matrix else: return None
def gather(client: Client, origin: str, destinations: list) -> list: """ Gathers all distances between origin and destination cities using Google Distance Matrix API :param client: Client object provided by googlemaps package :param origin: origin city :param destinations: list of destination cities :return: list of distances in meters in the order of list destinations """ data = distance_matrix(client, origin, destinations) return [ data['rows'][0]['elements'][i]['distance']['value'] for i in range(0, len(destinations)) ]
def gethospitals(): places=places_nearby(client,getlocation(),keyword="Hospitals near me",open_now=True,rank_by='distance',type="hospital") hospitals=[] for hospital in places['results']: name=hospital['name'] if not 'Vetenary' in name: if not "Critical" in name: if not "Neuro" in name: hospitals.append(name) #return hospitals hospitaldistances={} for name in hospitals: hospitaldistances[name]=distance_matrix(client2,[tuple(getlocation())],name)['rows'][0]['elements'][0]['distance']['text'] return hospitaldistances
def get_duration(self, first_point, second_point, transit_mode='transit'): """ Result is a distance between two points with selected transit_mode transit_mode in {transit, walking} """ request = distance_matrix(self.gmaps_distance, first_point, second_point, mode=transit_mode, language='ru') elements = request['rows'][0]['elements'][0] if elements['status'] != 'OK': return None duration = elements['duration']['value'] return duration // 60
def get_duration(self, first_point, second_point): """ get two point return time from goolge maps api """ request = distance_matrix( self.gmaps, first_point, second_point, transit_mode='transit', language='english', ) elements = request['rows'][0]['elements'][0] if elements['status'] != 'OK': return None duration = elements['duration']['value'] return duration
def get_nearest_spot(lat, lng, ptype): """最近の授乳台/オムツ台の緯度経度を返す :param lat: float, 出発地の緯度 :param lng: float, 出発地の経度 :param ptype: str, オムツ台か授乳台か :return: pd.Series, 目的地の緯度経度 """ lat = float(lat) lng = float(lng) cur = conn.cursor() # 授乳台もしくはオムツ台が1つ以上ある箇所を取得 if ptype == 'milk': cur.execute('SELECT * FROM babymap where Junyu_num > 0') else: # == 'omutsu' cur.execute('SELECT * FROM babymap where Omutsu_num > 0') # 結果をpd.DataFrameに納める query_result = pd.DataFrame(cur.fetchall(), columns=[ "id", "Name", "Prefecture", "Ward", "Address", "Latitude", "Longtitude", "Junyu_num", "Omutsu_num" ]) # haversine distanceを求める query_result["haversine"] = query_result.apply( lambda x: haversine(lng, lat, x[["Longtitude"]], x[["Latitude"]]), axis=1) # haversine distanceが2km以下のものだけ取得 query_result = query_result[query_result['haversine'] < 2] # APIで徒歩距離を計算 nearest_path_result = distance_matrix.distance_matrix( gmap_client, (lat, lng), np.array(query_result[['Latitude', 'Longtitude']].astype('float')), transit_mode="walking") return query_result.iloc[nearest(nearest_path_result)][[ "Latitude", "Longtitude" ]].astype('float')
def traveltime(sorteddate, datetravel): for element in range(len(sorteddate) - 1): location1 = buildinglocation[sorteddate[element][0]] location2 = buildinglocation[sorteddate[element + 1][0]] if location1 == location2: datetravel.append(Hour_Min("00:00")) else: distance = distance_matrix(gmaps, location1, location2) meterstraveled = distance["rows"][0]["elements"][0]["distance"][ "value"] timetraveling = meterstraveled // walkingspeed hours = str(timetraveling // 60) minutes = str(timetraveling % 60) if len(hours) == 1: hours = "0" + hours if len(minutes) == 1: minutes = "0" + minutes totaltime = hours + ":" + minutes datetravel.append(Hour_Min(totaltime)) return (datetravel)
def traveltime2point(location1, location2): if location1 == location2: datetravel.append(Hour_Min("00:00")) else: distance = distance_matrix( gmaps, location1, location2, ) meterstraveled = distance["rows"][0]["elements"][0]["distance"][ "value"] timetraveling = meterstraveled // walkingspeed hours = str(timetraveling // 60) minutes = str(timetraveling % 60) if len(hours) == 1: hours = "0" + hours if len(minutes) == 1: minutes = "0" + minutes totaltime = hours + ":" + minutes return (Hour_Min(totaltime))
def calculate_distances(node_id): from router.models import Node, Edge node = Node.objects.get(pk=node_id) gclient = googlemaps.Client(key=settings.GOOGLE_MAPS_API_KEY) if node.adjacent_nodes.exists(): nodes = [n.get_node_tuple for n in node.adjacent_nodes.all()] distance_matrix_response = distance_matrix(gclient, node.get_node_tuple, nodes) assert distance_matrix_response['status'] == 'OK', 'Bad response from google maps API:\n{}'.format(distance_matrix_response) elements = distance_matrix_response['rows'][0]['elements'] for i, n in enumerate(node.adjacent_nodes.filter(id__lt=node.id)): distance = elements[i]['distance']['value'] duration = elements[i]['duration']['value'] n1 = min(node, n, key=lambda x: x.id) n2 = max(node, n, key=lambda x: x.id) try: edge = Edge.objects.get( node_1=n1, node_2=n2, ) edge.distance = distance edge.time = duration except Edge.DoesNotExist: edge = Edge( node_1=n1, node_2=n2, distance=distance, time=duration ) edge.save() node.all_distances_calculated = True node.save()
def get_commute_details(commute_starting_address, commute_ending_address): """Get commute time and distance from Google Maps Arguments: commute_starting_address (str): Any address that can be geocoded by Google Maps for distance and directions. Where possible, store the ``formatted_address`` from a Google Maps geocode operation. commute_ending_address (str): Any address that can be geocoded by Google Maps for distance and directions. Where possible, store the ``formatted_address`` from a Google Maps geocode operation. Returns: dict: ``{"duration_seconds": int, "distance_meters": int}`` or None if Google Maps can't create directions for these addresses. """ api_result = distance_matrix.distance_matrix(MAPS_CLIENT, commute_starting_address, commute_ending_address) api_result = api_result["rows"][0]["elements"][0] if api_result["status"] != "OK": return None return {"duration_seconds": api_result["duration"]["value"], "distance_meters": api_result["distance"]["value"]}
def _get_servicable_schedules(self, candidate_lyftee_points): lyfter_coord = (self.lyfter_service_obj.source_lat, self.lyfter_service_obj.source_long) destination_coords = [ (candidate_lyftee_point.lyftee_schedule_obj.destination_lat, candidate_lyftee_point.lyftee_schedule_obj.destination_long) for candidate_lyftee_point in candidate_lyftee_points ] matrix = distance_matrix(self.gmaps, [lyfter_coord], destination_coords) servicable_schedules = [] present_time = datetime.datetime.now(timezone.utc) for idx, row in enumerate(matrix["rows"][0]["elements"]): duration_in_seconds = row["duration"]["value"] print(present_time + timedelta(seconds=duration_in_seconds)) lyftee_schedule_obj = candidate_lyftee_points[ idx].lyftee_schedule_obj time_diff = (present_time - lyftee_schedule_obj.scheduled_time ) + timedelta(seconds=duration_in_seconds) if time_diff < SCHEDULE_TIME_DIFFERENCE_THRESHOLD: servicable_schedules.append(candidate_lyftee_points[idx]) return servicable_schedules
def download_time_predictions(requests: List[TimePredictionRequest]): api_key = 'AIzaSyD_iwBsgQAqVYV4X89hy9oZRbq1cwXaO00' google_maps_client = googlemaps.Client(api_key) predictions = [] for request in requests: response = distance_matrix.distance_matrix( google_maps_client, (request.origin.latitude, request.origin.longitude), (request.destination.latitude, request.destination.longitude), mode="driving", units="metric", departure_time=request.time ) predictions.append(TimePrediction( request.origin.name, request.destination.name, response['rows'][0]['elements'][0]['duration_in_traffic']['value'], request.time )) return predictions
temp.update({'latitude': lat}) temp.update({'longitude': lng}) if (v[i][4] == 'Two wheeler'): temp.update({'mode': '2w'}) elif (v[i][4] == 'Four wheeler'): temp.update({'mode': '4w'}) elif (v[i][4] == 'Bus'): temp.update({'mode': 'bus'}) elif (v[i][4] == 'Cab'): temp.update({'mode': 'cab'}) if (v[i][4] == 'Two wheeler' or v[i][4] == 'Four wheeler' or v[i][4] == 'Cab'): distance2 = distance_matrix(gmaps, str(v[i][3]), "college of engineering,pune,IN", "driving") temp.update({ 'distance1': distance2['rows'][0]['elements'][0]['distance']['text'] }) temp.update({ 'time_req': distance2['rows'][0]['elements'][0]['duration']['text'] }) elif (v[i][4] == 'Bus'): distance2 = distance_matrix(gmaps, str(v[i][3]), "college of engineering,pune,IN", "transit") temp.update({ 'distance1':
def get_durations_and_distances(self, origins, destinations_input, mode=GoogleCommuteNaming.DRIVING, with_traffic=False): """ NOTE: THIS SHOULD NOT BE CALLED DIRECTLY To update the cache please use the commute_cache_updater To retrieve an exact commute please use the commute_retriever function Gets the distance matrix corresponding to a destination and an arbitrary number of origins. Segments requests to the distance matrix API to include a maximum of 25 origins and returns the consolidated results. :param origins: (list(HomeCommute)) -> List of origins as a HomeCommute :param destinations_input: (HomeCommute or list(HomeCommute) -> The destination or destinations for the commute :param mode: (GoogleCommuteNaming) -> Must be the mode using the google distance defined mode i.e from the GoogleCommuteNaming class :returns a list of lists of tuples containing the duration and distance between the origins and the destination(s). Each inner list corresponds to an origin and each of its tuples corresponds to a pairing between that origin and one of its destinations. :raises DistanceMatrixException on invalid request Example Output: ('12323', '232323') (duration_in_seconds, distance_in_meters) """ distance_matrix_list = [] origin_list = origins # Make sure the destinations is a list if isinstance(destinations_input, (list,)): destinations = destinations_input else: destinations = [destinations_input] # maximizes 100 elements while retaining 25 origin/dest limit destination_number = int(min(25, len(destinations))) origin_number = int(min((100 / destination_number), 25)) # traffic option set to best_guess (default) traffic_model = self.determine_traffic_model(mode, with_traffic) # Determines the departure time to give more accurate commute information departure_time = self.determine_departure_time(mode, with_traffic) while origin_list: # only computes for the first destination_number destinations response_json = distance_matrix.distance_matrix(self.client, [i.return_commute() for i in origin_list[:origin_number]], [i.return_commute() for i in destinations[:destination_number]], units=self.units, mode=mode, departure_time=departure_time, traffic_model=traffic_model, ) response_list = self.interpret_distance_matrix_response(response_json, mode, with_traffic) # each inner list the entire results of an origin for res in response_list: distance_matrix_list.append(res) origin_list = origin_list[origin_number:] # consolidated list containing an inner list for each origin with the duration # in minutes to all of its destinations return distance_matrix_list
from googlemaps.client import Client from googlemaps.distance_matrix import distance_matrix from duration_auth import (apiKey) gmaps = Client(apiKey) data = distance_matrix(gmaps, "55.781121, -4.045619", "56.454346, -3.016491") duration = data['rows'][0]['elements'][0]['duration']['text'] print(duration)
def googlemap_drive_duration(startPoint, endPoint, startYear, startMonth, startDay, startHour, startMinute, total_num, API_keys): day = DateChecker.func( startYear, startMonth, startDay ) if int(startMonth) != 12: num_day_2018 = (date(2018, int(startMonth) + 1, 1) - date(2018, int(startMonth), 1)).days num_day_2017 = (date(2017, int(startMonth) + 1, 1) - date(2017, int(startMonth), 1)).days else: num_day_2018 = (date(2019, 1, 1) - date(2018, 12, 1)).days num_day_2017 = (date(2018, 1, 1) - date(2017, 12, 1)).days day_count_2018 = 0 day_count_2017 = 0 temp_2018 = [] temp_2017 = [] for j in range(num_day_2018): if DateChecker.func( 2018, int(startMonth), j + 1 ) == day: temp_2018.append( [] ) temp_2018[day_count_2018].append(2018) temp_2018[day_count_2018].append(int(startMonth)) temp_2018[day_count_2018].append(j + 1) day_count_2018 += 1 else: pass week_num = 0 for j in range(num_day_2017): if DateChecker.func( 2017, int(startMonth), j + 1 ) == day: if j + 1 == int(startDay): week_num = day_count_2017 + 1 else: pass temp_2017.append( [] ) temp_2017[day_count_2017].append(2017) temp_2017[day_count_2017].append(int(startMonth)) temp_2017[day_count_2017].append(j + 1) day_count_2017 += 1 else: pass if day_count_2018 < day_count_2017: startDay_2018 = temp_2018[week_num - 1][2] else: startDay_2018 = temp_2018[week_num][2] startPoint = "Divvy Station: " + startPoint endPoint = "Divvy Station: " + endPoint departureDate = datetime(int(2018), int(startMonth), int(startDay_2018), int(startHour), int(startMinute), 0, 0) departureDate.isoformat() gmaps = Client(api_key) data = distance_matrix(gmaps, startPoint, endPoint, "driving", departure_time = departureDate) try: driving_duration = data['rows'][0]['elements'][0]['duration']['text'] driving_duration_in_traffic = data['rows'][0]['elements'][0]['duration_in_traffic']['text'] driving_distance = data['rows'][0]['elements'][0]['distance']['text'] print (driving_distance) except KeyError: print ( data ) driving_duration = str(0) + " mins" driving_duration_in_traffic = str(0) + " mins" driving_distance = str(0) + " km" google_API_data = [driving_duration, driving_duration_in_traffic, driving_distance, data] return google_API_data
def _distance_matrix_request(self, origin_list, destination_list): origin_str = self._create_places_string(origin_list) destination_str = self._create_places_string(destination_list) return distance_matrix.distance_matrix(client=self._client, origins=origin_str, destinations=destination_str)
def __GoogleDistanceMatrix(self, locations): Destinations = dict() Destinations["Points"] = list() Destinations["IDs"] = list() for ID, Point in locations: Destinations["Points"].append(Point) Destinations["IDs"].append(ID) destinationsPerOrigin = 25 Matrix = list() requests = 0 originCount = 1 print "Origins:" , len(locations) StartTime = time.time() OriginTimes = 0 RequestTimes = 0 for orID, orPoint in locations: OriginStartTime = time.time() print "Current Origin: ", originCount RestDestinationPoints = Destinations["Points"] RestDestinationIDs = Destinations["IDs"] while RestDestinationIDs: # Get first 25 destinations from Remaining Destinations DestinationPoints = RestDestinationPoints[0:destinationsPerOrigin] DestinationIDS = RestDestinationIDs[0:destinationsPerOrigin] # Remaining Destinations now start 25 indices to the right RestDestinationPoints = RestDestinationPoints[destinationsPerOrigin:] RestDestinationIDs = RestDestinationIDs[destinationsPerOrigin:] if (requests % 100) == 0: time.sleep(0.5) RequestStartTime = time.time() results = gd.distance_matrix(self.GoogleClient, orPoint, DestinationPoints) #mode="driving",\ #avoid="tolls", units="metric", region="GR") RequestEndTime = time.time() RequestDuration = RequestEndTime - RequestStartTime RequestTimes += RequestDuration requests += 1 # results["rows"] has always only one row since we give only one origin point row = results["rows"] for elem, deID in izip(row[0]["elements"], DestinationIDS): Matrix.append([orID, deID, elem["duration"]["value"], elem["distance"]["value"]]) OriginEndTime = time.time() OriginDuration = OriginEndTime - OriginStartTime OriginTimes += OriginDuration originCount += 1 print "Requests: ", requests EndTime = time.time() WholeDuration = EndTime - StartTime (Mins, Secs) = SecondsToMinutes(WholeDuration) try: TimeLog = open("TimeLogs.txt", "a+") TimeLog.write("\n") full = "Time elapsed for " + str(requests) + "requests (" + str(len(locations)) + "x" + str(len(locations)) + "):"\ + str(Mins) + "min, " + str(Secs) + "sec" ori = "Time per origin: " + str(OriginTimes / len(locations)) + " sec" req = "Time per request: " + str(RequestTimes / requests) + " sec" print full print ori print req TimeLog.write(full + "\n") TimeLog.write(ori + "\n") TimeLog.write(req + "\n") except: print "Syntax error in TimeLogging" return Matrix
def distanceMatrix(addresses): raw_matrix = dm.distance_matrix(gmaps, addresses, addresses) return cleanMatrix(raw_matrix, len(addresses))
def solve_shortest_route(locations): count = len(locations) # NOTE: Even if you specify imperial units (units="imperial"), the distance will # be internally represented in kilometers! # convert matrix returned from API into a usable matrix of integers # for the solver (api_matrix -> dist_matrix) api_matrix = distance_matrix(gmaps, locations, locations, mode="driving", units="imperial") dist_matrix = [[0 for i in range(count)] for j in range(count)] rows = api_matrix["rows"] for i in range(count): row = rows[i] cols = row["elements"] for j in range(count): element = cols[j] duration = element["duration"]["value"] # distance = element["distance"]["value"] dist_matrix[i][j] = duration print(api_matrix) # assemble distance print("dist_matrix = [") for row in range(count): sys.stdout.write(" [") for col in range(count): if col == count - 1: sys.stdout.write("%8d " % dist_matrix[row][col]) else: sys.stdout.write("%8d, " % dist_matrix[row][col]) if row == count - 1: sys.stdout.write("]] # %s\n" % locations[row]) else: sys.stdout.write("], # %s\n" % locations[row]) tsp_size = count num_routes = 1 depot = 0 # Create routing model if tsp_size > 0: routing = pywrapcp.RoutingModel(tsp_size, num_routes, depot) search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters() # Create the distance callback. dist_callback = create_distance_callback(dist_matrix) routing.SetArcCostEvaluatorOfAllVehicles(dist_callback) # Solve the problem. assignment = routing.SolveWithParameters(search_parameters) if assignment: # Solution distance. # print "Total distance: " + str(assignment.ObjectiveValue()) + " miles\n" # Represent as time (using travel time instead of distance) print "Total time: " + time_from_seconds(assignment.ObjectiveValue()) # Display the solution. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1 route_number = 0 index = routing.Start(route_number) # Index of the variable for the starting node. route = '' while not routing.IsEnd(index): # Convert variable indices to node indices in the displayed route. route += str(locations[routing.IndexToNode(index)]) + ' -> ' index = assignment.Value(routing.NextVar(index)) route += str(locations[routing.IndexToNode(index)]) print "Route:\n\n" + route else: print 'No solution found.' else: print 'Specify an instance greater than 0.'