Beispiel #1
0
    def distance(source, destination, distance_in=None):
        """ This function use to get distance between two address.

        Args:
        source (string/list): Source address string/ lat, lng as list.
        destination (string/list): Destination address string/ lat, lng as list.
        distance_in(string): Type of distance. Example: meter, kelometer, miles.

        Returns:
        Float: Distance The return value. """
        # Initialize return value.
        return_value = 0
        try:
            origin = (source['longitude'], source['latitude'])
            destination = (destination['longitude'], destination['latitude'])
            # Call mapbox client to get direction services.
            response = Directions(MAPBOX_TOKEN["mapbox_token"]).directions(
                [origin, destination])
            driving_routes = response.geojson()
            distances = driving_routes['features'][0]['properties']["distance"]
            if not distance_in:
                return_value = distances * 0.00062137
            elif distance_in == "kelometer":
                return_value = round(distances / 1000, 2)
        except BaseException:
            return_value = 0
        return return_value
Beispiel #2
0
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)
Beispiel #3
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"
Beispiel #4
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)
Beispiel #5
0
 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
Beispiel #7
0
    def geoMessage(self, bot, update):
        bot.send_message(chat_id=update.message.chat_id,
                         text="What is your origin?")
        origin = update.message.text
        # time = time.time(20)
        bot.send_message(chat_id=update.message.chat_id,
                         text="What is your destination?")
        destination = update.message.text
        geocoder = mapbox.Geocoder(
            access_token=
            'sk.eyJ1IjoiZGlhbmthbG9sNCIsImEiOiJjazhzdjE4c3QwMnlwM2Rud2EwZzg1b29iIn0.OqtyNqmiJI5q6UbWQC6oCQ'
        )
        response = geocoder.forward('Paris, France')
        with open('text.json', 'w', encoding='UTF-8') as f:
            json.dump(response.json(), f)

        from mapbox import Directions
        resp = Directions('mapbox.driving').directions([origin, destination])
        driving_routes = resp.geojson()
        first_route = driving_routes['features'][0]
        bot.send_message(chat_id=update.message.chat_id, pic=resp)
Beispiel #8
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')
Beispiel #10
0
import json
from flask import request, jsonify
from clean_fit.models import Users, Route, PlaceInfo, CleanCityIndex, History
from clean_fit import app, db
from flask_cors import CORS, cross_origin
from mapbox import Directions
import os
import math
import random
import datetime
from copy import deepcopy
import datetime
# from clean_fit.data_parser import parse_geo_info, parse_measures

service = Directions(
    access_token=
    'pk.eyJ1IjoicHJhbmF5a290aGFyaSIsImEiOiJja21kdTllMGoyY2VjMnBzOXA2eXBqZjJoIn0.v69swMJIzyBvXgbMHvOgGQ'
)

# frontend routes


@app.route('/', methods=["GET", "POST"])
def catch():
    return app.send_static_file('index.html')


@app.route('/go', methods=["GET", "POST"])
def catch_go():
    return app.send_static_file('index.html')

from typing import List

from mapbox import Directions

from api.routes.models import RouteSegment

service = Directions(access_token="pk.eyJ1IjoidG5hYmVyIiwiYSI6ImNqbmN5Zm"
                     "V0ODBsdXAzcW1yanVkY2xoazMifQ.r9yIImJoKcOSVhhew00aBg")


def get_polylines_from_array(arrays: List[List[float]]):
    return list(dict.fromkeys(get_lines_array(arrays)))


def get_polylines(route_points):
    return list(dict.fromkeys(get_lines(route_points)))


def get_lines_array(floats: List[List[float]]):
    coordinates = []
    coords = []
    if len(floats) >= 2:
        for i in floats:
            origin = {
                'type': 'Feature',
                'geometry': {
                    'type': 'Point',
                    'coordinates': i
                }
            }
            coords.append(origin)
Beispiel #12
0
response = service.directions([origin, destination],'mapbox/driving')
print(response.status_code)
driving_routes = response.geojson()
#print(driving_routes['features'][0]['geometry']['type'])
print(driving_routes['features'][0]['geometry']['coodinates'])
routes = driving_routes['features'][0]['geometry']['coodinates'];
print(routes.type)'''

from mapbox import Directions
import pandas as pd
import plotly.express as px
import plotly.io as pio
import plotly.offline as pyo
import plotly.graph_objects as go

service = Directions(access_token="")

origin = {
    'type': 'Feature',
    'properties': {
        'name': 'Portland, OR'
    },
    'geometry': {
        'type': 'Point',
        'coordinates': [-122.7282, 45.5801]
    }
}
destination = {
    'type': 'Feature',
    'properties': {
        'name': 'Bend, OR'
from mapbox import Geocoder, Directions
import json
from socketio import AsyncNamespace
import requests
from config import MAPBOX_ACCESS_TOKEN
import asyncio

geocoder = Geocoder(access_token=MAPBOX_ACCESS_TOKEN)
service = Directions()


async def full_route(params):
    response = service.directions([origin, destination],
                                  profile='mapbox/walking',
                                  geometries='geojson',
                                  overview=False,
                                  language=params['language'],
                                  steps=True)
    return response.json()


async def check_courier_position(profile, current_loc_coordinates, token):
    base_url = "https://api.mapbox.com"
    req = "{}/isochrone/v1/{}/{},{}?contours_minutes=1&access_token={}".format(
        base_url, profile, current_loc_coordinates[0],
        current_loc_coordinates[1], token)
    responce = requests.get(req)
    return responce.json()['features'][0]


loop = asyncio.get_event_loop()
Beispiel #14
0
import json
import time
from dbm import DBManager
import sqlite3 as db
from mapbox import Directions
import mapbox_token

DBM = DBManager('demo.db')

service = Directions(
    access_token=mapbox_token.MAPBOX_ACCESS_TOKEN)  #Mapbox API

result = DBM.read_locs()  #Get Location List to generate routes b/w them

#Builds list of possible destinations and origins in memory.
pairs = []
for loc_one in result:
    for loc_two in result:
        if (loc_one != loc_two):
            #Reformat raw db data into Mapbox Points
            point_one = {
                'type': 'Feature',
                'properties': {
                    'name': loc_one[0]
                },
                'geometry': {
                    'type': 'Point',
                    'coordinates': [loc_one[1], loc_one[2]]
                }
            }
            point_two = {
Beispiel #15
0
import mapbox
import json

geocoder = mapbox.Geocoder(
    access_token=
    'sk.eyJ1IjoiZGlhbmthbG9sNCIsImEiOiJjazhzdjE4c3QwMnlwM2Rud2EwZzg1b29iIn0.OqtyNqmiJI5q6UbWQC6oCQ'
)
response = geocoder.forward('Paris, France')
with open('text.json', 'w', encoding='UTF-8') as f:
    json.dump(response.json(), f)

from mapbox import Directions
resp = Directions('mapbox.driving').directions([origin, destination])
driving_routes = resp.geojson()
first_route = driving_routes['features'][0]
Beispiel #16
0
import os
from collections import namedtuple
from pprint import pprint
from mapbox import Geocoder, Distance, Directions
from model import db, connect_to_db, Popos, Posm


MB_ACCESS_TOKEN = os.environ['MAPBOX_ACCESS_TOKEN']
geocoder = Geocoder(access_token=MB_ACCESS_TOKEN)
service = Distance(access_token=MB_ACCESS_TOKEN)
service1 = Directions(access_token=MB_ACCESS_TOKEN)


def geocode_location(location):
    """Geocodes origin and returns lng/lat in named tuple."""

    # Forward geocoding with proximity so results are biased toward given lng/lat
    response = geocoder.forward(location, lon=-122.431, lat=37.773)
    
    if response.status_code == 200:
        first = response.geojson()['features'][0]

        origin_lng = first['geometry']['coordinates'][0]
        origin_lat = first['geometry']['coordinates'][1]

        Latlng = namedtuple('Latlng', 'latitude longitude')
        origin = Latlng(origin_lat, origin_lng)

        return origin
        # Latlng(latitude=37.792458, longitude=-122.395709)
Beispiel #17
0
#   - [email protected]
#   - http://www.ucs.louisiana.edu/~jev9637
#
# Modified:
#   * 
#
# TODO:
#   * 
###############################################################################

import numpy as np

from mapbox import Directions, Static
import folium

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')
Beispiel #18
0
from mapbox import Directions

service = Directions(access_token='pk.eyJ1IjoibXRjb2x2YXJkIiwiYSI6ImNrMDgzYndkZjBoanUzb21jaTkzajZjNWEifQ.ocEzAm8Y7a6im_FVc92HjQ')

class DirectionsCalculations:
    def returnRouteGeometry(self, waypoints_list):
        response = service.directions(waypoints_list, profile='mapbox/walking', walkway_bias=1, alley_bias=1, continue_straight=True)
        data = response.geojson()
        # print('DirectionsCalulations', data['features'])
        print('DirectionsCalulations', data)
        return data['features'][0]
Beispiel #19
0
from configmodule import ProductionConfig, DevelopmentConfig, TestingConfig

from mapbox import Directions

import os
import math
import random
import datetime

from copy import deepcopy

# instantiate the app
app = Flask(__name__)
app.config.from_object(ProductionConfig())

service = Directions(access_token=DevelopmentConfig().MAPBOX_APIKEY)
db = SQLAlchemy(app)

import models

# enable CORS
CORS(app, resources={r'/plog*': {'origins': '*'}})


def coord_list_to_linestring(coordinates):
    linestring = "LINESTRING("
    len_coords = len(coordinates)
    counter = 0
    for coord in coordinates:
        if counter == len_coords - 1:
            linestring += f'{coord[0]} {coord[1]}'
Beispiel #20
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)