Ejemplo n.º 1
0
def save_map():
    # Doc: https://github.com/mapbox/mapbox-sdk-py/blob/master/docs/static.md#static-maps
    service = Static(access_token=MAPBOX_TOKEN)
    
    response = service.image('mapbox.satellite', lon=-61.7, lat=12.1, z=12)
    with open('/tmp/map.png', 'wb') as output:
        output.write(response.content)
Ejemplo n.º 2
0
def save_map():
    # Doc: https://github.com/mapbox/mapbox-sdk-py/blob/master/docs/static.md#static-maps
    service = Static(access_token=MAPBOX_TOKEN)

    response = service.image('mapbox.satellite', lon=-61.7, lat=12.1, z=12)
    with open('/tmp/map.png', 'wb') as output:
        output.write(response.content)
Ejemplo n.º 3
0
def satellite(request):
    data = {}

    if request.method == "POST":
        try:
            body = json.loads(request.body)

            if "lat" in body and "lon" in body:
                lat = body['lat']
                lon = body['lon']

                service = Static()
                service_response = service.image('mapbox.satellite', lon=lon, lat=lat, z=18)

                with open('/Users/s.hamiti/Desktop/wd/hackathon/tmp/test.jpg', 'wb') as output:
                    output.write(service_response.content)
                  


                response = body['lat']

            else:
                data["error"] = "Please input lat and lon"
                return JsonResponse(data)

        except Exception as e:
            response = str(e)

        data.update({'response': response})

    return JsonResponse(data)
Ejemplo n.º 4
0
def get_and_store_file(tile_ind, list_format=('x', 'y', 'z')):
    """Fetch tile from internet and store on local drive"""

    # Only download a certain percentage of tiles
    # if random() > down_p['download_prob']:
    #
    #     return 0
    tile_ind = tile_ind.rstrip('\n').split()
    #####################################
    # Construct url to image
    #####################################
    # Allow for other x/y/z orders
    ind_pos = [list_format.index(letter) for letter in ['x', 'y', 'z']]
    ind_dict = dict(x=tile_ind[ind_pos[0]],
                    y=tile_ind[ind_pos[1]],
                    z=tile_ind[ind_pos[2]])
    #url = down_p['url_template'].format(**ind_dict)

    service = Static(down_p['token'])
    coords = mercantile.ul(int(tile_ind[ind_pos[0]]), int(tile_ind[ind_pos[1]]), int(tile_ind[ind_pos[2]]))

    response = service.image('mapbox.satellite', lon=coords.lng, lat=coords.lat, z=tile_ind[ind_pos[2]], image_format='jpg', width=256, height=256)

    ##############################################
    # Setup file paths
    ##############################################
    # Check if tile exists already
    tile_fname = op.join(down_p['storage_dir'],
                        '{x}-{y}-{z}.jpg'.format(**ind_dict))

    ####################################################
    # Download to storage if file doesn't exist
    ####################################################
    if not op.exists(tile_fname):
        repeat_try = 10
        while repeat_try:
            try:
                print("status code", response.status_code)
                if response.status_code == 200:
                    with open(tile_fname, 'wb') as output:
                        _ = output.write(response.content)
                    print('Successfully saved', tile_fname)
                    return 200
                elif response.status_code == 429:
                    print('URL Error')
                    return 429
            except response.status_code != 200:
                repeat_try -= 1

        if repeat_try == 0:
            print('Too many repeats, quitting on {}'.format(tile_fname))
            return
    else:
        print('File exists: {}'.format(tile_fname))
        return 0
Ejemplo n.º 5
0
 def _initialize_services(self):
     '''Set the mapbox access token for both the StaticStyle API and Static API sessions'''
     self.service_style = StaticStyle(self.token)
     self.service_static = Static(self.token)
     self.service_geocoder = Geocoder()
     os.environ['MAPBOX_ACCESS_TOKEN'] = self.token
     self.service_style.session.params['access_token'] == os.environ[
         'MAPBOX_ACCESS_TOKEN']
     self.service_static.session.params['access_token'] == os.environ[
         'MAPBOX_ACCESS_TOKEN']
     self.service_geocoder.session.params['access_token'] == os.environ[
         'MAPBOX_ACCESS_TOKEN']
Ejemplo n.º 6
0
    def __init__(self, service=None, access_token=None):
        """Built a instance of mapbox.

        References: https://www.mapbox.com/api-documentation/#maps

        Args:
            service: The name of service that can be used as image source.
                     e.g. ['mapbox.satellite','mapbox.streets']
        """
        self.token = access_token or ''
        self.service = service or 'mapbox.satellite'
        self.source = Static(access_token=self.token)
        self.destination = f'/tmp/mapbox/{service.replace("mapbox","")}'
Ejemplo n.º 7
0
def getMapCode(points):
    def errorsShallNotPass(response):
        try:
            response.raise_for_status()
        except:
            print("Error %d occured while getting map" %response.status_code,
                  file=stderr)
            exit(EXIT_FAILURE)

    service  = Static(MAPBOX_TOKEN)
    response = service.image("mapbox.streets", features=points)
    errorsShallNotPass(response)
    return response.content
Ejemplo n.º 8
0
 def createMapBoxMap(self):
     service = Static()
     fullPathImage = self.PATH + self.id + '.png'
     features = [self.createFeature(point) for point in self.points]
     response = None
     if len(features) == 1:
         print(features[0]['geometry']['coordinates'][0])
         print(features[0]['geometry']['coordinates'][1])
         response = service.image(
             'mapbox.satellite',
             lon=features[0]['geometry']['coordinates'][0],
             lat=features[0]['geometry']['coordinates'][1],
             z=15,
             features=features)
     else:
         response = service.image('mapbox.satellite', features=features)
     print(response)
     with open(fullPathImage, 'wb') as output:
         _ = output.write(response.content)
Ejemplo n.º 9
0
def get_map(latitude, longitude):
    service = Static(access_token=config.MAPBOX_ACCESS_TOKEN)

    point_on_map = {
        'type': 'Feature',
        'properties': {
            'name': 'point'
        },
        'geometry': {
            'type': 'Point',
            'coordinates': [longitude, latitude]
        }
    }

    response = service.image('mapbox.streets',
                             retina=True,
                             features=point_on_map,
                             lon=longitude,
                             lat=latitude,
                             z=15)

    return response.url
Ejemplo n.º 10
0
class MapBox:
    def __init__(self, service=None, access_token=None):
        """Built a instance of mapbox.

        References: https://www.mapbox.com/api-documentation/#maps

        Args:
            service: The name of service that can be used as image source.
                     e.g. ['mapbox.satellite','mapbox.streets']
        """
        self.token = access_token or ''
        self.service = service or 'mapbox.satellite'
        self.source = Static(access_token=self.token)
        self.destination = f'/tmp/mapbox/{service.replace("mapbox","")}'

    def download(self, coordinate=('0', '0'), params={}):
        """Download an image based on coordinate.

        Args:
         coordinate: (lat,lon): Latitude and Longitude coordinates.
         params: Dict with the following attributes.
            zoom
        """
        params['lat'] = coordinate[0]
        params['lon'] = coordinate[1]

        response = self.source.image(self.service, **params)

        if response.status_code != 200:
            raise "The coordinate can't be found."

        image = response.content
        destination = f'{self.destination}/{"_".join(coordinate)}.png'

        with open(destination, 'wb') as output:
            output.write(image)
Ejemplo n.º 11
0
import os
import json
import urllib
import time
import shutil

from mapbox import Static

MAPBOX_ACCESS_TOKEN = os.environ['MAPBOX_ACCESS_TOKEN']
service = Static(access_token=MAPBOX_ACCESS_TOKEN)


class ImagesManager:
    def __init__(self, sites_data_filepath='json/sites.json'):
        self._STANDARD_ZOOM = 15
        self._STATIC_DIRECTORY = 'static/'
        self._BASE_IMAGES_DIRECTORY = 'base_images/'
        self._CURRENT_IMAGE_DIRECTORY = 'current_image/'
        self._LABELED_IMAGES_DIRECTORY = 'labeled_images/'
        self._SITES_DATA_FILEPATH = sites_data_filepath
        self._IMAGE_WIDTH = 1000
        self._IMAGE_HEIGHT = 1000

        self._sites_dict = self.get_sites_dict()
        self._unchecked_sites = self._sites_dict['unchecked']
        self._water_sites = self._sites_dict['water']
        self._no_water_sites = self._sites_dict['no_water']

        self._current_site = None
        next_image_is_ready = self.initialize_next_image()
Ejemplo n.º 12
0
def main():

    # ------
    # Static
    # ------
    
    service = Static()
    response = service.image('mapbox.satellite', lon=-61.7, lat=12.1, z=12)
    print(response.status_code)
    print(response.headers['Content-Type'])

    portland = {
        'type': 'Feature',
        'properties': {'name': 'Portland, OR'},
        'geometry': {
            'type': 'Point',
            'coordinates': [-122.7282, 45.5801]
        }
    }

    bend = {
        'type': 'Feature',
        'properties': {'name': 'Bend, OR'},
        'geometry': {
            'type': 'Point',
            'coordinates': [-121.3153, 44.0582]
        }
    }

    response = service.image('mapbox.satellite', features = [portland, bend])
    print(response.status_code)
    print(response.headers['Content-Type'])

    with open('map.png', 'wb') as f:
        _ = f.write(response.content)

    help(Static)

    # --------
    # Geocoder
    # --------

    perm_geocoder = Geocoder(name='mapbox.places-permanet')
    geocoder = Geocoder()

    # Limits

    response = geocoder.forward('Chester, NJ')
    print(response.headers['X-Rate-Limit-Interval'])
    print(response.headers['X-Rate-Limit-Limit'])
    print(response.headers['X-Rate-Limit-Reset'])

    # Response format
    
    collection = response.json()
    print(collection['type'] == 'FeatureCollection')
    print(sorted(collection.keys()))
    print(collection['query'])

    first = collection['features'][0]
    print(first['type'] == 'Feature')

    # Forward geocoding

    response = geocoder.forward('200 queen street')
    print(response.status_code)
    print(response.headers['Content-Type'])
    first = response.geojson()['features'][0]
    print(first['place_name'])

    # Forward geocoding with proximity

    response = geocoder.forward('200 queen street', lon=-66.05, lat=45.27)
    print(response.status_code)
    first = response.geojson()['features'][0]
    print(first['place_name'])
    print([int(coord) for coord in first['geometry']['coordinates']])

    # Forward geocoding with bounding box

    response = geocoder.forward('washington', bbox=[-78.338320, 38.520792, -77.935454, 38.864909], types=('place',))
    print(response.status_code)
    first = response.geojson()['features'][0]
    print(first['place_name'])
    print([round(coord,2) for coord in first['geometry']['coordinates']])

    # Forward geocoding with limited results

    response = geocoder.forward('washington', limit=3)
    print(response.status_code)
    print(len(response.geojson()['features']))

    # Reverse geocoding

    response = geocoder.reverse(lon=-73.989, lat=40.733)
    print(response.status_code)
    features = sorted(response.geojson()['features'], key = lambda x: x['place_name'])
    for f in features:
        print('{place_name}: {id}'.format(**f))

    # Reverse geocoding with limited results by location type

    response = geocoder.reverse(lon=-73.989, lat=40.733, limit=1, types=['country'])
    print(response.status_code)
    features = response.geojson()['features']
    print(len(features))

    print('{place_name}: {id}'.format(**features[0]))

    # Filtering by country code

    response = geocoder.forward('200 queen street', country=['us'])
    print(response.status_code)
    print(any(['Canada' in f['place_name'] for f in response.geojson()['features']]))

    # Filtering by type

    response = geocoder.reverse(lon=-73.989, lat=40.733, types=['poi'])
    print(response.status_code)
    features = response.geojson()['features']
    print(all([f['id'].startswith('poi') for f in features]))
Ejemplo n.º 13
0
#   - 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')
Ejemplo n.º 14
0
class TileGenerator:
    '''Use this class to access Mapbox API and generate tiles'''
    def __init__(self,
                 settings_file='mapbox_settings.yaml',
                 parent_directory='.',
                 train='train',
                 valid='valid'):
        '''Initialise a tile generator with a yaml settings file.
        Set the parent directory path and names of training an validation folders'''
        with open(settings_file) as f:
            try:
                self.data = yaml.load(f, Loader=yaml.FullLoader)
                self.token = self.data['MAPBOX_ACCESS_TOKEN']
                self.data_types = self._map_data(self.data['ids'])
            except:
                print('Check the settings file path:', settings_file)

        self._initialize_services()
        self.parent_directory = parent_directory
        self.train = train
        self.valid = valid
        self.image_size = 0

    def _initialize_services(self):
        '''Set the mapbox access token for both the StaticStyle API and Static API sessions'''
        self.service_style = StaticStyle(self.token)
        self.service_static = Static(self.token)
        self.service_geocoder = Geocoder()
        os.environ['MAPBOX_ACCESS_TOKEN'] = self.token
        self.service_style.session.params['access_token'] == os.environ[
            'MAPBOX_ACCESS_TOKEN']
        self.service_static.session.params['access_token'] == os.environ[
            'MAPBOX_ACCESS_TOKEN']
        self.service_geocoder.session.params['access_token'] == os.environ[
            'MAPBOX_ACCESS_TOKEN']

    def _map_data(self, ids: dict) -> dict:
        data_type = {}
        for id, info in self.data['ids'].items():
            data_type[id] = Map(info['type'], info['user'], info['key'],
                                info['file_name'])
        return data_type

    def get_styleid_response(self,
                             lon: float,
                             lat: float,
                             zoom: int,
                             data_type: str,
                             features=None,
                             width=512,
                             height=512):
        '''Retrieve the raster data for a given style available from Mapbox either from already created styles or
        from user created ones in Mapbox Studio. Longitude, latitude, zoom and data type are required.
        Additional features can be added to this raster by providing a json object for the features argument.'''
        if self.data_types[data_type].map_type != 'style':
            return 'Not the right data type. Must be a style type for the StaticStyle API'
        response = self.service_style.image(
            username=self.data_types[data_type].user,
            style_id=self.data_types[data_type].key,
            features=features,
            lon=lon,
            lat=lat,
            zoom=zoom,
            width=width,
            height=height)
        return response.content

    def get_mapid_response(self,
                           lon: float,
                           lat: float,
                           zoom: int,
                           data_type: str,
                           features=None,
                           width=512,
                           height=512):
        '''Retrieve the raster data for a given map id with longitude, latitude, zoom and data type. Additional features
        can be added to this raster by providing a json object for the features argument.'''
        if self.data_types[data_type].map_type != 'map':
            return 'Not the right data type. Must be a map type for the Static API'
        mapid = f'{self.data_types[data_type].user}.{self.data_types[data_type].key}'
        response = self.service_static.image(mapid,
                                             lon,
                                             lat,
                                             z=zoom,
                                             features=features,
                                             width=width,
                                             height=height)
        return response.content

    def get_response(self,
                     lon,
                     lat,
                     zoom,
                     data_type,
                     features=None,
                     width=512,
                     height=512):
        '''Response depending on data type.'''
        if self.data_types[data_type].map_type == 'style':
            return self.get_styleid_response(lon,
                                             lat,
                                             zoom,
                                             data_type,
                                             features,
                                             width=width,
                                             height=height)
        elif self.data_types[data_type].map_type == 'map':
            return self.get_mapid_response(lon,
                                           lat,
                                           zoom,
                                           data_type,
                                           features,
                                           width=width,
                                           height=height)
        else:
            'Not a recognised data type.'

    def view_style_tile(self,
                        lon,
                        lat,
                        zoom,
                        data_type,
                        additional_features=None):
        '''View tile image from Mapbox style definition'''
        xr = self.get_styleid_response(lon, lat, zoom, data_type,
                                       additional_features)
        img = im.open(io.BytesIO(xr))
        if self.image_size != 0:
            img = img.crop((0, 0, self.image_size, self.image_size))
        img = img.convert('RGB')
        return img

    def view_map_tile(self,
                      lat,
                      lon,
                      zoom,
                      data_type,
                      additional_features=None):
        '''View tile image based on Mapbox Map API'''
        xr = self.get_mapid_response(lat,
                                     lon,
                                     zoom,
                                     data_type,
                                     features=additional_features)
        img = im.open(io.BytesIO(xr))
        if self.image_size != 0:
            img = img.crop((0, 0, self.image_size, self.image_size))
        img = img.convert('RGB')
        return img

    def file_exist(self, file_name: str):
        '''Create directories if they do not exist'''
        path = Path(f'{file_name}/')
        if not path.exists():
            path.mkdir()

    def check_and_create_folder(self, file_name):
        p = Path(file_name)
        pth = Path()
        for i in p.parts:
            pth = pth.joinpath(i + '/')
            self.file_exist(pth)

    def get_tile_set(self,
                     lon: float,
                     lat: float,
                     zoom: int,
                     processors: dict,
                     file_list: list,
                     additional_features: dict = None,
                     add_features: list = None,
                     file: str = 'train',
                     compress_level=3,
                     width=512,
                     height=512):
        for data_type, func in processors.items():
            feature = None
            if data_type in add_features: feature = additional_features
            self.check_and_create_folder(
                f'{self.parent_directory}/{self.data_types[data_type].file_name}/{file}'
            )
            if not self.file_exists(
                    file_list, self.data_types[data_type].file_name, file, lon,
                    lat, zoom):
                xr = self.get_response(lon,
                                       lat,
                                       zoom,
                                       data_type,
                                       feature,
                                       width=width,
                                       height=height)
                img = im.open(io.BytesIO(xr))
                if self.image_size != 0:
                    img = img.crop((0, 0, self.image_size, self.image_size))
                img = img.convert('RGB')
                func(img)
                img.save(
                    f'{self.parent_directory}/{self.data_types[data_type].file_name}/{file}/{lon},{lat},{zoom}.png',
                    'PNG',
                    compress_level=compress_level)

    def get_existing_files(self, file_name: str, file: str = 'train') -> list:
        '''Find all existing files inside file (defalut is train) and retrn list'''
        existing_files = [
            f'{file_name}/{file}/{o.name}'
            for o in os.scandir(f'{self.parent_directory}/{file_name}/{file}')
        ]
        return existing_files

    def file_exists(self, file_list: list, file_name: str, file: str,
                    lon: float, lat: float, zoom: int) -> bool:
        '''Check if file exists'''
        file_path = f'{file_name}/{file}/{lon},{lat},{zoom}.png'
        return True if file_path in file_list else False

    def generate_tile_set(self,
                          top_left_lon: float,
                          top_left_lat: float,
                          bottom_right_lon: float,
                          bottom_right_lat: float,
                          zoom: int,
                          processors: dict,
                          add_features: list,
                          valid_percentage=10,
                          image_crop=0,
                          g: dict = None,
                          max_imgs: int = 1000,
                          compress_level=3,
                          width=512,
                          height=512):
        '''Method used to generate a set of tiles inside an area defined by the upper left corner and lower right corner'''
        per = int(100 / valid_percentage)
        total_imgs = 0
        train_existing_files = []
        valid_existing_files = []
        if self.image_size == image_crop:
            for f, _ in processors.items():
                train_existing_files.extend(
                    self.get_existing_files(self.data_types[f].file_name,
                                            self.train))
                if self.valid:
                    valid_existing_files.extend(
                        self.get_existing_files(self.data_types[f].file_name,
                                                self.valid))
        else:
            self.image_size = image_crop
        tl_x, tl_y, _ = self.lat_lon_to_x_y(top_left_lat, top_left_lon, zoom)
        br_x, br_y, _ = self.lat_lon_to_x_y(bottom_right_lat, bottom_right_lon,
                                            zoom)
        tot = int((abs(br_x - tl_x) + 1) * (abs(tl_y - br_y) + 1))
        for j in range(int(abs(tl_y - br_y)) + 1):
            for i in range(int(abs(br_x - tl_x)) + 1):
                lat, lon = self.x_y_lat_lon(tl_x - i * 0.71, tl_y - j, zoom)
                if total_imgs % per == 0 and self.valid != None:
                    self.get_tile_set(lat,
                                      lon,
                                      zoom,
                                      processors,
                                      valid_existing_files,
                                      additional_features=g,
                                      add_features=add_features,
                                      file=self.valid,
                                      compress_level=compress_level,
                                      width=width,
                                      height=height)
                else:
                    self.get_tile_set(lat,
                                      lon,
                                      zoom,
                                      processors,
                                      train_existing_files,
                                      additional_features=g,
                                      add_features=add_features,
                                      file=self.train,
                                      compress_level=compress_level,
                                      width=width,
                                      height=height)
                total_imgs += 1
                if total_imgs == max_imgs:
                    return
                tenper = int(0.1 * tot) if int(0.1 * tot) > 1 else tot
                if int(total_imgs % tenper) == 0:
                    per = int(100 * total_imgs / tot)
                    print(f'{per}%')

    def generate_tiles_around_lat_lon(self,
                                      lat: float,
                                      lon: float,
                                      zoom: int,
                                      lat_lon_list: list,
                                      processors: dict,
                                      add_features: list,
                                      feature_scale=0.0002,
                                      tile_num: int = 1,
                                      valid_percentage=10,
                                      image_crop=0,
                                      g: dict = None,
                                      max_imgs: int = 1000,
                                      compress_level=3,
                                      width=512,
                                      height=512):
        '''generate a set of tiles arounf a latitude and longitude'''
        per = int(100 / valid_percentage)
        total_imgs = 0
        lat_lon_pairs = []
        total_tiles = (2 * tile_num + 1)
        tl_x, tl_y, _ = self.lat_lon_to_x_y(lat, lon, zoom)
        train_existing_files = []
        valid_existing_files = []
        if self.image_size == image_crop:
            for f, _ in processors.items():
                train_existing_files.extend(
                    self.get_existing_files(self.data_types[f].file_name,
                                            self.train))
                if self.valid:
                    valid_existing_files.extend(
                        self.get_existing_files(self.data_types[f].file_name,
                                                self.valid))
        else:
            self.image_size = image_crop
        for x in range(3):
            for y in range(3):
                lat_lon_pairs.append(
                    (tl_x + 0.25 * (x - 1), tl_y + 0.25 * (y - 1)))
        for ll in lat_lon_pairs:
            for j in range(total_tiles):
                for i in range(total_tiles):
                    lat, lon = self.x_y_lat_lon(ll[0] + tile_num - i,
                                                ll[1] + tile_num - j, zoom)
                    lls, ftrs = self.find_nn_ll(lat, lon, lat_lon_list, zoom,
                                                feature_scale)
                    if ftrs['type'] == 'None': ftrs = None
                    if total_imgs % per == 0 and self.valid != None:
                        self.get_tile_set(lls[1],
                                          lls[0],
                                          zoom,
                                          processors,
                                          valid_existing_files,
                                          additional_features=ftrs,
                                          add_features=add_features,
                                          file=self.valid,
                                          compress_level=compress_level,
                                          width=width,
                                          height=height)
                    else:
                        self.get_tile_set(lls[1],
                                          lls[0],
                                          zoom,
                                          processors,
                                          train_existing_files,
                                          additional_features=ftrs,
                                          add_features=add_features,
                                          file=self.train,
                                          compress_level=compress_level,
                                          width=width,
                                          height=height)
                    total_imgs += 1

    def find_nn_ll(self, lati, long, ll_list, zoom, scale: float):
        '''Find other latitudes and longitudes in the same tile. There is a limit on the number of neighbours
        to be found as there is a character limit in the Mapbox query (see the counter variable in this method).'''
        lati = lati
        long = long
        size_func = lambda x: math.log(x + 1) * scale
        x, y, _ = self.lat_lon_to_x_y(lati, long, zoom)
        minx = x - 0.5
        maxx = x + 0.5
        miny = y - 0.5
        maxy = y + 0.5
        nn_list = []
        counter = 0
        #counter is needed to restrict the number of rectangles created as there is a character limit
        #for the string when submitting a query to Mapbox
        for o in ll_list:
            if self.filter_area(o, minx, maxx, miny, maxy,
                                zoom) and counter < 6:
                nn_list.append(self.create_rectangle_polygon(o, size_func))
                counter += 1
        features = ' '.join(map(str, nn_list))
        if len(nn_list) > 0:
            nns = {'type': 'FeatureCollection', 'features': nn_list}
        else:
            nns = {'type': 'None'}
        return (lati, long), nns

    def filter_area(self, ll, minx, maxx, miny, maxy, zoom):
        x, y, _ = self.lat_lon_to_x_y(ll[0], ll[1], zoom)
        if x > minx and x < maxx and y > miny and y < maxy:
            return True
        return False

    def convertMasksToSegmentation(self,
                                   file='train',
                                   segmentation_array=None,
                                   clean_function=None,
                                   mask_file='mask',
                                   label_file='labels'):
        '''Used to label pixels with an integer value corresponding to the order of the segmentation array'''
        self.segmentation_array = segmentation_array
        self.check_and_create_folder(
            f'{self.parent_directory}/{label_file}/{file}')
        file_names = [
            o.name
            for o in os.scandir(f'{self.parent_directory}/{mask_file}/{file}')
        ]
        existing_files = [
            f'{o.name}'
            for o in os.scandir(f'{self.parent_directory}/{label_file}/{file}')
        ]
        for fn in file_names:
            if fn not in existing_files:
                orig = im.open(
                    f'{self.parent_directory}/{mask_file}/{file}/{fn}')
                width, height = orig.size
                if clean_function:
                    clean_function(orig)
                m = np.array([self.pxToSeg(d) for d in orig.getdata()])
                m = m.reshape((-1, width))
                m = m.astype(float)
                img = im.fromarray(m)
                img = img.convert('RGB')
                img.save(f'{self.parent_directory}/{label_file}/{file}/{fn}')

    def pxToSeg(self, pixel):
        return np.where([pixel == i for i in self.segmentation_array])[0][0]

    def number_of_tiles(self, top_left_lon: float, top_left_lat: float,
                        bottom_right_lon: float, bottom_right_lat: float,
                        zoom: int):
        '''Get the number of tiles in an area defined by upper left and lower right coordinates for a given zoom'''
        tl_x, tl_y, _ = self.lat_lon_to_x_y(top_left_lat, top_left_lon, zoom)
        br_x, br_y, _ = self.lat_lon_to_x_y(bottom_right_lat, bottom_right_lon,
                                            zoom)
        tot = int((abs(br_x - tl_x) + 1) * (abs(tl_y - br_y) + 1))
        return tot

    def convertToRadians(self, degrees):
        '''Simply convert Degrees to Radians'''
        return degrees * math.pi / 180

    def lat_lon_to_x_y(self, lat_deg, lon_deg, zoom):
        '''Convert Latitude/Longitude coordinates to x/y coordinates'''
        n = 2**zoom
        lat_rad = self.convertToRadians(lat_deg)
        xtile = n * ((lon_deg + 180) / 360)
        ytile = n * (1 -
                     (math.log(math.tan(lat_rad) +
                               (1 / math.cos(lat_rad))) / math.pi)) / 2
        return xtile, ytile, zoom

    def x_y_lat_lon(self, x, y, zoom):
        '''Convert x/y coordinates to Latitude/Longitude coordinates'''
        n = 2**zoom
        lon_deg = x / n * 360.0 - 180.0
        lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * y / n)))
        lat_deg = lat_rad * 180.0 / math.pi
        return lat_deg, lon_deg

    def get_lats_lons_search(
            self,
            search_string: str = 'Den Haag, museum, gallery',
            minmax_lonlat: list = [4.244794, 4.349174, 52.068414, 52.087417],
            limit: int = 20):
        res = self.service_geocoder.forward(f'\"{search_string}\"',
                                            bbox=minmax_lonlat,
                                            limit=limit)
        gj = res.geojson()
        name = []
        lat = []
        lon = []
        weights = []
        for l in gj['features']:
            name.append(l['text'])
            lat.append(l['geometry']['coordinates'][1])
            lon.append(l['geometry']['coordinates'][0])
            weights.append(1)
        return pd.DataFrame({
            'name': name,
            'lat': lat,
            'lon': lon,
            'weight': weights
        })

    def search_lats_lons(
            self,
            search_string: str = 'Den Haag, museum, gallery',
            minmax_lonlat: list = [4.244794, 4.349174, 52.068414, 52.087417],
            limit: int = 20):
        out = self.get_lats_lons_search(search_string, minmax_lonlat,
                                        limit)[['lat', 'lon', 'weight']]
        lat_max = out['lat'].max()
        lat_min = out['lat'].min()
        lon_max = out['lon'].max()
        lon_min = out['lon'].min()
        return [tuple(r) for r in out.values.tolist()
                ], lat_max, lat_min, lon_max, lon_min

    def create_rectangle_polygon(self,
                                 center: tuple,
                                 size_func,
                                 colour: str = "#BE00FF",
                                 fill_opacity: float = 1):
        '''Creates a json describing a rectangle that is sent to Mapbox to be drawn on the request image.'''
        size = size_func(center[2])
        tl = [center[1] - size, center[0] + size]
        tr = [center[1] + size, center[0] + size]
        br = [center[1] + size, center[0] - size]
        bl = [center[1] - size, center[0] - size]
        return {
            'type': 'Feature',
            'geometry': {
                'type': 'Polygon',
                'coordinates': [[tl, tr, br, bl, tl]]
            },
            'properties': {
                'stroke': colour,
                'fill': colour,
                'fill-opacity': fill_opacity
            }
        }
Ejemplo n.º 15
0
 def render_map(formdata):
     ver("Preparing map for: {0}".format(formdata['querylocation']))
     authSelector = dict(
         fencemaster = ("tinetiffeencesidetteryto","1d181a41ebbe621ad2cf7fd5780261efeae17c7e"),
         testfences = ("ieuredislonlyeacticullea","e346439405bc87a5ea7adb3941f5f92bcf83a3c2"),
         pullpaths = ("itsederesedowtherandstra","24c8cb6b93ba3e82a4a07d2e7fb180be29a880b1")
     )
     account = 'bradwbonn'
     db = formdata['database']
     ddoc = 'geoIdx'
     index = 'newGeoIndex'
     myAuth = authSelector[db] # APIキーは読み取り専用です
     
     myPoint = get_point(formdata['querylocation'])
     pointWKT = "point({0}+{1})".format(myPoint[0],myPoint[1]) # longitude first
     
     queryBase = "https://{0}.cloudant.com/{1}/_design/{2}/_geo/{3}?".format(account,db,ddoc,index)
     
     if formdata['querytype'] == "contains":
         queryString = queryBase + "g={0}&limit={1}&relation=contains".format(pointWKT,formdata['limit'])
     elif formdata['querytype'] == "intersects":
         queryString = queryBase + "g={0}&limit={1}&relation=intersects".format(pointWKT,formdata['limit'])
     elif formdata['querytype'] == "nearest":
         queryString = queryBase + "g={0}&limit={1}&nearest=true".format(pointWKT,formdata['limit'])
     elif formdata['querytype'] == "radius":
         queryString = queryBase + "lat={0}&lon={1}&radius={2}&limit={3}".format(
             myPoint[1],
             myPoint[0],
             formdata['radius'],
             formdata['limit']
         )
     
     # first element of returned array is status element.
     # -1 = Cloudant database error
     # 0 = No geo entities found. Show only map with point
     # else: query time for matching geo entities
     
     fences = getFences(queryString,myAuth)
     
     if fences[0] == -1:
         return {
             'queryTime': 0,
             'message': "DATABASE ERROR",
             'uri': queryString
             }
     else:
         featureCollection = buildFeatureCollection(fences, myPoint)
         queryTime = fences[0]
     
     try:
         service = Static()
         # service.session.params['access_token'] = os.environ['MAPBOX_ACCESS_TOKEN']
         #ver("Feature Collection size: {0}".format(len(featureCollection)))
         service.session.params['access_token'] = 'pk.eyJ1IjoiYnJhZHdib25uIiwiYSI6ImNqMjd3bmEwbjAwMjQyeHF0OGp3dm5ibWUifQ.uNds-BFopyeVQY7beRAeQw'
         response = service.image('mapbox.streets', features=featureCollection)
         if response.status_code <> 200:
             ver("Mapbox error: HTTP {0}: {1}".format(response.status_code,response.text))
     except Exception as e:
         ver("Unable to render map: {0}".format(e))
         return {
             'queryTime': 0,
             'message': "Results too large for static map render",
             'uri': queryString
         }            
     
     try:
         with open(newImageName, 'wb') as output:
             output.write(response.content)
         ver("Map image written")
     except Exception as e:
         ver("Cannot write file: {0}".format(e))
         return {
             'queryTime': 0,
             'message': "***Unable to render map!***",
             'uri': queryString
         }
     fencesFound = len(fences) - 1
     if fencesFound > 0:
         message = "Showing {0} matching entities".format(fencesFound)
     else:
         message = "No matching entities"
     return {
         'queryTime': queryTime,
         'message': message,
         'uri': queryString
     }
Ejemplo n.º 16
0
              (0, 0, STITCH_WIDTH, STITCH_WIDTH)]
PASTE_COORDINATES = [
    (0, 0),
    (0, STITCH_WIDTH),
    (0, TILE_SIDE_LENGTH + STITCH_WIDTH),
    (STITCH_WIDTH, 0),
    (STITCH_WIDTH, STITCH_WIDTH),
    (STITCH_WIDTH, TILE_SIDE_LENGTH + STITCH_WIDTH),
    (TILE_SIDE_LENGTH + STITCH_WIDTH, 0),
    (TILE_SIDE_LENGTH + STITCH_WIDTH, STITCH_WIDTH),
    (TILE_SIDE_LENGTH + STITCH_WIDTH, TILE_SIDE_LENGTH + STITCH_WIDTH),
]

MAX_RETRIES = 12  # max wait time with exponential backoff would be ~34 minutes

service = Static()


def gather_and_persist_imagery_at_coordinate(slippy_coordinates,
                                             final_zoom=FINAL_ZOOM,
                                             grid_size=GRID_SIZE,
                                             imagery="mapbox"):
    # the top left square of the query grid this point belongs to
    base_coords = tuple(map(lambda x: x - x % grid_size, slippy_coordinates))
    if grid_size % 2 == 0:
        # if the grid size is even, the center point is between 4 tiles in center (or the top left of bottom right one)
        center_bottom_right_tile = tuple(
            map(lambda x: x + grid_size // 2, base_coords))
        center_lon_lat = num2deg(center_bottom_right_tile,
                                 zoom=final_zoom,
                                 center=False)
Ejemplo n.º 17
0
from mapbox import Static
from mapbox import Geocoder
import mapbox
'''
export MAPBOX_ACCESS_TOKEN="pk.eyJ1IjoidGVzdGVybWlzbyIsImEiOiJja2VkY3RjbncwcW53MnNydmQ2ZjJhZXZ5In0.xquJPYqw4t4Mjsq06Nw66Q"
'''
if __name__ == '__main__':

    service = Static()
    portland = {
        'type': 'Feature',
        'properties': {
            'name': 'Portland, OR'
        },
        'geometry': {
            'type': 'Point',
            'coordinates': [-3.6803, 40.4067]
        }
    }

    bend = {
        'type': 'Feature',
        'properties': {
            'name': 'Bend, OR'
        },
        'geometry': {
            'type': 'Point',
            'coordinates': [-3.7703, 40.4067]
        }
    }
Ejemplo n.º 18
0
from mapbox import Static
import pygame, sys, os
import os.path
from all_nearest_planes import Flyover
from pygame.locals import *
import math
os.putenv('SDL_FBDEV', '/dev/fb1')
os.putenv('SDL_MOUSEDRV', 'TSLIB')
os.putenv('SDL_MOUSEDEV', '/dev/input/event0')

access_token = 'YOUR API KEY'
service = Static(access_token=access_token)

pygame.init()
pygame.mouse.set_visible(False)

#here is the width and the height of the LCD aka FB1
screen_width = 480
screen_height = 320

center_lon = -122.185724
center_lat = 37.617190

tile_zoom = 14
tile_dimension = 256
map_folder = "_vect"

# set up the window
#for the mini screen
DISPLAYSURF = pygame.display.set_mode((screen_width, screen_height))
#DISPLAYSURF = pygame.display.set_mode((screen_width, screen_height),pygame.FULLSCREEN)