def get_google_locations(self, start_string, end_string, path=False): """ :param start_string: starting location :param end_string: destination location :param path: inid :return: """ #set whether or not to use a pedestrian path mode = "driving" if path: mode = "walking" use_client = client.Client(key=google_key) #Example responses to test code with (to limit api call count) #directions = dict([{u'overview_polyline': {u'points': u'cgriFt|k`NFF?E@Md@aALi@Do@IkBGa@}@sAQk@E]?g@B[Lk@LWNQTO`@K|AGb@?lAJjDZXFVoBBmAE{@WoAsAqFWo@Im@Cg@Ba@Fa@r@{BnAeEFy@CsA[cBAq@Hq@Tw@'}, u'warnings': [], u'bounds': {u'northeast': {u'lat': 38.4373241, u'lng': -78.86271409999999}, u'southwest': {u'lat': 38.4346274, u'lng': -78.8732684}}, u'waypoint_order': [], u'summary': u'Bluestone Dr and Carrier Dr', u'copyrights': u'Map data \xa92018 Google', u'legs': [{u'distance': {u'text': u'0.8 mi', u'value': 1273}, u'traffic_speed_entry': [], u'end_address': u'701 Carrier Dr, Harrisonburg, VA 22807, USA', u'via_waypoint': [], u'start_address': u'Wilson Hall, 951 Madison Dr, Harrisonburg, VA 22801, USA', u'start_location': {u'lat': 38.4371436, u'lng': -78.87323119999999}, u'steps': [{u'html_instructions': u'Head <b>southwest</b> on <b>Madison Dr</b> toward <b>Bluestone Dr</b>', u'distance': {u'text': u'20 ft', u'value': 6}, u'travel_mode': u'DRIVING', u'start_location': {u'lat': 38.4371436, u'lng': -78.87323119999999}, u'polyline': {u'points': u'cgriFt|k`NFF'}, u'duration': {u'text': u'1 min', u'value': 1}, u'end_location': {u'lat': 38.4371032, u'lng': -78.8732684}}, {u'html_instructions': u'Turn <b>left</b> onto <b>Bluestone Dr</b><div style="font-size:0.9em">Closed Mon\u2013Fri 7:00 AM \u2013 7:00 PM</div>', u'distance': {u'text': u'0.4 mi', u'value': 571}, u'travel_mode': u'DRIVING', u'maneuver': u'turn-left', u'start_location': {u'lat': 38.4371032, u'lng': -78.8732684}, u'polyline': {u'points': u'{friF||k`N?E?E@GBEP]HODMBIDQBM@I@C@K?U@KA]C]Ec@?KAECEAIACCECCQWOQAAGKGMCEGSCGAIAOAA?EAE?C?IAI@O?E?C@G@I@I@IBKDK@C@EBEDG@CDE@ADEDEDCFE@?DCDABAPCH?DAJA`ACT?L?F?dAJnCTZDH@ND'}, u'duration': {u'text': u'2 mins', u'value': 147}, u'end_location': {u'lat': 38.4347736, u'lng': -78.8701761}}, {u'html_instructions': u'Turn <b>left</b> onto <b>Carrier Dr</b><div style="font-size:0.9em">Destination will be on the right</div>', u'distance': {u'text': u'0.4 mi', u'value': 696}, u'travel_mode': u'DRIVING', u'maneuver': u'turn-left', u'start_location': {u'lat': 38.4347736, u'lng': -78.8701761}, u'polyline': {u'points': u'ixqiFrik`NBWJo@D[@K@M@[?Y?I?IA[AKAIAKAEG[Ka@EUc@eBUeAGWCGCGACACGOEGEMCIAICIAOAIAI?EAC?S?C?E@I@M?E@IBI@GBI^iA@CLc@FS@C|@{CFQ@M@I@O@Q?Q?SAMA_@Os@COCQCM?MAI?K?M@K@O@KBIBMBIBKHS'}, u'duration': {u'text': u'2 mins', u'value': 119}, u'end_location': {u'lat': 38.4346365, u'lng': -78.86271409999999}}], u'duration': {u'text': u'4 mins', u'value': 267}, u'end_location': {u'lat': 38.4346365, u'lng': -78.86271409999999}}]}]) #overview_points = "cgriFt|k`NFF?E@Md@aALi@Do@IkBGa@}@sAQk@E]?g@B[Lk@LWNQTO`@K|AGb@?lAJjDZXFVoBBmAE{@WoAsAqFWo@Im@Cg@Ba@Fa@r@{BnAeEFy@CsA[cBAq@Hq@Tw@" #Real lines to get polyline from googles servers directions = client.directions(use_client, start_string, end_string, transit_mode=mode) overview_points = directions[0]["overview_polyline"]["points"] points = polyline.decode( overview_points) #uses polyline package to decode. return points
def main(user_location, destination): """ Returns polyline of safest route :param user_location: list or tuple of latitude, longitude coordinates (lat, lng) :param destination: list or tuple of latitude, longitude coordinates(lat, lng) :return: """ utcrime = load_data() crime_weights = generate_crime_weights(utcrime.df) subregion_weights = generate_subregion_weights(utcrime, crime_weights) api_key = 'AIzaSyDmKbjLrlWQowWVzzTy_AAWsFQO4Hdbeko' cli = client.Client(key=api_key) gmap_routes = route_generator(user_location, destination, cli) point_routes = convert_to_point_routes(gmap_routes) scores = score_routes(point_routes, gmap_routes, subregion_weights) safe_route = safest_route(scores) route = gmap_routes[safe_route] if type(route) is dict: # alternative route, indexes differently than waypoint route polyline = route['overview_polyline']['points'] else: # waypoint route, indexes differently than alternative route polyline = route[0]['overview_polyline']['points'] return polyline
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 get_elevations(self, points): """ :param points: list of points (lat/long tuple) :return: list of lat/long/elevation tuples """ use_client = client.Client(key=google_elevation_key) elevations = client.elevation(use_client, points) new_list = [] for elevation in elevations: new_list.append( (elevation["location"]["lat"], elevation["location"]["lng"], elevation["elevation"])) return new_list
from setting import * from math import radians, cos, sin, asin, sqrt from googlemaps import distance_matrix, client # sql seting conn = mysql.connector.connect( host='localhost', port=3306, user='******', password=MYSQL_PW, database='anone', ) # google map distance matrix api setting gmap_client = client.Client(key=GOOGLE_MAPS_DISTANCE_MATRIX_API_Key) # keep sql connection conn.ping(reconnect=True) def haversine(lng1, lat1, lng2, lat2): """緯度経度から直線距離を求める :param lng1: float, 経度1 :param lat1: float, 緯度1 :param lng2: float, 経度2 :param lat2: float, 緯度2 :return: float, 直線距離(km) """ lat1 = float(lat1) lat2 = float(lat2)
def __init__(self, key=gmaps_api_key, units="imperial"): self.key = key self.units = units self.client = client.Client(self.key)
from googlemaps import client, geocoding from config import Config """ Module to get coordinates of a given address. """ gm_client = client.Client(key=Config.GOOGLE_API_KEY) def get_coordinates(address): """ Get coordinates. :param address: Returned address from 'input.get_address()' :return: A set of coordinates """ geocode_result = geocoding.geocode(gm_client, address) if geocode_result: coordinates = { "address": address, "street": "", "city": "", "formatted_address": geocode_result[0]['formatted_address'], "lat": geocode_result[0]['geometry']['location']['lat'], "lng": geocode_result[0]['geometry']['location']['lng'], "place_id": geocode_result[0]['place_id'], "status": "OK" } # If the first component of an address is a locality (city). if geocode_result[0]['address_components'][0]['types'] == [ 'locality', 'political' ]: coordinates['city'] = geocode_result[0]['address_components'][0][
import os import sys import click from googlemaps import client, geocoding, distance_matrix # TODO Decorate(?)/wrap the click functions to apply this suffix automatically CLI_PROMPT_SUFFIX = "\n" # TODO Is there a way to group the __main__ handling in the main block? # TODO Determine a reasonable Maps timeout; default is no per-request timeout # and 60 seconds total for retriable requests # TODO Also support the client key and ID pair try: # TODO Should I uppercase this variable name? MAPS_CLIENT = client.Client(key=os.environ["GOOGLE_API_KEY"]) except KeyError: if __name__ == "__main__": sys.stderr.write("Please set the environment variable GOOGLE_API_KEY") sys.exit(1) raise class UserCommute(object): """Current commute data directly provided by a user. All attributes are required. Attributes: commute_starting_address (str): Any address that can be geocoded by Google Maps for distance and directions
h['Access-Control-Allow-Origin'] = origin h['Access-Control-Allow-Methods'] = get_methods() h['Access-Control-Max-Age'] = str(max_age) h['Access-Control-Allow-Credentials'] = 'true' h['Access-Control-Allow-Headers'] = \ "Origin, X-Requested-With, Content-Type, Accept, Authorization" if headers is not None: h['Access-Control-Allow-Headers'] = headers return resp f.provide_automatic_options = False return update_wrapper(wrapped_function, f) return decorator api = client.Client(key=environ.get('GOOGLE_MAPS_SERVER_API_KEY')) # Function to abstract reversing a location def place_from_location_string(location_string): """Returns a human-readable place name given a string of coordinates.""" location = [float(component) for component in location_string.split(' ')] return reverse_geocode(api, location)[0]['formatted_address'] # Function to abstract getting directions def google_maps_directions(start, end, **kwargs): """Returns directions from Google Maps.""" return directions(api, start, end, **kwargs)
def __init__(self): """ Start with APi parameters """ LBSociam.__init__(self) self.client = client.Client(key=self.gmaps_api_key)
import psycopg2 from googlemaps import client import sys key= "A GOOGLE API KEY AUTHORIZED ON SEVERAL DIRECTIONS APIS" myClient = client.Client(key) def getRoutes(cursor) : valsToText = [] cursor.execute("""select * from person""") person=cursor.fetchone() while(person): [minCluster,minDirections] = getClosestCluster(cursor,person) urlForRoute = getURLForRoute(cursor, minDirections,person) valsToText.append([person[1], urlForRoute]) person = cursor.fetchone() return valsToText def getClosestCluster(cursor,person) : cursor.execute("""select * from cluster""") cluster = cursor.fetchone() minDistance = sys.maxsize minCluster = None minDirections = None while(cluster): directions = myClient.directions(getCoordsForGoogle(person[2],person[3]),getCoordsForGoogle(cluster[1],cluster[2]),alternatives=True) distance = directions[0].get('legs')[0].get('duration').get('value') if(distance<minDistance): minDistance=distance minCluster=cluster minDirections = directions