def mapbox_route(origin, destination, profile):
    """
    origin (float, float): coordinates longitude, latitude, eg: (-122.7282, 45.5801)
    destination (float, float): coordinates
    profile (str): "car", "bike", or "foot"
    return RouteSummary
    """
    mbprofile = {
        "car": "mapbox/driving-traffic",
        "bike": "mapbox/cycling",
        "foot": "mapbox/walking"
    }[profile]

    service = Directions()
    response = service.directions([origin, destination], mbprofile)
    # TODO: check it went fine

    r = response.json()
    logging.debug(response.json())
    # TODO: r = response.json()
    # Get the most recommended route
    route = r["routes"][0]
    # To get the whole geometry:
    # driving_routes = response.geojson()

    if profile == "car":
        dist_km = route["distance"] / 1000
        price = PRICE_PER_KM_CAR * dist_km
        co2 = CO2_PER_KM_CAR * dist_km
    else:
        price = 0
        co2 = 0
    return RouteSummary(profile, route["distance"], route["duration"], price,
                        co2)
Exemple #2
0
def directionRoute():
    if request.method == 'POST' or request.method == 'GET':
        data = request.get_json()
        src = data['start']
        dest = data['end']
        pro = data['profile']
        '''src=request.form['src']
                dest=request.form['dest']
                pro=request.form['pro']'''
        Profile = 'mapbox/' + pro
        PRofile = 'mapbox.' + pro
        MAPBOX_ACCESS_TOKEN = 'pk.eyJ1IjoidmluaXRoYS1zaHJlZSIsImEiOiJjamJ0ZW1yc24xMzB2Mnp1ZnVhazB6MnVzIn0.ynemM-bZ9mc4C9PuasnVow'
        geocoder = Geocoder(access_token=MAPBOX_ACCESS_TOKEN)
        #geocoder.session.params['access_token'] == 'sk.eyJ1IjoidmluaXRoYS1zaHJlZSIsImEiOiJjamNjMjkzZ3MwbTc0MndvMndtM2Ewb3lxIn0.cm3yhsou3E8UD0pm1GPKlA'
        geocode1 = geocoder.forward(src)
        src_geocode = geocode1.json()
        src1_geocode = json.dumps(src_geocode)
        geocode2 = geocoder.forward(dest)
        dest_geocode = geocode2.json()
        src_latlng = src_geocode["features"][0]['geometry']['coordinates']
        dest_latlng = dest_geocode['features'][0]['geometry']['coordinates']
        print(src_latlng)
        print(dest_latlng)
        origin = {
            'type': 'Feature',
            'properties': {
                'name': 'dummy'
            },
            'geometry': {
                'type': 'Point',
                'coordinates': [0, 0]
            }
        }
        origin['properties']['name'] = src
        origin['geometry']['coordinates'] = src_latlng
        destination = {
            'type': 'Feature',
            'properties': {
                'name': 'dummy'
            },
            'geometry': {
                'type': 'Point',
                'coordinates': [0, 0]
            }
        }
        destination['properties']['name'] = dest
        destination['geometry']['coordinates'] = dest_latlng
        print(origin)
        print(destination)
        services = Directions(access_token=MAPBOX_ACCESS_TOKEN)
        responses = services.directions([origin, destination], PRofile)
        directions_status = responses.status_code
        print(directions_status)
        directions_type = responses.headers['Content-Type']
        print(directions_type)
        directionResponse_json = responses.json()
        #print(directionResponse_json)
        return json.dumps(directionResponse_json)
    return "works bad"
Exemple #3
0
def output():

    #get the lat/long of origin and destination
    geocoder = Geocoder()
    geocoder.session.params['access_token'] = 'pk.eyJ1IjoiYWNiYXR0bGVzIiwiYSI6ImNrNXptdWtnajA4ZGYzamxscmR5ZmV4ZGEifQ.e99budVtY2MsprEhvTNEtQ'
    directions = Directions()
    directions.session.params['access_token'] = 'pk.eyJ1IjoiYWNiYXR0bGVzIiwiYSI6ImNrNXptdWtnajA4ZGYzamxscmR5ZmV4ZGEifQ.e99budVtY2MsprEhvTNEtQ'

    starting_location = request.args.get('starting_location')
    ending_location = request.args.get('ending_location')

    #Auto input, if fields left blank
    if starting_location == '':
        start_geo = geocoder.forward('200 E Colfax Ave, Denver, CO 80203')
    else:
        start_geo = geocoder.forward(starting_location)

    if ending_location == '':
        end_geo = geocoder.forward('7711 E Academy Blvd, 80230')
    else:
        end_geo = geocoder.forward(ending_location)
    
    origin = start_geo.geojson()['features'][0]
    destination = end_geo.geojson()['features'][0]

    route = directions.directions([origin,destination], 'mapbox/driving', alternatives=True, exclude = 'motorway')
    route1 = route.geojson()['features'][0]
    route2 = route.geojson()['features'][1]

    #makes a list of the start/end coordinates on each line segment of the route
    coord_points_alt1 = route1['geometry']['coordinates']
    coord_points_alt2 = route2['geometry']['coordinates']

    #get the coordinates for TURNS (at this point)
    intersections_df1 = geodb_query(coord_points_alt1)
    intersections_df2 = geodb_query(coord_points_alt2)

    #get the relative risk at each turn.
    total_risk1 = intersections_df1['Pred_Prob'].sum()
    total_risk2 = intersections_df2['Pred_Prob'].sum()

    
    if total_risk1 < total_risk2:
        best_route = route1
        next_route = route2
        risk_out_low = round(total_risk1,1)
        risk_out_high = round(total_risk2,1)
        
    else:
        best_route = route2
        next_route = route1
        risk_out_low = round(total_risk2,1)
        risk_out_high = round(total_risk1,1)
    
    risk_proportion = round(((1-(risk_out_low/risk_out_high))*100),1)

    return render_template("output.html", routeA = best_route, routeB = next_route, origin = origin, destination = destination,
    risk1 = risk_out_low, risk2 = risk_out_high, risk_proportion = risk_proportion)
 def snap_to_road(received_point):
     service = Directions()
     coords = [received_point.lng, received_point.lat]
     origin = destination = {
         "type": "Feature",
         "geometry": {
             "type": "LineString",
             "coordinates": [coords, coords]
         }    
     }
     response = service.directions([origin, destination], profile='mapbox.driving')
     try:
         coordinates = response.geojson()['features'][0]['geometry']['coordinates'][0]
     except IndexError:
         return received_point
     received_point.lat = coordinates[1]
     received_point.lng = coordinates[0]
     received_point.save()
     return received_point
def get_Directions_Mapbox(from_location, to_location, api_key):
    service = Directions(access_token=api_key)
    origin = Feature(geometry=Point((from_location.longitude,
                                     from_location.latitude)))
    destination = Feature(geometry=Point((to_location.longitude,
                                          to_location.latitude)))
    #my_profile = 'mapbox/driving'
    my_profile = 'mapbox/driving-traffic'
    response = service.directions([origin, destination],
                                  profile=my_profile,
                                  geometries=None,
                                  annotations=['duration', 'distance'])
    driving_routes = response.geojson()
    #print("JSON Object: ", driving_routes, file=sys.stderr)
    #new_json = driving_routes['features'][0]['properties']
    #pprint.pprint(new_json)
    if response.status_code == 200:
        return driving_routes['features'][0]['properties']
    else:
        return response.status_code
Exemple #6
0
def computeDistance(stationN1, stationN2):
    def getDirectionObjects(stationN1, stationN2):
        data = getStationsData()
        dest = {"type":     "Feature",
                "geometry": {"type":        "Point",
                             "coordinates": [None, None]}}
        orig = {"type":     "Feature",
                "geometry": {"type":        "Point",
                             "coordinates": [None, None]}}
        for station in data:
            if station["number"] == stationN1:
                orig["geometry"]["coordinates"][1] = station["position"]["lng"]
                orig["geometry"]["coordinates"][0] = station["position"]["lat"]
            elif station["number"] == stationN2:
                dest["geometry"]["coordinates"][1] = station["position"]["lng"]
                dest["geometry"]["coordinates"][0] = station["position"]["lat"]
            if orig["geometry"]["coordinates"][0] != None and \
               dest["geometry"]["coordinates"][0] != None:
                break
        return [orig, dest]

    service = Directions(MAPBOX_TOKEN)
    response = service.directions(getDirectionObjects(stationN1, stationN2),
                                  PROFILE)
    try:
        response.raise_for_status()
    except:
        print("Error %d occured while retreiving answer from server"
              %response.status_code, file=stderr)
        exit(EXIT_FAILURE)
    try:
        response = loads(response.text)
    except TypeError or ValueError:
        print("Incorrect data formating collected from:\n  %s" %URL_DATA,
              file=stderr)
        exit(EXIT_FAILURE)
    return response["routes"][0]["distance"]
def gps_point_to_routes(points_from_file: str, dump_to='routes.geojson'):
    get_direct = Directions(access_token=TOKEN)

    with open(points_from_file, 'r') as cat:
        data = geojson.load(cat).copy()

    end_points = data['features']

    if len(end_points) <= 25:
        resp = get_direct.directions(walkway_bias=1,
                                     profile='mapbox/walking',
                                     features=end_points,
                                     geometries='geojson')
        print(resp.status_code)
        print(resp.url)

        new_data = resp.json()
        geom = new_data['routes'][-1]['geometry']
        line = LineString(geom['coordinates'])

        route_df = gpd.GeoDataFrame(geometry=[line])
        route_df.to_file(dump_to, driver='GeoJSON', encoding="utf-8")
    else:
        print('many points in data')
Exemple #8
0
        'type': 'Point',
        'coordinates': [-122.7282, 45.5801]
    }
}
destination = {
    'type': 'Feature',
    'properties': {
        'name': 'Bend, OR'
    },
    'geometry': {
        'type': 'Point',
        'coordinates': [-121.3153, 44.0582]
    }
}

response = service.directions([origin, destination], 'mapbox/driving')
print(response.status_code)
driving_routes = response.geojson()

waypoints = driving_routes['features'][0]['geometry']['coordinates']

df = pd.DataFrame(waypoints, columns=['long', 'lat'])

fig = go.Figure(
    go.Scattermapbox(mode="markers+lines",
                     lon=df.iloc[:, 0],
                     lat=df.iloc[:, 1],
                     marker={'size': 40},
                     fillcolor='blue'))

fig.update_layout(mapbox={
Exemple #9
0
direction_service = Directions(access_token='pk.eyJ1IjoiZG9jdmF1Z2hhbiIsImEiOiI1NXdlS184In0.xkx1iJIxebVhEXFS8cadrg')
static_service = Static(access_token='pk.eyJ1IjoiZG9jdmF1Z2hhbiIsImEiOiI1NXdlS184In0.xkx1iJIxebVhEXFS8cadrg')

origin = {'type': 'Feature',
          'properties': {'name': 'Rougeou Hall'},
          'geometry': {
          'type': 'Point',
          'coordinates': [-92.0224611, 30.2096914]}}
          
destination = {'type': 'Feature',
               'properties': {'name': 'Martin Hall'},
                'geometry': {
                'type': 'Point',
                'coordinates': [-92.0189939, 30.215553]}}
                
response = direction_service.directions([origin, destination], 'mapbox.walking')

path =  response.geojson()['features'][0]['geometry']['coordinates']


# Get the start and end locations from the 
start = [origin['geometry']['coordinates'][1], origin['geometry']['coordinates'][0]]
end = [destination['geometry']['coordinates'][1], destination['geometry']['coordinates'][0]]

# Set up base map
mymap = folium.Map(location = start, tiles= 'MapBox', 
                   API_key='docvaughan.iia856df', 
                   zoom_start=16, 
                   height=1200, 
                   width = 1800)
Exemple #10
0
def output():
    # get origin and destination geolocations
    key = config.mapbox['key']
    geocoder = Geocoder()
    geocoder.session.params['access_token'] = key
    directions = Directions()
    directions.session.params['access_token'] = key

    startname = request.args.get('origin')
    endname = request.args.get('destination')
    if startname == '' or endname == '':
        startname = 'Punxsutawney, PA'
        endname = 'State College, PA'

    startresponse = geocoder.forward(startname)
    endresponse = geocoder.forward(endname)
    origin = startresponse.geojson()['features'][0]
    destination = endresponse.geojson()['features'][0]
    response = directions.directions([origin, destination], 'mapbox/driving')

    coords = response.geojson()['features'][0]['geometry']['coordinates']
    shapely_line = LineString(coords)
    midpoint = shapely_line.interpolate(0.5, normalized=True).coords[:][0]
    line = '[' + ','.join(["[{},{}]".format(lat, lon)
                           for lat, lon in coords]) + ']'

    # Splitting shapely_line
    line_list = split_line(shapely_line)
    # Get features from overpass
    feature_df = overpass_query(line_list)
    #feature_df = feature_df.reindex(sorted(feature_df.columns), axis=1)
    feature_df.to_csv('debugging.csv')
    # Make prediction
    predictions = loaded_model.predict(feature_df)
    #predictions = [.2, .7, .8, .2]
    print(predictions)
    # Make pretty colors
    #colorstring = process_line_colors(predictions)
    colors_segments = process_line_colors(predictions)
    print(colors_segments)
    #print('COLORSTRING\n{}'.format(colors_segments))

    #pull 'date' from input field and store it
    drive_date = request.args.get('date')
    drive_date = pd.to_datetime(drive_date)
    hour, minute = request.args.get('time').split(":")
    minute = float(minute) / 60
    hour = float(hour) + minute
    #drive_time = int(request.args.get('time'))/100

    idx = test.index.get_loc(drive_date, method='nearest')
    date_prob = test.iloc[idx].values[0]
    time_prob = deer_time(hour)
    time_multiplier = (date_prob * time_prob * 1)
    if time_multiplier > 0.5:
        color = "red"
    else:
        color = "blue"

    #print(color)

    return render_template("output.html",
                           line=line,
                           lat=midpoint[0],
                           lon=midpoint[1],
                           colors_segments=colors_segments)