示例#1
0
def test_geocoder_place_types():
    """Place types are enumerated"""
    assert sorted(mapbox.Geocoder().place_types.items()) == [
        ('address',
         "A street address with house number. Examples: 1600 Pennsylvania Ave NW, 1051 Market St, Oberbaumstrasse 7."
         ),
        ('country',
         "Sovereign states and other political entities. Examples: United States, France, China, Russia."
         ),
        ('district',
         "Second order administrative division. Only used when necessary. Examples: Tianjin, Beijing"
         ),
        ('locality',
         "A smaller area within a place that possesses official status and boundaries. Examples: Oakleigh (Melbourne)"
         ),
        ('neighborhood',
         'A smaller area within a place, often without formal boundaries. Examples: Montparnasse, Downtown, Haight-Ashbury.'
         ),
        ('place',
         "City, town, village or other municipality relevant to a country's address or postal system. Examples: Cleveland, Saratoga Springs, Berlin, Paris."
         ),
        ('poi',
         "Places of interest including commercial venues, major landmarks, parks, and other features. Examples: Subway Restaurant, Yosemite National Park, Statue of Liberty."
         ),
        ('poi.landmark',
         "Places of interest that are particularly notable or long-lived like parks, places of worship and museums. A strict subset of the poi place type. Examples: Yosemite National Park, Statue of Liberty."
         ),
        ('postcode',
         "Postal code, varies by a country's postal system. Examples: 20009, CR0 3RL."
         ),
        ('region',
         "First order administrative divisions within a country, usually provinces or states. Examples: California, Ontario, Essonne."
         )
    ]
def test_geocoder_place_types():
    """Place types are enumerated"""
    assert sorted(mapbox.Geocoder().place_types.items()) == [
        ('address',
         "A street address with house number. Examples: 1600 Pennsylvania Ave NW, 1051 Market St, Oberbaumstrasse 7."
         ),
        ('country',
         "Sovereign states and other political entities. Examples: United States, France, China, Russia."
         ),
        ('neighborhood',
         'A smaller area within a place, often without formal boundaries. Examples: Montparnasse, Downtown, Haight-Ashbury.'
         ),
        ('place',
         "City, town, village or other municipality relevant to a country's address or postal system. Examples: Cleveland, Saratoga Springs, Berlin, Paris."
         ),
        ('poi',
         "Places of interest including commercial venues, major landmarks, parks, and other features. Examples: Yosemite National Park, Lake Superior."
         ),
        ('postcode',
         "Postal code, varies by a country's postal system. Examples: 20009, CR0 3RL."
         ),
        ('region',
         "First order administrative divisions within a country, usually provinces or states. Examples: California, Ontario, Essonne."
         )
    ]
def test_geocoder_language():
    responses.add(
        responses.GET,
        'https://api.mapbox.com/geocoding/v5/mapbox.places/1600%20pennsylvania%20ave%20nw.json?language=en,de&access_token=pk.test',
        match_querystring=True,
        body='{"query": ["1600", "pennsylvania", "ave", "nw"]}', status=200,
        content_type='application/json')

    response = mapbox.Geocoder(access_token='pk.test').forward(
        '1600 pennsylvania ave nw', languages=['en', 'de'])
    assert response.status_code == 200
示例#4
0
def test_geocoder_reverse_limit_requires_onetype():
    """Limit requires a single type"""

    lon, lat = -77.123456789, 37.987654321
    service = mapbox.Geocoder(access_token='pk.test')

    with pytest.raises(mapbox.InvalidPlaceTypeError):
        service.reverse(lon=lon, lat=lat, limit=1)

    with pytest.raises(mapbox.InvalidPlaceTypeError):
        service.reverse(lon=lon, lat=lat, limit=1, types=['places', 'country'])
示例#5
0
def makeMBConnection():

    myMBaccessToken = 'pk.eyJ1IjoicmlrYmVsZXciLCJhIjoiY2pieTZwNnB4MzR5YjMybWtld3FzODFvZyJ9.w0Sqg1pkABegUuQhBTPKwQ'

    try:
        geocoder = mapbox.Geocoder(access_token=myMBaccessToken)

    except Exception as e:
        print('makeMBConnection: unable to connect', e)
        return None

    return geocoder
def test_geocoder_forward():
    """Forward geocoding works"""

    responses.add(
        responses.GET,
        'https://api.mapbox.com/geocoding/v5/mapbox.places/1600%20pennsylvania%20ave%20nw.json?access_token=pk.test',
        match_querystring=True,
        body='{"query": ["1600", "pennsylvania", "ave", "nw"]}', status=200,
        content_type='application/json')

    response = mapbox.Geocoder(access_token='pk.test').forward('1600 pennsylvania ave nw')
    assert response.status_code == 200
    assert response.json()['query'] == ["1600", "pennsylvania", "ave", "nw"]
示例#7
0
def get_loc(address):
	"""
	Convert a string of address to latitude and longitude
	Input: String
	Output: latitude, longitude coordinate
	"""

	geocoder = mapbox.Geocoder(access_token = MAPBOX_ACCESS_KEY)
	response = geocoder.forward(address)
	address = response.json()
	add_lat = address["features"][0]["center"][1]
	add_lon = address["features"][0]["center"][0]
	return add_lat, add_lon
示例#8
0
 def save(self, *args, **kwargs):
     if not self.location_geom:
         # geocode
         geocoder = mapbox.Geocoder()
         result = geocoder.forward(
             self.location,
             lon=settings.LOCAL_LONGITUDE,
             lat=settings.LOCAL_LATITUDE,
             types=["address"],
         ).geojson()
         self.location_geom = GEOSGeometry(str(result["features"][0]["geometry"]))
     if not self.region:
         self.region = Region.get_for_point(self.location_geom)
     super().save(*args, **kwargs)
示例#9
0
def test_geocoder_forward_limit():
    """Limit parameter works"""

    responses.add(
        responses.GET,
        'https://api.mapbox.com/geocoding/v5/mapbox.places/washington.json?limit=3&access_token=pk.test',
        match_querystring=True,
        body='{"query": ["washington"], "features": [1, 2, 3]}',
        status=200,
        content_type='application/json')

    response = mapbox.Geocoder(access_token='pk.test').forward('washington',
                                                               limit=3)
    assert response.status_code == 200
    assert len(response.json()['features']) == 3
示例#10
0
def test_geocoder_forward_bbox():
    """Bbox parameter works"""

    responses.add(
        responses.GET,
        'https://api.mapbox.com/geocoding/v5/mapbox.places/washington.json?bbox=-78.3284%2C38.6039%2C-78.0428%2C38.7841&access_token=pk.test',
        match_querystring=True,
        body='{"query": ["washington"]}',
        status=200,
        content_type='application/json')

    response = mapbox.Geocoder(access_token='pk.test').forward(
        'washington', bbox=(-78.3284, 38.6039, -78.0428, 38.7841))
    assert response.status_code == 200
    assert response.json()['query'] == ["washington"]
def test_geocoder_forward_types():
    """Type filtering of forward geocoding works"""

    responses.add(
        responses.GET,
        'https://api.mapbox.com/geocoding/v5/mapbox.places/1600%20pennsylvania%20ave%20nw.json?types=address,country,place,poi,postcode,region&access_token=pk.test',
        match_querystring=True,
        body='{"query": ["1600", "pennsylvania", "ave", "nw"]}', status=200,
        content_type='application/json')

    response = mapbox.Geocoder(
        access_token='pk.test').forward(
            '1600 pennsylvania ave nw',
            types=('address', 'country', 'place', 'poi', 'postcode', 'region'))
    assert response.status_code == 200
    assert response.json()['query'] == ["1600", "pennsylvania", "ave", "nw"]
示例#12
0
def geocode_address(address):
    """
    Geocodes address with Mapbox Geocoding API, then returns data in a
    a tuple of the format ('place name', [x, y])

    Returns None if Mapbox Geocoding API returns nothing of value.
    """
    geocoder = None
    geocoder = mapbox.Geocoder()
    geo_json = geocoder.forward(address).json()

    if "features" not in geo_json or len(geo_json["features"]) == 0:
        return None
    feature = geo_json["features"][0]

    return (feature["place_name"], feature['geometry']['coordinates'])
def test_geocoder_reverse():
    """Reverse geocoding works"""

    lon, lat = -77.4371, 37.5227
    body = json.dumps({"query": [lon, lat]})

    responses.add(
        responses.GET,
        'https://api.mapbox.com/geocoding/v5/mapbox.places/{0},{1}.json?access_token=pk.test'.format(lon, lat),
        match_querystring=True,
        body=body,
        status=200,
        content_type='application/json')

    response = mapbox.Geocoder(access_token='pk.test').reverse(lon=lon, lat=lat)
    assert response.status_code == 200
    assert response.json()['query'] == [lon, lat]
示例#14
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)
示例#15
0
def geocode(ctx, query, forward, include_headers, lat, lon, place_type, output):
    """This command returns places matching an address (forward mode) or
    places matching coordinates (reverse mode).

    In forward (the default) mode the query argument shall be an address
    such as '1600 pennsylvania ave nw'.

      $ mbx geocode '1600 pennsylvania ave nw'

    In reverse mode the query argument shall be a JSON encoded array
    of longitude and latitude (in that order) in decimal degrees.

      $ mbx geocode --reverse '[-77.4371, 37.5227]'

    An access token is required, see `mbx --help`.
    """
    verbosity = (ctx.obj and ctx.obj.get('verbosity')) or 2
    logger = logging.getLogger('mapbox')

    access_token = (ctx.obj and ctx.obj.get('access_token')) or None
    stdout = click.open_file(output, 'w')

    geocoder = mapbox.Geocoder(access_token=access_token)

    if forward:
        for q in iter_query(query):
            resp = geocoder.forward(
                q, types=place_type, lat=lat, lon=lon)
            if include_headers:
                echo_headers(resp.headers, file=stdout)
            if resp.status_code == 200:
                click.echo(resp.text, file=stdout)
            else:
                raise MapboxCLIException(resp.text.strip())
    else:
        for lon, lat in map(coords_from_query, iter_query(query)):
            resp = geocoder.reverse(lon=lon, lat=lat, types=place_type)
            if include_headers:
                echo_headers(resp.headers, file=stdout)
            if resp.status_code == 200:
                click.echo(resp.text, file=stdout)
            else:
                raise MapboxCLIException(resp.text.strip())
def test_geocoder_proximity_rounding():
    """Proximity parameter is rounded to 3 decimal places"""

    responses.add(
        responses.GET,
        'https://api.mapbox.com/geocoding/v5/mapbox.places/1600%20pennsylvania%20ave%20nw.json',
        match_querystring=False,
        body='{"query": ["1600", "pennsylvania", "ave", "nw"]}', status=200,
        content_type='application/json')

    response = mapbox.Geocoder(
        access_token='pk.test').forward(
            '1600 pennsylvania ave nw', lon=0.123456, lat=0.987654)

    # check coordinate precision for proximity flag
    match = re.search(r'[&\?]proximity=([^&$]+)', response.url)
    assert match is not None
    for coord in re.split(r'(%2C|,)', match.group(1)):
        assert _check_coordinate_precision(coord, 3)
示例#17
0
def test_geocoder_reverse_limit():
    """Limit parameter works"""

    lon, lat = -77.4371, 37.5227
    body = json.dumps({"query": [lon, lat], "features": [{'name': 'place'}]})

    responses.add(
        responses.GET,
        'https://api.mapbox.com/geocoding/v5/mapbox.places/{0},{1}.json?access_token=pk.test&limit=1&types=place'
        .format(lon, lat),
        match_querystring=True,
        body=body,
        status=200,
        content_type='application/json')

    service = mapbox.Geocoder(access_token='pk.test')
    response = service.reverse(lon=lon, lat=lat, limit=1, types=['place'])
    assert response.status_code == 200
    assert len(response.json()['features']) == 1
def test_geocoder_unicode():
    """Forward geocoding works with non-ascii inputs
    Specifically, the URITemplate needs to utf-8 encode all inputs
    """

    responses.add(
        responses.GET,
        'https://api.mapbox.com/geocoding/v5/mapbox.places/Florian%C3%B3polis%2C%20Brazil.json?access_token=pk.test',
        match_querystring=True,
        body='{}', status=200,
        content_type='application/json')

    query = "Florianópolis, Brazil"
    try:
        query = query.decode('utf-8')  # Python 2
    except:
        pass  # Python 3

    response = mapbox.Geocoder(access_token='pk.test').forward(query)
    assert response.status_code == 200
def test_geocoder_reverse_types():
    """Type filtering of reverse geocoding works"""

    lon, lat = -77.4371, 37.5227
    body = json.dumps({"query": [lon, lat]})

    responses.add(
        responses.GET,
        'https://api.mapbox.com/geocoding/v5/mapbox.places/{0},{1}.json?types=address,country,place,poi,postcode,region&access_token=pk.test'.format(lon, lat),
        match_querystring=True,
        body=body,
        status=200,
        content_type='application/json')

    response = mapbox.Geocoder(
        access_token='pk.test').reverse(
            lon=lon, lat=lat,
            types=('address', 'country', 'place', 'poi', 'postcode', 'region'))
    assert response.status_code == 200
    assert response.json()['query'] == [lon, lat]
示例#20
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)
def test_geocoder_reverse_rounding():
    """Reverse geocoding parameters are rounded to 5 decimal places"""

    lon, lat = -77.123456789, 37.987654321
    body = json.dumps({"query": [lon, lat]})

    responses.add(
        responses.GET,
        re.compile('https:\/\/api\.mapbox\.com\/geocoding\/v5\/mapbox\.places\/.+\.json'),
        match_querystring=False,
        body=body,
        status=200,
        content_type='application/json')

    response = mapbox.Geocoder(
        access_token='pk.test').reverse(
            lon=lon, lat=lat)

    # check coordinate precision for reverse geocoding coordinates
    match = re.search(r'\/([\-\d\.\,]+)\.json', response.url)
    assert match is not None
    for coord in re.split(r'(%2C|,)', match.group(1)):
        assert _check_coordinate_precision(coord, 5)
示例#22
0
文件: app.py 项目: gresiandra/ISSlive
def update_metrics(n):
    try:
        geocoder = mapbox.Geocoder(
            access_token=
            'pk.eyJ1IjoiZ3Jlc2lhbmRyYSIsImEiOiJjanpxbmJpbXEwbmtiM2JvYmExOWkzYmV2In0.r10NAfXhqvZm5TXTG1Eg6w'
        )
        response = geocoder.reverse(lon=longitude[-1], lat=latitude[-1])
        result = response.json()
        address0 = result['features'][0]['place_name']
        locationiss.append(address0)
    except:
        locationiss.append('Unknown')

    return html.H3(str(locationiss[-1]),
                   style={
                       'font-family': 'Helvetica',
                       'textAlign': 'center',
                       'border': '3px solid #303952',
                       'padding': 15,
                       'margin-right': 15,
                       'fontSize': '13px',
                       'border-radius': 5,
                       'color': '#303952'
                   }),
def test_validate_country():
    assert mapbox.Geocoder()._validate_country_codes(
        ('us', 'br')) ==  {'country': 'us,br'}
def test_geocoder_name():
    """Named dataset name is set"""
    geocoder = mapbox.Geocoder('mapbox.places-permanent')
    assert geocoder.name == 'mapbox.places-permanent'
def test_geocoder_default_name():
    """Default name is set"""
    geocoder = mapbox.Geocoder()
    assert geocoder.name == 'mapbox.places'
示例#26
0
from datetime import date, datetime, timedelta
from collections import defaultdict
import mapbox
from mapbox import Geocoder
from dash.dash import no_update
from return_calc_rent import calc_rent
import json

# Google maps api key
import googlemaps

gmaps = googlemaps.Client(key='AIzaSyC0XCzdNwzI26ad9XXgwFRn2s7HrCWnCOk')

MAPBOX_KEY = 'pk.eyJ1Ijoia2V2YWxzaGFoIiwiYSI6ImNqbW1nbG90MDBhNTQza3IwM3pvd2I3bGUifQ.dzdTsg69SdUXY4zE9s2VGg'
token = MAPBOX_KEY
geocoder = mapbox.Geocoder(access_token=token)

df_lease = pd.read_csv(
    '~/Keval_Backup/Startups/California_2018/CommercialRE/CRE/Platform/Deploy/data/LeaseComp_v1.csv'
)
df_lease = df_lease.sample(100)

# App Layout for designing the page and adding elements
layout = html.Div([
    html.Div(
        [

            # Plot properties map
            dcc.Graph(
                id='map-graph1',
                style={
示例#27
0
    def run(self, filepath=None):
        addresses = {
            'rob': {
                'name': 'First test Location',
                'phone': '250-588-9595',
                'address': '3329 University Woods, Canada',
                'price': 12.35,
            },
            'rob2': {
                'name': 'Second test Location',
                'phone': '800 647 5463',
                'address': '3800 Finnerty Rd,  Canada',
                'price': 22.42,
            },
            'rob3': {
                'name': 'Third test Location',
                'phone': '202-426-6841',
                'address': '3440 Saanich Rd,  Canada',
                'price': 11.52,
            },
            'rob4': {
                'name': 'Fourth test Location',
                'phone': '202.334.6000',
                'address': '1150 Douglas St, Victoria, V8W3M9, Canada',
                'price': 16.65,
            },
            'rob5': {
                'name': 'Fifth test Location',
                'phone': '240-283-9942',
                'address': '3190 Shelbourne St, Victoria, V8T3A8, Canada',
                'price': 6.99,
            }
        }
        for username, address in addresses.items():
            address_entry = AddressEntry()
            address_entry.user_id = User.query.filter(
                User.username == username).first().id
            address_entry.name = address['name']
            address_entry.phone = address['phone']

            geocoder = mapbox.Geocoder()
            selected_feature = json.loads(
                geocoder.forward(
                    address['address']).content.decode('utf-8'))['features'][0]
            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']
            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()
            print("Created: %s" % address['name'])
def test_validate_place_types():
    assert mapbox.Geocoder()._validate_place_types(
        ('address', 'poi')) == {'types': 'address,poi'}
def test_validate_place_types_err():
    try:
        mapbox.Geocoder()._validate_place_types(('address', 'bogus'))
    except mapbox.InvalidPlaceTypeError as err:
        assert str(err) == "'bogus'"
示例#30
0
    def match_via_mapbox(self, s, relevance_threshold=0.75):
        access_token = self.config.get('mapbox_access_token')
        if not access_token:
            log.warning(
                'LookupService must be configured with a mapbox_access_token to enable geocoding '
                'via Mapbox')
            return None

        bbox = self.config.get('bbox')
        center = self.config.get('center')
        longitude, latitude = center if center else (None, None)

        try:
            # REF: https://docs.mapbox.com/api/search/#geocoding
            geocoder = mapbox.Geocoder(access_token=access_token)

            # XXX: Hard coded country
            # XXX: Hard coded place types
            response = geocoder.forward(
                s,
                bbox=bbox,
                country=['us'],
                lat=latitude,
                lon=longitude,
                limit=3,
                types=['address', 'poi'],
            )
        except mapbox.errors.ValidationError as mapbox_exc:
            raise LookupError('Unable to geocode via Mapbox geocoder',
                              str(mapbox_exc))

        log.info('Mapbox geocoder service response status code: %d',
                 response.status_code)

        data = response.json()

        if response.status_code != 200:
            error_message = data.get('message', 'Unknown Error')
            raise LookupError('Unable to geocode via Mapbox geocoder',
                              error_message)

        all_features = data['features']

        # Filter out less-relevant features
        relevant_features = [
            f for f in all_features if f['relevance'] > relevance_threshold
        ]

        # Sort by relevance and prominence
        relevant_features = sorted(relevant_features,
                                   key=lambda f:
                                   (f['relevance'], f.get('score', 0)))

        num_features = len(relevant_features)

        if num_features == 0:
            if all_features:
                # Fall back to the most-relevant feature
                relevant_features = [all_features[0]]
                num_features = 1
            else:
                return None

        if num_features == 1:
            result = relevant_features[0]
            return self._mapbox_result_to_lookup_result(s, result)
        else:
            results = tuple(
                self._mapbox_result_to_lookup_result(s, r)
                for r in relevant_features)
            raise MultipleLookupResultsError(choices=results)