Exemplo n.º 1
0
def test_direction_params():
    params = "&alternatives=false&geometries=polyline&overview=false&steps=false" \
             "&continue_straight=false&annotations=distance%2Cspeed&language=en" \
             "&radiuses=10%3Bunlimited"

    responses.add(
        responses.GET,
        'https://api.mapbox.com/directions/v5/mapbox/driving/'
        '-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test'
        + params,
        match_querystring=True,
        body="not important, only testing URI templating",
        status=200,
        content_type='application/json')

    res = mapbox.Directions(access_token='pk.test').directions(
        points,
        alternatives=False,
        geometries='polyline',
        overview=False,
        continue_straight=True,
        annotations=['distance', 'speed'],
        language='en',
        waypoint_snapping=[10, 'unlimited'],
        steps=False)
    assert res.status_code == 200
Exemplo n.º 2
0
def directions(ctx, features, geojson, profile, alternatives,
               instructions, geometry, steps, output):
    """Calculate optimal route with turn-by-turn directions
    between up to 25 waypoints.

      $ mapbox directions "[-122.681032, 45.528334]" "[-122.71679, 45.525135]"

    An access token is required, see `mapbox --help`.
    """
    stdout = click.open_file(output, 'w')
    access_token = (ctx.obj and ctx.obj.get('access_token')) or None
    if geojson:
        geometry = 'geojson'

    service = mapbox.Directions(access_token=access_token)

    try:
        res = service.directions(
            features,
            steps=steps,
            alternatives=alternatives,
            instructions=instructions,
            geometry=geometry,
            profile=profile)
    except mapbox.errors.ValidationError as exc:
        raise click.BadParameter(str(exc))

    if res.status_code == 200:
        if geojson:
            click.echo(json.dumps(res.geojson()), file=stdout)
        else:
            click.echo(res.text, file=stdout)
    else:
        raise MapboxCLIException(res.text.strip())
Exemplo n.º 3
0
def directions(ctx, features, profile, alternatives, 
               geometries, overview, steps, continue_straight, 
               waypoint_snapping, annotations, language, output):
    """The Mapbox Directions API will show you how to get
       where you're going.

       mapbox directions "[0, 0]" "[1, 1]"

       An access token is required.  See "mapbox --help".
    """

    access_token = (ctx.obj and ctx.obj.get("access_token")) or None

    service = mapbox.Directions(access_token=access_token)

    # The Directions SDK expects False to be
    # a bool, not a str.

    if overview == "False":
        overview = False

    # When using waypoint snapping, the 
    # Directions SDK expects features to be 
    # a list, not a generator.

    if waypoint_snapping is not None:
        features = list(features)

    if annotations:
        annotations = annotations.split(",")

    stdout = click.open_file(output, "w")

    try:
        res = service.directions(
            features,
            profile=profile,
            alternatives=alternatives,
            geometries=geometries,
            overview=overview,
            steps=steps,
            continue_straight=continue_straight,
            waypoint_snapping=waypoint_snapping,
            annotations=annotations,
            language=language
        )
    except mapbox.errors.ValidationError as exc:
        raise click.BadParameter(str(exc))

    if res.status_code == 200:
        if geometries == "geojson":
            click.echo(json.dumps(res.geojson()), file=stdout)
        else:
            click.echo(res.text, file=stdout)
    else:
        raise MapboxCLIException(res.text.strip())
Exemplo n.º 4
0
def trip(df):
    token = config.plotly_key
    directions_api = mapbox.Directions(access_token=token)
    df_tour['Winery'] = df_tour.index
    feat = df_to_geojson(df_tour, properties=['Winery'])
    feat['features'].append({
        'geometry': {
            'coordinates': [-121.945778, 37.281630],
            'type': 'Point'
        },
        'properties': {
            'Winery': 'Home'
        },
        'type': 'Feature'
    })
    res = directions_api.directions(feat['features'])

    data = Data([
        Scattermapbox(
            lat=[
                item_x[1] for item_x in res.geojson()['features'][0]
                ['geometry']['coordinates']
            ],
            lon=[
                item_y[0] for item_y in res.geojson()['features'][0]
                ['geometry']['coordinates']
            ],
            mode='markers+lines',
            marker=Marker(size=3),
        ),
        (Scattermapbox(lon=df_tour['Lon'],
                       lat=df_tour['Lat'],
                       mode='markers',
                       hoverinfo='text',
                       marker=Marker(color='purple', size=12),
                       text=df_tour['Winery'],
                       name='Stops'))
    ])
    layout = Layout(
        margin=dict(t=0, b=0, r=0, l=0),
        autosize=True,
        hovermode='closest',
        showlegend=False,
        mapbox=dict(accesstoken=token,
                    bearing=0,
                    center=dict(lat=37, lon=-122),
                    pitch=0,
                    zoom=8,
                    style='outdoors'),
    )

    fig = dict(data=data, layout=layout)
    py_off.plot(fig, filename='tour.html')
Exemplo n.º 5
0
def test_direction_bearings_none():
    responses.add(
        responses.GET, 'https://api.mapbox.com/directions/v5/mapbox/driving/'
        '-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test'
        '&radiuses=10%3B20&bearings=%3B315%2C90',
        match_querystring=True,
        body="not important, only testing URI templating",
        status=200,
        content_type='application/json')

    res = mapbox.Directions(access_token='pk.test').directions(
        points, waypoint_snapping=[10, (20, 315, 90)])
    assert res.status_code == 200
Exemplo n.º 6
0
def test_directions(cache):
    with open('tests/moors.json') as fh:
        body = fh.read()

    responses.add(
        responses.GET,
        'https://api.mapbox.com/v4/directions/mapbox.driving/-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test',
        match_querystring=True,
        body=body, status=200,
        content_type='application/json')

    res = mapbox.Directions(access_token='pk.test', cache=cache).directions(points)
    assert res.status_code == 200
    assert sorted(res.json()['routes'][0].keys()) == ['distance', 'duration', 'geometry', 'steps', 'summary']
    assert sorted(res.json().keys()) == ['destination', 'origin', 'routes', 'waypoints']
Exemplo n.º 7
0
def test_directions_geojson():
    with open('tests/moors.json') as fh:
        body = fh.read()

    responses.add(
        responses.GET, 'https://api.mapbox.com/directions/v5/mapbox/driving/'
        '-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test',
        match_querystring=True,
        body=body,
        status=200,
        content_type='application/json')

    res = mapbox.Directions(access_token='pk.test').directions(points)
    fc = res.geojson()
    assert fc['type'] == 'FeatureCollection'
    assert fc['features'][0]['geometry']['type'] == 'LineString'
Exemplo n.º 8
0
def test_directions(cache):
    with open('tests/moors.json') as fh:
        body = fh.read()

    responses.add(
        responses.GET,
        'https://api.mapbox.com/directions/v5/mapbox/driving/' +
        '-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test',
        match_querystring=True,
        body=body,
        status=200,
        content_type='application/json')

    res = mapbox.Directions(access_token='pk.test',
                            cache=cache).directions(points)
    assert res.status_code == 200
    assert 'distance' in res.json()['routes'][0].keys()
Exemplo n.º 9
0
def test_direction_params():
    params = "&alternatives=false&instructions=html&geometry=polyline&steps=false"

    responses.add(
        responses.GET,
        'https://api.mapbox.com/v4/directions/mapbox.driving/-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test' + params,
        match_querystring=True,
        body="not important, only testing URI templating", status=200,
        content_type='application/json')

    res = mapbox.Directions(access_token='pk.test').directions(
        points,
        alternatives=False,
        instructions='html',
        geometry='polyline',
        steps=False)
    assert res.status_code == 200
Exemplo n.º 10
0
def distanca(mesto):
    destination = str(mesto) + ', Serbia'
    map = mapbox.Geocoder(
        access_token=
        "pk.eyJ1IjoiZHVoaXpqYW1lIiwiYSI6ImNrZHhzdGxvbDM0aGkyd21xNHVleTByajUifQ.esMht2IXyPcuICHLA9vl2Q"
    )
    d_code = map.forward(destination)
    dest = d_code.json()
    for z in dest['features']:
        print(z)
        print("============================================")
    beograd = map.forward("Belgrade, Serbia")

    bg_json = beograd.json()

    destination = {
        'type': 'Feature',
        'properties': {
            'name': destination
        },
        'geometry': {
            'type': 'Point',
            'coordinates': dest['features'][0]['center']
        }
    }
    service = mapbox.Directions(
        access_token=
        "pk.eyJ1IjoiZHVoaXpqYW1lIiwiYSI6ImNrZHhzdGxvbDM0aGkyd21xNHVleTByajUifQ.esMht2IXyPcuICHLA9vl2Q"
    )

    origin = {
        'type': 'Feature',
        'properties': {
            'name': "Belgrade, Serbia"
        },
        'geometry': {
            'type': 'Point',
            'coordinates': bg_json['features'][0]['center']
        }
    }
    directions = service.directions([origin, destination])
    dir_json = directions.json()
    distance = dir_json['routes'][0]['legs'][0]['distance'] / 1000
    print(distance)
Exemplo n.º 11
0
def test_direction_backwards_compat():
    """Ensure old calls to directions method work against v5 API
    """
    responses.add(
        responses.GET, 'https://api.mapbox.com/directions/v5/mapbox/cycling/'
        '-87.337875%2C36.539157%3B-88.247681%2C36.922175.json?access_token=pk.test'
        '&geometries=polyline',
        match_querystring=True,
        body="not important, only testing URI templating",
        status=200,
        content_type='application/json')

    res = mapbox.Directions(access_token='pk.test').directions(
        points,
        geometry='polyline',  # plural in v5
        profile='mapbox.cycling',  # '/' delimited in v5
    )
    # TODO instructions parameter removed in v5
    assert res.status_code == 200
Exemplo n.º 12
0
def test_invalid_bearing_tuple():
    service = mapbox.Directions(access_token='pk.test')
    with pytest.raises(mapbox.errors.InvalidParameterError) as e:
        service._validate_snapping([(270, 45, 'extra'), (315, )], points)
        assert 'bearing tuple' in str(e)
Exemplo n.º 13
0
def distanca(mesto):
    destination = str(mesto).replace('đ','dj') + ', Serbia'
    db = sqlite3.connect("placesDB.db")
    map = mapbox.Geocoder(access_token="pk.eyJ1IjoiZHVoaXpqYW1lIiwiYSI6ImNrZHhzdGxvbDM0aGkyd21xNHVleTByajUifQ.esMht2IXyPcuICHLA9vl2Q")
    d_code = map.forward(destination)
    dest = d_code.json()
    y = 0
    nasao = False
    while(dest['features'][int(y)]['place_type']!=["place"] or dest['features'][int(y)]['place_type']!=["region"]  or dest['features'][int(y)]['text']=="Serbia"):
        for i,z in enumerate(dest['features']):
            if (z['place_type']==['place'] or z['place_type']==['region']) and z['text']!="Serbia":
                # print(z)
                y = i
                nasao = True
                break
        if nasao == True:
            break
        x = str(mesto).replace('đ','dj').replace('š','s').replace('ž','z').replace('č','c').replace('ć','c').replace('Đ','Dj').replace('Š','S').replace('Ž','Z').replace('Č','C').replace('Ć','C')
        execution = f"SELECT * from mesto where nazivMesta = \"{x}\""
        cursor = db.execute(execution)
        res = cursor.fetchone()
        if res is None:
            print("Can't find place in database.")
            return
        zipCode = res[0]
        while(zipCode % 100 !=0 ):
            zipCode = zipCode - 1
            cursor = db.execute(f"SELECT * from mesto where idMesta = {zipCode}")
            mesto = cursor.fetchone()
            if mesto is None:
                continue
            d_code = map.forward(str(mesto) + ', Serbia')
            dest = d_code.json()
            print(dest['features'][y]['text'])
            if (dest['features'][y]['place_type']==["place"] or dest['features'][int(y)]['place_type']==["region"]) and dest['features'][y]['text']!="Serbia":
                break
    beograd = map.forward("Belgrade, Serbia")
    novi_sad = map.forward("Novi Sad, Serbia")
    lazarevac = map.forward("Lazarevac, Serbia")

    bg_json = beograd.json()
    la_json = lazarevac.json()
    ns_json = novi_sad.json()

    origins = []
    origins.append((bg_json['features'][0]['text'],bg_json['features'][0]['center']))
    origins.append((la_json['features'][0]['text'],la_json['features'][0]['center']))
    origins.append((ns_json['features'][0]['text'],ns_json['features'][0]['center']))
    destinations = {
        'type': 'Feature',
        'properties': {'name': dest['features'][y]['text']},
        'geometry': {
            'type': 'Point',
            'coordinates': dest['features'][y]['center']
            }
        }
    service = mapbox.Directions(access_token="pk.eyJ1IjoiZHVoaXpqYW1lIiwiYSI6ImNrZHhzdGxvbDM0aGkyd21xNHVleTByajUifQ.esMht2IXyPcuICHLA9vl2Q")
    for place in origins:
        origin = {
                'type': 'Feature',
                'properties': {'name': place[0]},
                'geometry': {
                    'type': 'Point',
                    'coordinates': place[1]
                    }
                }
        directions = service.directions([origin,destinations])
        dir_json = directions.json()
        distance = dir_json['routes'][0]['legs'][0]['distance']/1000

        if int(distance) <= 165 and (str(place[0]).lower() == 'Belgrade'.lower() or str(place[0]).lower() == "Beograd".lower()):
            return True
        elif int(distance) <= 60 and str(place[0]).lower() == 'Novi Sad'.lower():
            return True
        elif int(distance) <= 80 and str(place[0]).lower() == 'Lazarevac'.lower():
            return True
    return False
Exemplo n.º 14
0
def test_invalid_geom_encoding():
    service = mapbox.Directions(access_token='pk.test')
    with pytest.raises(mapbox.errors.ValidationError):
        service._validate_geom_encoding('wkb')
Exemplo n.º 15
0
def test_invalid_profile():
    with pytest.raises(ValueError):
        mapbox.Directions(access_token='pk.test').directions(points,
                                                             profile='bogus')
Exemplo n.º 16
0
def test_bearings_without_radius():
    with pytest.raises(TypeError):
        mapbox.Directions(access_token='pk.test').directions(
            waypoint_snapping=[(270, 45), (270, 45)])
Exemplo n.º 17
0
def test_v4_profile_aliases():
    service = mapbox.Directions(access_token='pk.test')
    assert 'mapbox/cycling' == service._validate_profile('mapbox.cycling')
Exemplo n.º 18
0
def test_validate_radius_invalid():
    service = mapbox.Directions(access_token='pk.test')
    with pytest.raises(mapbox.errors.InvalidParameterError) as e:
        service._validate_radius(-1)
Exemplo n.º 19
0
def test_invalid_bearing_domain():
    service = mapbox.Directions(access_token='pk.test')
    with pytest.raises(mapbox.errors.InvalidParameterError) as e:
        service._validate_snapping([(-1, 90), (315, 90)], points)
        assert 'between 0 and 360' in str(e)
Exemplo n.º 20
0
def test_invalid_annotations():
    service = mapbox.Directions(access_token='pk.test')
    with pytest.raises(mapbox.errors.InvalidParameterError):
        service._validate_annotations(['awesomeness'])
Exemplo n.º 21
0
def test_validate_radius_none():
    service = mapbox.Directions(access_token='pk.test')
    assert service._validate_radius(None) is None
Exemplo n.º 22
0
    def post(self):
        lookup = json.loads(request.data)['address']
        geocoder = mapbox.Geocoder()
        features = json.loads(geocoder.forward(lookup).content.decode('utf-8'))['features']

        selected_feature = None
        for feature in features:
            if 'address' in feature:
                selected_feature = feature
                break
        if not selected_feature:
            return 'The is no such place on mapbox!', 400

        # print lookup
        # print selected_feature['place_name'], '@@@@@@@@'    
        # print selected_feature['relevance']

        query_set = AddressEntry.query.filter(AddressEntry.user_id==g.user_id, AddressEntry.is_dest==True, AddressEntry.is_avail==True)
        if query_set.count() == 0:
            address_entry = AddressEntry()
            address_entry.user_id = g.user_id
            address_entry.is_dest = True
            address_entry.is_avail = True
        else:
            address_entry = query_set.first()


        address_entry.name = json.loads(request.data)['spot_name']
        address_entry.longitude = selected_feature['center'][0]
        address_entry.latitude = selected_feature['center'][1]
        address_entry.street_number = selected_feature['address']
        address_entry.street_name = selected_feature['text']
        address_entry.mapbox_place_name = selected_feature['place_name']

        # Generate a dict from
        for feature in selected_feature['context']:
            if feature['id'].startswith('place'):
                address_entry.county = feature['text']

            if feature['id'].startswith('postcode'):
                address_entry.postal_code = feature['text']

            if feature['id'].startswith('region'):
                address_entry.state = feature['text']

            if feature['id'].startswith('country'):
                address_entry.country = feature['text']

            if feature['id'].startswith('neighborhood'):
                address_entry.neighborhood = feature['text']

        db_session = db.session()
        db_session.add(address_entry)
        db_session.commit()

        origin = {
            'type': 'Feature',
            'properties': {'name': address_entry.name},
            'geometry': {
                'type': 'Point',
                'coordinates': [float(address_entry.longitude), float(address_entry.latitude)]
            }
        }

        # just for the parking spots within the threshold (20Km), create/update the distance from the destination
        for sub_address in AddressEntry.query.filter(AddressEntry.is_dest==False, AddressEntry.is_avail==True):
            distance = get_straight_distance(float(address_entry.latitude), float(address_entry.longitude), float(sub_address.latitude), float(sub_address.longitude))
            if distance > 20000:
                continue

            query_set = AddressDistance.query.filter(AddressDistance.address_a_id==address_entry.id, AddressDistance.address_b_id==sub_address.id)
            if query_set.count() == 0:
                address_distance = AddressDistance()
            else:
                address_distance = query_set.first()

            destination = {
                'type': 'Feature',
                'properties': {'name': sub_address.name},
                'geometry': {
                    'type': 'Point',
                    'coordinates': [float(sub_address.longitude), float(sub_address.latitude)],
                }
            }

            content = mapbox.Directions().directions([origin, destination],'mapbox.driving').geojson()
            address_distance.address_a_id = address_entry.id
            address_distance.address_b_id = sub_address.id
            address_distance.mapbox_response = json.dumps(content)
            address_distance.speed_scala = sum([feature['properties']['distance'] for feature in content['features']])
            db_session = db.session()
            db_session.add(address_distance)
            db_session.commit()

        return  {
                    'waypoints': AddressDistance.get_direction_pois(address_entry.id),
                    'origin': address_entry.as_geojson(True),
                }
Exemplo n.º 23
0
def sell_parking():
    if request.method == 'GET':
        spots = AddressEntry.query.filter(AddressEntry.user_id==current_user.id, AddressEntry.is_dest==False)
        return render_template('users/sell_parking.html', spots=spots)
    else:
        address_entry_form = AddressEntryForm()
        if address_entry_form.validate_on_submit():
            # Join the address fields into a single field.
            # 'address city state postal_code'
            lookup = ' '.join([address_entry_form.data['address'],
                address_entry_form.data['city'],
                address_entry_form.data['state']])

            geocoder = mapbox.Geocoder()
            features = json.loads(geocoder.forward(lookup).content.decode('utf-8'))['features']
            features = [ feature for feature in features if ('address' in feature) ]
            # Storage Convenience
            session['_price'] = address_entry_form.data.get('price', None)
            if address_entry_form.data.get('form_state', None) == 'validation':
                # Store the features in the session based off feature['id'].
                session['_geocoded_values'] = json.dumps({feature['id']:feature for feature in features })
                return jsonify({'features': features})
            else:
                abort(400) # Probably trying to do something nasty.

            address_entry_form = None

        # Frame Three Logic
        address_entry_commit_form = AddressEntryCommitForm()
        if address_entry_commit_form.validate_on_submit():
            address_entry = AddressEntry()

            if address_entry_commit_form.data.get('form_state', None) == 'commit':
                address_entry.user_id = current_user.id
                address_entry.is_dest = False
                address_entry.is_avail = True

                address_entry.price = session['_price']
                del session['_price']

                selected_feature = json.loads(session['_geocoded_values'])[address_entry_commit_form.data['picked']]
                del session['_geocoded_values'] # Clean up the session
                address_entry.longitude = selected_feature['center'][0]
                address_entry.latitude = selected_feature['center'][1]
                address_entry.street_number = selected_feature['address']
                address_entry.street_name = selected_feature['text']
                address_entry.mapbox_place_name = selected_feature['place_name']

                # address_entry.name = data.get('name')
                # Generate a dict from
                for feature in selected_feature['context']:
                    if feature['id'].startswith('place'):
                        address_entry.county = feature['text']

                    if feature['id'].startswith('postcode'):
                        address_entry.postal_code = feature['text']

                    if feature['id'].startswith('region'):
                        address_entry.state = feature['text']

                    if feature['id'].startswith('country'):
                        address_entry.country = feature['text']

                    if feature['id'].startswith('neighborhood'):
                        address_entry.neighborhood = feature['text']

                db_session = db.session()
                db_session.add(address_entry)
                db_session.commit()

                origin = {
                    'type': 'Feature',
                    'properties': {'name': address_entry.street_name},
                    'geometry': {
                        'type': 'Point',
                        'coordinates': [float(address_entry.longitude), float(address_entry.latitude)]
                    }
                }

                # just for the destinations within the threshold (20Km), create the distance from the new spot
                for sub_address in AddressEntry.query.filter(AddressEntry.is_dest==True, AddressEntry.is_avail==True):
                    distance = get_straight_distance(float(address_entry.latitude), float(address_entry.longitude), float(sub_address.latitude), float(sub_address.longitude))
                    if distance > 20000:
                        continue

                    address_distance = AddressDistance()

                    destination = {
                        'type': 'Feature',
                        'properties': {'name': sub_address.street_name},
                        'geometry': {
                            'type': 'Point',
                            'coordinates': [float(sub_address.longitude), float(sub_address.latitude)],
                        }
                    }

                    content = mapbox.Directions().directions([origin, destination],'mapbox.driving').geojson()
                    address_distance.address_a_id = sub_address.id      # destination
                    address_distance.address_b_id = address_entry.id    # parking spot
                    address_distance.mapbox_response = json.dumps(content)
                    address_distance.speed_scala = sum([feature['properties']['distance'] for feature in content['features']])
                    db_session = db.session()
                    db_session.add(address_distance)
                    db_session.commit()
                return 'success'
Exemplo n.º 24
0
def test_invalid_number_of_bearings():
    service = mapbox.Directions(access_token='pk.test')
    with pytest.raises(mapbox.errors.InvalidParameterError) as e:
        service._validate_snapping([1, 2, 3], points)
        assert 'exactly one' in str(e)
Exemplo n.º 25
0
def test_invalid_radiuses():
    service = mapbox.Directions(access_token='pk.test')
    with pytest.raises(mapbox.errors.InvalidParameterError) as e:
        service._validate_radius('forever')
        assert 'not a valid radius' in str(e)
Exemplo n.º 26
0
def test_invalid_geom_overview():
    service = mapbox.Directions(access_token='pk.test')
    with pytest.raises(mapbox.errors.InvalidParameterError):
        service._validate_geom_overview('infinite')
Exemplo n.º 27
0
def _update_users_address():
    # Frame Two Logic
    address_entry_form = AddressEntryForm()
    if address_entry_form.validate_on_submit():
        # Join the address fields into a single field.
        # 'address city state postal_code'
        lookup = ','.join([address_entry_form.data['address'],
            address_entry_form.data['city'],
            address_entry_form.data['state'],
            address_entry_form.data['postal_code']])

        geocoder = mapbox.Geocoder()
        features = json.loads(geocoder.forward(lookup).content.decode('utf-8'))['features']
        features = [ feature for feature in features if ('address' in feature) ]
        # Storage Convenience
        session['_phone'] = address_entry_form.data.get('phone', None)
        session['_building_name'] = address_entry_form.data.get('building_name', None)
        if address_entry_form.data.get('form_state', None) == 'validation':
            # Store the features in the session based off feature['id'].
            session['_geocoded_values'] = json.dumps({feature['id']:feature for feature in features })
            return jsonify({'features': features})
        else:
            abort(400) # Probably trying to do something nasty.

        address_entry_form = None

    # Frame Three Logic
    address_entry_commit_form = AddressEntryCommitForm()
    if address_entry_commit_form.validate_on_submit():
        query_set = AddressEntry.query.filter(AddressEntry.user_id==current_user.id)
        if query_set.count() == 0:
            address_entry = AddressEntry()
        else:
            address_entry = query_set.first()

        if address_entry_commit_form.data.get('form_state', None) == 'commit':
            address_entry.user_id = current_user.id
            address_entry.is_dest = True
            address_entry.is_avail = True

            address_entry.name = session['_building_name']
            address_entry.phone = session['_phone']
            del session['_building_name'] # Cleanup the session
            del session['_phone'] # Cleanup the session
            # https://www.mapbox.com/help/define-lat-lon/
            # Sometimes mapbox returns long/lat or lat/long. With the Geocoding API, it seems
            #  long/lat is the format.
            # With that, make sure you double check the projections. Google will return a long in the
            #  positive specturm while mapbox will return a long in the negative spectrum. Not a problem technically,
            #  but this very question breeds hours of googling to understand the contextual differences between map
            #  providers.
            #  https://en.wikipedia.org/wiki/Map_projection
            #  https://www.mapbox.com/tilemill/docs/manual/basics/
            #  There is even some drama with the Google projections. epsg3857 and 900913 should be the same thing;
            #   but are very different when it comes to the specification. It's fun to read about. :)
            #  http://gis.stackexchange.com/questions/50347/which-is-correct-projection-in-arcgis-server-for-epsg3857-900913
            selected_feature = json.loads(session['_geocoded_values'])[address_entry_commit_form.data['picked']]
            del session['_geocoded_values'] # Clean up the session
            address_entry.longitude = selected_feature['center'][0]
            address_entry.latitude = selected_feature['center'][1]
            address_entry.street_number = selected_feature['address']
            address_entry.street_name = selected_feature['text']
            address_entry.mapbox_place_name = selected_feature['place_name']

            # address_entry.name = data.get('name')
            # Generate a dict from
            for feature in selected_feature['context']:
                if feature['id'].startswith('place'):
                    address_entry.county = feature['text']

                if feature['id'].startswith('postcode'):
                    address_entry.postal_code = feature['text']

                if feature['id'].startswith('region'):
                    address_entry.state = feature['text']

                if feature['id'].startswith('country'):
                    address_entry.country = feature['text']

                if feature['id'].startswith('neighborhood'):
                    address_entry.neighborhood = feature['text']

            db_session = db.session()
            db_session.add(address_entry)
            db_session.commit()

            origin = {
                'type': 'Feature',
                'properties': {'name': address_entry.name},
                'geometry': {
                    'type': 'Point',
                    'coordinates': [float(address_entry.longitude), float(address_entry.latitude)]
                }
            }

            # just for the parking spots within the threshold (20Km), create/update the distance from the destination
            for sub_address in AddressEntry.query.filter(AddressEntry.is_dest==False, AddressEntry.is_avail==True):
                distance = get_straight_distance(float(address_entry.latitude), float(address_entry.longitude), float(sub_address.latitude), float(sub_address.longitude))
                if distance > 20000:
                    continue

                query_set = AddressDistance.query.filter(AddressDistance.address_a_id==address_entry.id, AddressDistance.address_b_id==sub_address.id)
                if query_set.count() == 0:
                    address_distance = AddressDistance()
                else:
                    address_distance = query_set.first()

                destination = {
                    'type': 'Feature',
                    'properties': {'name': sub_address.name},
                    'geometry': {
                        'type': 'Point',
                        'coordinates': [float(sub_address.longitude), float(sub_address.latitude)],
                    }
                }

                content = mapbox.Directions().directions([origin, destination],'mapbox.driving').geojson()
                address_distance.address_a_id = address_entry.id
                address_distance.address_b_id = sub_address.id
                address_distance.mapbox_response = json.dumps(content)
                address_distance.speed_scala = sum([feature['properties']['distance'] for feature in content['features']])
                db_session = db.session()
                db_session.add(address_distance)
                db_session.commit()

    return jsonify({
        'waypoints': AddressDistance.get_direction_pois(address_entry.id),
        'origin': address_entry.as_geojson(),
    })
Exemplo n.º 28
0
def test_class_attrs():
    """Get expected class attr values"""
    serv = mapbox.Directions()
    assert serv.api_name == 'directions'
    assert serv.api_version == 'v5'
Exemplo n.º 29
0
    def post(self, action):
        spot = json.loads(request.data)
        address_entry = AddressEntry()

        address_entry.user_id = g.user_id
        address_entry.is_dest = False
        address_entry.is_avail = True
        address_entry.price = spot['price']

        address_entry.photo_url = spot['photo_url']
        address_entry.spot_type = spot['spot_type']
        address_entry.avail_type = spot['availability_type']

        # update the user's phone number
        # spot['phone']
        
        geocoder = mapbox.Geocoder()
        features = json.loads(geocoder.forward(spot['address']).content.decode('utf-8'))['features']

        selected_feature = None
        for feature in features:
            if 'address' in feature:
                selected_feature = feature
                break
        if not selected_feature:
            return 'The is no such place on mapbox!', 400

        address_entry.longitude = selected_feature['center'][0]
        address_entry.latitude = selected_feature['center'][1]
        address_entry.street_number = selected_feature['address']
        address_entry.street_name = selected_feature['text']
        address_entry.mapbox_place_name = selected_feature['place_name']

        # address_entry.name = data.get('name')
        # Generate a dict from
        for feature in selected_feature['context']:
            if feature['id'].startswith('place'):
                address_entry.county = feature['text']

            if feature['id'].startswith('postcode'):
                address_entry.postal_code = feature['text']

            if feature['id'].startswith('region'):
                address_entry.state = feature['text']

            if feature['id'].startswith('country'):
                address_entry.country = feature['text']

            if feature['id'].startswith('neighborhood'):
                address_entry.neighborhood = feature['text']

        db_session = db.session()
        db_session.add(address_entry)
        db_session.commit()

        origin = {
            'type': 'Feature',
            'properties': {'name': address_entry.street_name},
            'geometry': {
                'type': 'Point',
                'coordinates': [float(address_entry.longitude), float(address_entry.latitude)]
            }
        }

        # just for the destinations within the threshold (20Km), create the distance from the new spot
        for sub_address in AddressEntry.query.filter(AddressEntry.is_dest==True, AddressEntry.is_avail==True):
            distance = get_straight_distance(float(address_entry.latitude), float(address_entry.longitude), float(sub_address.latitude), float(sub_address.longitude))
            if distance > 20000:
                continue

            address_distance = AddressDistance()

            destination = {
                'type': 'Feature',
                'properties': {'name': sub_address.street_name},
                'geometry': {
                    'type': 'Point',
                    'coordinates': [float(sub_address.longitude), float(sub_address.latitude)],
                }
            }

            content = mapbox.Directions().directions([origin, destination],'mapbox.driving').geojson()
            address_distance.address_a_id = sub_address.id      # destination
            address_distance.address_b_id = address_entry.id    # parking spot
            address_distance.mapbox_response = json.dumps(content)
            address_distance.speed_scala = sum([feature['properties']['distance'] for feature in content['features']])
            db_session = db.session()
            db_session.add(address_distance)
            db_session.commit()
        return 'success'
Exemplo n.º 30
0
def test_snapping_radii_none():
    service = mapbox.Directions(access_token='pk.test')
    bearings, radii = service._validate_snapping([(10, 270, 45), None], points)
    assert bearings == [(270, 45), None]
    assert radii == [10, None]