def create_image_source(origin_uri, source_uri, image_folder, order, tile_dim): with rasterio.drivers(): with rasterio.open(source_uri) as src: shape = src.shape res = src.res bounds = src.bounds (ll_transform, ll_cols, ll_rows) = calculate_default_transform( src.crs, "EPSG:4326", src.shape[0], src.shape[1], src.bounds.left, src.bounds.bottom, src.bounds.right, src.bounds.top) w, n = ll_transform.xoff, ll_transform.yoff e, s = ll_transform * (ll_cols, ll_rows) ll_bounds = [w, s, e, n] (wm_transform, _, _) = calculate_default_transform( src.crs, "EPSG:3857", src.shape[0], src.shape[1], src.bounds.left, src.bounds.bottom, src.bounds.right, src.bounds.top) resolution = max(abs(wm_transform[0]), abs(wm_transform[4])) zoom = get_zoom(resolution, tile_dim) min_tile = mercantile.tile(ll_bounds[0], ll_bounds[3], zoom) max_tile = mercantile.tile(ll_bounds[2], ll_bounds[1], zoom) return ImageSource( origin_uri=origin_uri, source_uri=source_uri, src_bounds=src.bounds, src_shape=src.shape, src_crs=src.crs, zoom=zoom, ll_bounds=ll_bounds, tile_bounds=[min_tile.x, min_tile.y, max_tile.x, max_tile.y], image_folder=image_folder, order=order)
def read_tile(id, tile, scale=1): meta = get_metadata(id) maxzoom = int(meta['maxzoom']) minzoom = int(meta['minzoom']) if not minzoom <= tile.z <= maxzoom: raise InvalidTileRequest('Invalid zoom: {} outside [{}, {}]'.format( tile.z, minzoom, maxzoom)) sw = mercantile.tile(*meta['bounds'][0:2], zoom=tile.z) ne = mercantile.tile(*meta['bounds'][2:4], zoom=tile.z) if not sw.x <= tile.x <= ne.x: raise InvalidTileRequest( 'Invalid x coordinate: {} outside [{}, {}]'.format( tile.x, sw.x, ne.x)) if not ne.y <= tile.y <= sw.y: raise InvalidTileRequest( 'Invalid y coordinate: {} outside [{}, {}]'.format( tile.y, sw.y, ne.y)) data = render_tile(meta, tile, scale=scale) imgarr = np.ma.transpose(data, [1, 2, 0]).astype(np.byte) out = StringIO() im = Image.fromarray(imgarr, 'RGBA') im.save(out, 'png') return out.getvalue()
def get_bbox_tiles(self, zoom=18): bbox = self.get_bbox() ne = mercantile.tile(*bbox[2:], zoom=zoom) sw = mercantile.tile(*bbox[:2], zoom=zoom) return ne, sw
def validate_mbtiles(job): if "mbtiles" in job["export_formats"]: if job.get("mbtiles_source") is None: raise ValidationError("A source is required when generating an MBTiles archive.") if job.get("mbtiles_maxzoom") is None or job.get("mbtiles_minzoom") is None: raise ValidationError("A zoom range must be provided when generating an MBTiles archive.") bounds = job["the_geom"].extent tile_count = 0 for z in range(int(job["mbtiles_minzoom"]), int(job["mbtiles_maxzoom"])): sw = mercantile.tile(*bounds[0:2], zoom=z) ne = mercantile.tile(*bounds[2:4], zoom=z) width = 1 + ne[0] - sw[0] height = 1 + sw[1] - ne[1] tile_count += width * height if tile_count > MAX_TILE_COUNT: raise ValidationError( "%(tile_count)s tiles would be rendered; please reduce the zoom range, the size of your AOI, or split the export into pieces covering specific areas in order to render fewer than %(max_tile_count)s in each.", params={'tile_count': tile_count, 'max_tile_count': MAX_TILE_COUNT}, )
def Bounds(self, latitude, longitude): """ Method to calculate the pixel locations of the bounding box with a radius of self.radius given the center longitude and latitude coordinates Parameters ---------- latitude: latitude coordinate of the center of the bounding box in degrees longitude: longitude coordinate of the center of the bounding box in degrees Returns ------- minY: starting pixel location of the bounding box on the Y-axis maxY: ending pixel location of the bounding box on the Y-axis minX: starting pixel location of the bounding box on the X-axis maxX: ending pixel location of the bounding box on the X-axis """ minLat, minLon, maxLat, maxLon = boundingBox(latitude, longitude, self.radius) minX, minY = self.coord2pixel( minLon, maxLat, mercantile.bounds(mercantile.tile(longitude, latitude, self.zoom))) maxX, maxY = self.coord2pixel( maxLon, minLat, mercantile.bounds(mercantile.tile(longitude, latitude, self.zoom))) if minY < 0: minY += self.IMGSIZE maxY += self.IMGSIZE if minX < 0: minX += self.IMGSIZE maxX += self.IMGSIZE return minY, maxY, minX, maxX
def tile_exists(bounds, tile_z, tile_x, tile_y): """Check if a mercatile tile is inside a given bounds Attributes ---------- bounds : list WGS84 bounds (left, bottom, right, top). x : int Mercator tile Y index. y : int Mercator tile Y index. z : int Mercator tile ZOOM level. Returns ------- out : boolean if True, the z-x-y mercator tile in inside the bounds. """ mintile = mercantile.tile(bounds[0], bounds[3], tile_z) maxtile = mercantile.tile(bounds[2], bounds[1], tile_z) return (tile_x <= maxtile.x + 1) \ and (tile_x >= mintile.x) \ and (tile_y <= maxtile.y + 1) \ and (tile_y >= mintile.y)
def triangulate(zoom, output, bounds, tile, tableid): if bounds: bounds = np.array(bounds).astype(np.float64) elif tile: epsilon = 1.0e-10 tile = np.array(tile).astype(np.uint16) tBounds = mercantile.bounds(*tile) bounds = np.array([ tBounds.west + epsilon, tBounds.south + epsilon, tBounds.east - epsilon, tBounds.north - epsilon ]) else: sys.exit('Error: A bounds or tile must be specified') tileMin = mercantile.tile(bounds[0], bounds[3], zoom) tileMax = mercantile.tile(bounds[2], bounds[1], zoom) pGet = facetParent() if tableid: gJSON = createDBinit(tileMin, tileMax, zoom, pGet, tableid) else: gJSON = createFacets(tileMin, tileMax, zoom, pGet) if output: with open(output, 'w') as oFile: for feat in gJSON: oFile.write(json.dumps(feat) + '\n') else: for feat in gJSON: click.echo(json.dumps(feat))
def purge_record(bbox, tiles_generate): """ Purge the tiles in the bbox zone """ # Zoom minzoom = int(sys.argv[5]) maxzoom = int(sys.argv[6]) # Zone west = bbox["bbox"][0] south = bbox["bbox"][1] east = bbox["bbox"][2] north = bbox["bbox"][3] # Varnish connection host = sys.argv[7] port = sys.argv[8] for zoom in range(minzoom, maxzoom + 1): west_south_tile = mercantile.tile(west, south, zoom) east_north_tile = mercantile.tile(east, north, zoom) for x in range(west_south_tile.x, east_north_tile.x + 1): for y in range(east_north_tile.y, west_south_tile.y + 1): tile_already_generate = 0 url = "http://{0}:{1}/all/{2}/{3}/{4}.pbf".format(host, port, zoom, x, y) for tile in tiles_generate: if(tile == url): tile_already_generate = 1 break if(tile_already_generate == 0): print(zoom, x, y) tiles_generate.append(url) os.system('curl -s -X PURGE {0} > /dev/null 2>&1'.format(url)) return tiles_generate
def Download(self, latitude, longitude): """ Method to retrieve Mercartor tiles corresponding to the bounding box around longitude and latitude with radius self.radius Returns a list of 4 items, either the image of a tile or an empty object (None) Parameters ---------- latitude: latitude coordinate of the center of the desired bounding box in degrees longitude: longitude coordinate of the center of the desired bounding box in degrees Returns ------- images: list of PNG images corresponding to the Mercartor tiles """ minLat, minLon, maxLat, maxLon = boundingBox(latitude, longitude, self.radius) tiles = [ mercantile.tile(minLon, maxLat, self.zoom), # upleft mercantile.tile(maxLon, maxLat, self.zoom), # upright mercantile.tile(minLon, minLat, self.zoom), # downleft mercantile.tile(maxLon, minLat, self.zoom), # downright ] urls = [] images = [] for i, location in enumerate(self.locations): tile = tiles[i] url = self.base_url.format(tile.z, tile.x, tile.y) if url in urls: images.append(None) else: urls.append(urls.append(url)) images.append(PIL.Image.open(urllib.request.urlopen(url))) time.sleep(0.2) return images
def read_tile(id, tile, scale=1): meta = get_metadata(id) approximate_zoom = meta['meta']['approximateZoom'] bounds = meta['bounds'] height = meta['meta']['height'] width = meta['meta']['width'] zoom_offset = get_zoom_offset(width, height, approximate_zoom) min_zoom = approximate_zoom - zoom_offset if not min_zoom <= tile.z <= MAX_ZOOM: raise InvalidTileRequest('Invalid zoom: {} outside [{}, {}]'.format(tile.z, min_zoom, MAX_ZOOM)) sw = mercantile.tile(*bounds[0:2], zoom=tile.z) ne = mercantile.tile(*bounds[2:4], zoom=tile.z) if not sw.x <= tile.x <= ne.x: raise InvalidTileRequest('Invalid x coordinate: {} outside [{}, {}]'.format(tile.x, sw.x, ne.x)) if not ne.y <= tile.y <= sw.y: raise InvalidTileRequest('Invalid y coordinate: {} outside [{}, {}]'.format(tile.y, sw.y, ne.y)) data = render_tile(meta, tile, scale=scale) imgarr = np.ma.transpose(data, [1, 2, 0]).astype(np.byte) out = StringIO() im = Image.fromarray(imgarr, 'RGBA') im.save(out, 'png') return out.getvalue()
def triangulate(zoom, output, bounds=None, tile=None): if bounds: bounds = np.array(bounds).astype(np.float64) elif tile: epsilon = 1.0e-10 tile = np.array(tile).astype(np.uint16) tBounds = mercantile.bounds(*tile) bounds = np.array([ tBounds.west + epsilon, tBounds.south + epsilon, tBounds.east - epsilon, tBounds.north - epsilon ]) else: sys.exit('Error: A bounds or tile must be specified') tileMin = mercantile.tile(bounds[0], bounds[3], zoom) tileMax = mercantile.tile(bounds[2], bounds[1], zoom) pGet = facetParent() gJSON = createFacets(tileMin, tileMax, zoom, pGet) if output: with open(output, 'w') as oFile: for feat in gJSON: oFile.write(json.dumps(feat) + '\n') else: for feat in gJSON: click.echo(json.dumps(feat))
def tile_extrema(bounds, zoom): minimumTile = mercantile.tile(bounds[0], bounds[3], zoom) maximumTile = mercantile.tile(bounds[2], bounds[1], zoom) return { "x": {"min": minimumTile.x, "max": maximumTile.x + 1}, "y": {"min": minimumTile.y, "max": maximumTile.y + 1}, }
def coord_range_breakdown(bbox): # Topleft / Bottom right coordinates of the bounding box tl = [float(bbox['corner_nw'][0].split(',')[0]), float(bbox['corner_nw'][0].split(',')[1])] br = [float(bbox['corner_se'][0].split(',')[0]), float(bbox['corner_se'][0].split(',')[1])] # Set the resolution (max at 15) tl_tiles = mercantile.tile(tl[1],tl[0],z) br_tiles = mercantile.tile(br[1],br[0],z) return [tl_tiles.x,br_tiles.x], [tl_tiles.y,br_tiles.y]
def test_cog_translate_web(): """ Test Web-Optimized COG. - Test COG size is a multiple of 256 (mercator tile size) - Test COG bounds are aligned with mercator grid at max zoom """ runner = CliRunner() with runner.isolated_filesystem(): web_profile = cog_profiles.get("raw") web_profile.update({"blockxsize": 256, "blockysize": 256}) config = dict(GDAL_TIFF_OVR_BLOCKSIZE="128") cog_translate( raster_path_web, "cogeo.tif", web_profile, quiet=True, web_optimized=True, config=config, ) with rasterio.open(raster_path_web) as src_dst: with rasterio.open("cogeo.tif") as out_dst: blocks = list(set(out_dst.block_shapes)) assert len(blocks) == 1 ts = blocks[0][0] assert not out_dst.width % ts assert not out_dst.height % ts max_zoom = get_max_zoom(out_dst) bounds = list( transform_bounds( *[src_dst.crs, "epsg:4326"] + list(src_dst.bounds), densify_pts=21 ) ) leftTile = mercantile.tile(bounds[0], bounds[3], max_zoom) tbounds = mercantile.xy_bounds(leftTile) west, north = tbounds.left, tbounds.top assert out_dst.transform.xoff == west assert out_dst.transform.yoff == north rightTile = mercantile.tile(bounds[2], bounds[1], max_zoom) tbounds = mercantile.xy_bounds(rightTile) east, south = tbounds.right, tbounds.bottom lrx = round( out_dst.transform.xoff + out_dst.transform.a * out_dst.width, 6 ) lry = round( out_dst.transform.yoff + out_dst.transform.e * out_dst.height, 6 ) assert lrx == round(east, 6) assert lry == round(south, 6)
def tile_exists(self, z: int, x: int, y: int) -> bool: """Check if a mercator tile is within raster bounds.""" mintile = mercantile.tile(self.bounds[0], self.bounds[3], z) maxtile = mercantile.tile(self.bounds[2], self.bounds[1], z) return ( (x <= maxtile.x + 1) and (x >= mintile.x) and (y <= maxtile.y + 1) and (y >= mintile.y) )
def get_bbox(self, zoom=18): tile = self.get_tile(zoom) ne = mercantile.bounds( mercantile.tile(*mercantile.ul(tile.x + 1, tile.y + 1, zoom), zoom=zoom)) sw = mercantile.bounds( mercantile.tile(*mercantile.ul(tile.x - 1, tile.y - 1, zoom), zoom=zoom)) return sw.west, sw.south, ne.east, ne.north
def __init__(self, center, bbox, zoom, basemap, opacity, size=None): self._configure_event_loop() point = center['geometry']['coordinates'] if size is None: size = IMAGE_SIZE self.num_tiles = [ math.ceil(size[x] / TILE_SIZE[x]) + 1 for x in (0, 1) ] center_tile = mercantile.tile(point[0], point[1], zoom) mercator = Proj(init='epsg:3857') wgs84 = Proj(init='epsg:4326') center_tile_bbox = BBox(mercantile.bounds(*center_tile), projection=wgs84).project(mercator, edge_points=0) center_to_image = world_to_image(center_tile_bbox, TILE_SIZE) center_to_world = image_to_world(center_tile_bbox, TILE_SIZE) center_point_px = center_to_image(*mercantile.xy(*point)) self.ul_tile = mercantile.tile(*transform( mercator, wgs84, *center_to_world(center_point_px[0] - math.ceil(IMAGE_SIZE[0] / 2), center_point_px[1] - math.ceil(IMAGE_SIZE[1] / 2)), zoom)) lr_tile = mercantile.Tile(x=min(2**zoom, self.ul_tile.x + self.num_tiles[0]), y=min(2**zoom, self.ul_tile.y + self.num_tiles[1]), z=zoom) ul = mercantile.xy(*mercantile.ul(*self.ul_tile)) lr = mercantile.xy(*mercantile.ul(*lr_tile)) self.image_bbox = BBox((ul[0], lr[1], lr[0], ul[1])) self.image_size = (TILE_SIZE[0] * self.num_tiles[0], TILE_SIZE[1] * self.num_tiles[1]) self.to_image = world_to_image(self.image_bbox, self.image_size) self.to_world = image_to_world(self.image_bbox, self.image_size) self.point_px = [ round(x) for x in self.to_image(*mercantile.xy(*point)) ] self.target_size = size self.point = point self.zoom = zoom self.basemap = basemap self._basemap_image = None self.opacity = opacity
def handle(self, *args, **options): # the mission ul = (-122.424130, 37.764861) br = (-122.404819, 37.749389) ZOOM = 19 ul_tile = mercantile.tile(*ul + (ZOOM, )) br_tile = mercantile.tile(*br + (ZOOM, )) for x in range(ul_tile.x, br_tile.x + 1): for y in range(ul_tile.y, br_tile.y + 1): lng, lat = mercantile.ul(x, y, ZOOM) Tile.objects.get_or_create(pt=Point(lng, lat))
def get_map(lon_min, lon_max, lat_min, lat_max, zoom=19): """ Get an ESRI World Imagery map of the selected region Args: lon_min: Minimum longitude (degrees) lon_max: Maximum longitude (degrees) lat_min: Minimum latitude (degrees) lat_max: Maximum latitude (degrees) zoom: Zoom level Returns: np.array: Numpy array which can be plotted with plt.imshow """ upperleft_tile = mercantile.tile(lon_min, lat_max, zoom) xmin, ymin = upperleft_tile.x, upperleft_tile.y lowerright_tile = mercantile.tile(lon_max, lat_min, zoom) xmax, ymax = lowerright_tile.x, lowerright_tile.y total_image = np.zeros([256 * (ymax - ymin + 1), 256 * (xmax - xmin + 1), 3], dtype='uint8') os.makedirs("tilecache", exist_ok=True) tile_min = mercantile.tile(lon_min, lat_min, zoom) tile_max = mercantile.tile(lon_max, lat_max, zoom) wmts = WebMapTileService("http://server.arcgisonline.com/arcgis/rest/" + "services/World_Imagery/MapServer/WMTS/1.0.0/WMTSCapabilities.xml") for x in range(tile_min.x, tile_max.x + 1): for y in range(tile_max.y, tile_min.y + 1): tilename = os.path.join("tilecache", f"World_Imagery_{zoom}_{x}_{y}.jpg") if not os.path.isfile(tilename): tile = wmts.gettile(layer="World_Imagery", tilematrix=str(zoom), row=y, column=x) out = open(tilename, "wb") out.write(tile.read()) out.close() tile_image = imread(tilename) total_image[(y - ymin) * 256: (y - ymin + 1) * 256, (x - xmin) * 256: (x - xmin + 1) * 256] = tile_image total_llmin = {'lon': mercantile.bounds(xmin, ymax, zoom).west, 'lat': mercantile.bounds(xmin, ymax, zoom).south} total_llmax = {'lon': mercantile.bounds(xmax, ymin, zoom).east, 'lat': mercantile.bounds(xmax, ymin, zoom).north} pix_xmin = int(round(np.interp(lon_min, [total_llmin['lon'], total_llmax['lon']], [0, total_image.shape[1]]))) pix_ymin = int(round(np.interp(lat_min, [total_llmin['lat'], total_llmax['lat']], [0, total_image.shape[0]]))) pix_xmax = int(round(np.interp(lon_max, [total_llmin['lon'], total_llmax['lon']], [0, total_image.shape[1]]))) pix_ymax = int(round(np.interp(lat_max, [total_llmin['lat'], total_llmax['lat']], [0, total_image.shape[0]]))) return total_image[total_image.shape[0] - pix_ymax: total_image.shape[0] - pix_ymin, pix_xmin: pix_xmax]
def tile_extrema(bounds, zoom): minimumTile = mercantile.tile(bounds[0], bounds[3], zoom) maximumTile = mercantile.tile(bounds[2], bounds[1], zoom) return { 'x': { 'min': minimumTile.x, 'max': maximumTile.x + 1 }, 'y': { 'min': minimumTile.y, 'max': maximumTile.y + 1 } }
def create_image_source(origin_uri, source_uri, image_folder, order, tile_dim): with rasterio.drivers(): with rasterio.open(source_uri) as src: shape = src.shape res = src.res bounds = src.bounds (ll_transform, ll_cols, ll_rows) = calculate_default_transform( src.crs, "EPSG:4326", src.shape[0], src.shape[1], src.bounds.left, src.bounds.bottom, src.bounds.right, src.bounds.top, ) w, n = ll_transform.xoff, ll_transform.yoff e, s = ll_transform * (ll_cols, ll_rows) ll_bounds = [w, s, e, n] (wm_transform, _, _) = calculate_default_transform( src.crs, "EPSG:3857", src.shape[0], src.shape[1], src.bounds.left, src.bounds.bottom, src.bounds.right, src.bounds.top, ) resolution = max(abs(wm_transform[0]), abs(wm_transform[4])) zoom = get_zoom(resolution, tile_dim) min_tile = mercantile.tile(ll_bounds[0], ll_bounds[3], zoom) max_tile = mercantile.tile(ll_bounds[2], ll_bounds[1], zoom) return ImageSource( origin_uri=origin_uri, source_uri=source_uri, src_bounds=src.bounds, src_shape=src.shape, src_crs=src.crs, zoom=zoom, ll_bounds=ll_bounds, tile_bounds=[min_tile.x, min_tile.y, max_tile.x, max_tile.y], image_folder=image_folder, order=order, )
def read_tile(id, tile, scale=1, **kwargs): meta = get_metadata(id, **kwargs) maxzoom = int(meta['maxzoom']) minzoom = int(meta['minzoom']) if not minzoom <= tile.z <= maxzoom: raise InvalidTileRequest('Invalid zoom: {} outside [{}, {}]'.format(tile.z, minzoom, maxzoom)) sw = mercantile.tile(*meta['bounds'][0:2], zoom=tile.z) ne = mercantile.tile(*meta['bounds'][2:4], zoom=tile.z) if not sw.x <= tile.x <= ne.x: raise InvalidTileRequest('Invalid x coordinate: {} outside [{}, {}]'.format(tile.x, sw.x, ne.x)) if not ne.y <= tile.y <= sw.y: raise InvalidTileRequest('Invalid y coordinate: {} outside [{}, {}]'.format(tile.y, sw.y, ne.y)) data = render_tile(meta, tile, scale=scale) # 8-bit per pixel target_dtype = np.uint8 # default values from rio color atmo ops = meta['meta'].get('operations') if ops: # scale to (0..1) floats = (data * 1.0 / np.iinfo(data.dtype).max).astype(np.float32) for func in operations.parse_operations(ops): floats = func(floats) # scale back to uint8 data = (floats * np.iinfo(target_dtype).max).astype(target_dtype) if data.dtype != target_dtype: # rescale try: data = (data * (np.iinfo(target_dtype).max / np.iinfo(data.dtype).max)).astype(target_dtype) except: raise Exception('Not enough information to rescale; source is "{}""'.format(data.dtype)) imgarr = np.ma.transpose(data, [1, 2, 0]) out = StringIO() im = Image.fromarray(imgarr, 'RGBA') im.save(out, 'png') return out.getvalue()
def lookup_tile(lng, lat, zoom=ZOOM): tile = mercantile.tile(lng, lat, zoom) out_dir = "./tiles/" + str(VERSION) + "/" + str(zoom) + "/" + str( tile.y) + "/" + str(tile.x) filename = out_dir + "/" + str(tile.x) + "_" + str( tile.y) + "_" + str(zoom) + ".pbf" return filename
def get_tiles(self): tiles = [] square_4326 = self.userMarker.get_square_4326() for p in square_4326: mercent = mercantile.tile(p[1], p[0], 15) print(mercent) tiles.append([mercent.x, mercent.y]) x_matrix = [p[1] for p in tiles] y_matrix = [p[0] for p in tiles] x_matrix_max, x_matrix_min = max(x_matrix), min(x_matrix) y_matrix_max, y_matrix_min = max(y_matrix), min(y_matrix) total_x_axis_tiles = x_matrix_max - x_matrix_min + 1 total_y_axis_tiles = y_matrix_max - y_matrix_min + 1 print(total_x_axis_tiles, total_y_axis_tiles) top_left_tile = tiles[0] total_tiles_matrix = [] for x in range(total_x_axis_tiles): temp = [] for y in range(total_y_axis_tiles): temp.append([top_left_tile[0] - y, top_left_tile[1] + x]) total_tiles_matrix.append(temp) total_tiles_matrix = total_tiles_matrix[::-1] return total_tiles_matrix
def features_from_slice(ophoto, slc, detector, desc_extract, terrain_handler, zoom=15, bias=None): """ Takes in an orthophoto, slice tuple, detector, and extractor """ sub_photo = ophoto.get_img_from_slice(slc) kp1, desc1 = f2d.extract_features(sub_photo.img, detector, desc_extract) if len(kp1) > 0: pix = f2d.keypoint_pixels(kp1) meta = np.array([(kp.angle, kp.response, kp.size) for kp in kp1]) packed = f2d.numpySIFTScale(kp1) pts_wgs84 = sub_photo.pix_to_wgs84(pix) pts_hae = terrain_handler.add_heights(pts_wgs84) if bias is not None: print(bias) ref = pts_hae[0, [1, 0, 2]] pts_ned = navpy.lla2ned(pts_hae[:, 1], pts_hae[:, 0], pts_hae[:, 2], *ref) pts_ned -= bias pts_hae = np.vstack(navpy.ned2lla(pts_ned, *ref)).T pts_hae = pts_hae[:, [1, 0, 2]] tile_coords = np.array( [np.array(mercantile.tile(pt[0], pt[1], zoom)) for pt in pts_hae]) return (np.hstack((tile_coords, pts_hae, packed, meta)), desc1) else: return (None, None)
def flip_quadkey(q, flip): lng, lat = quadkey_to_centroid(q) z = len(q) if flip[0]: lng = -lng if flip[1]: lat = -lat tile = mercantile.tile(lng, lat, z) return mercantile.quadkey(tile)
def test_ul_tile_roundtrip(t): """ul and tile roundtrip""" lnglat = mercantile.ul(t) tile = mercantile.tile(lnglat.lng, lnglat.lat, t.z) assert tile.z == t.z assert tile.x == t.x assert tile.y == t.y
def main(): args = _get_clargs() size = ceil(args.size / 2) provider = providers[args.provider]() tp = ThreadPool(10) with tp: for zoom in range(args.max_zoom): tile = mercantile.tile(args.long, args.lat, zoom, truncate=True) x_center, y_center = tile.x, tile.y x_min = max(0, x_center - size) x_max = min(2**zoom - 1, x_center + size) y_min = max(0, y_center - size) y_max = min(2**zoom - 1, y_center + size) print(zoom, (x_min, x_max), (y_min, y_max)) results = [] for x in range(x_min, x_max + 1): for y in range(y_min, y_max + 1): res = tp.apply_async(_get_tile, args=(provider, zoom, x, y)) results.append(res) for result in results: result.get()
def add_tiles(self, zMin, zMax): zooms = np.arange(zMax - zMin + 2) + zMin - 1 obj = {zMin - 1: [mercantile.tile(-122.4, 37.5, zMin - 1)]} basepath = '%s/jpg' % (self.path) if not os.path.isdir(basepath): os.mkdir(basepath) for i in range(1, len(zooms)): tiles = [] os.mkdir("%s/%s" % (basepath, zooms[i])) for t in obj[zooms[i - 1]]: for tt in mercantile.children(t): tiles.append(tt) if os.path.isdir("%s/%s/%s" % (basepath, zooms[i], tt.x)): shutil.copy( self.imgs[int(np.random.rand() + 0.1)], "%s/%s/%s/%s.jpg" % (basepath, zooms[i], tt.x, tt.y)) else: os.mkdir("%s/%s/%s" % (basepath, zooms[i], tt.x)) shutil.copy( self.imgs[int(np.random.rand() + 0.1)], "%s/%s/%s/%s.jpg" % (basepath, zooms[i], tt.x, tt.y)) obj[zooms[i]] = tiles
def test_zoom(zoom: int) -> None: tested_zooms.add(zoom) tile: mercantile.Tile = mercantile.tile(centroid_x, centroid_y, zoom) # type: ignore tile_x: int = tile.x # type: ignore tile_y: int = tile.y # type: ignore query_url = url if "{-y}" in url: y = 2**zoom - 1 - tile_y query_url = query_url.replace("{-y}", str(y)) elif "{!y}" in url: y = 2**(zoom - 1) - 1 - tile_y query_url = query_url.replace("{!y}", str(y)) else: query_url = query_url.replace("{y}", str(tile_y)) parameters["x"] = tile_x parameters["zoom"] = zoom query_url = query_url.format(**parameters) url_is_good, http_code, mime = test_image(query_url, source_headers) if url_is_good: zoom_success.append(zoom) else: zoom_failures.append((zoom, query_url, http_code, mime))
def mt_tile_by_dim(lon, lat, bdim=BASE_DIM, asc=True, more=False): """ lon @float : Center longitude. lat @float : Center latitude. bdim @float : Base tile dimension in meters. returns: tt @mercantile.tile : Tile nearest to desidered dimension coontaining the point of given coordinates. zoom_level @integer : The tile zoom level. """ max_area = bdim**2 zooms = range(MT_MAX_ZOOM) if asc else reversed(range(MT_MAX_ZOOM)) for zoom_level in zooms: tt = mt.tile(lon, lat, zoom_level) bb = mt.xy_bounds(tt) if (bb.right - bb.left) * (bb.top - bb.bottom) < max_area: if asc: break elif not asc: break return tt if not more else ( tt, resolution, )
def add_tiles(self, zMin, zMax): zooms = np.arange(zMax - zMin + 2) + zMin - 1 obj = { zMin - 1: [mercantile.tile(-122.4, 37.5, zMin - 1)] } basepath = '%s/jpg' % (self.path) if not os.path.isdir(basepath): os.mkdir(basepath) for i in xrange(1, len(zooms)): tiles = [] os.mkdir("%s/%s" % (basepath, zooms[i])) for t in obj[zooms[i - 1]]: for tt in mercantile.children(t): tiles.append(tt) if os.path.isdir("%s/%s/%s" % (basepath, zooms[i], tt.x)): shutil.copy(self.imgs[int(np.random.rand() + 0.1)], "%s/%s/%s/%s.jpg" % (basepath, zooms[i], tt.x, tt.y)) else: os.mkdir("%s/%s/%s" % (basepath, zooms[i], tt.x)) shutil.copy(self.imgs[int(np.random.rand() + 0.1)], "%s/%s/%s/%s.jpg" % (basepath, zooms[i], tt.x, tt.y)) obj[zooms[i]] = tiles
def main(): m = folium.Map(location=skytree, zoom_start=18) # geojson読み込み geojson = r'japan.geojson' # m.choropleth(geo_data=geojson,fill_opacity=0.1) # 渋谷駅をマーク folium.Marker(skytree, popup='Shibuya St.').add_to(m) # 渋谷駅の位置情報からquadkeyの上位3層を生成 lat, lon = skytree for i in range(18, 21): bounds = mercantile.bounds(mercantile.tile(lon, lat, zoom=i)) print("{:16.12f} {:16.12f} {:16.12f} {:16.12f} {:8.4f}".format( *bounds, dist(latlon_to_yx([bounds.north, bounds.east]), latlon_to_yx([bounds.north, bounds.west])))) bounds_gj = make_geo_json(bounds.north, bounds.east, bounds.west, bounds.south) color = plt.cm.Reds(i / 10) color = mpl.colors.to_hex(color) gj = folium.GeoJson(bounds_gj, style_function=lambda feature, color=color: { 'fillColor': color, 'color': "black", 'weight': 1, 'dashArray': '5, 5', 'fillOpacity': 0.3, }) popup = folium.Popup("level {}".format(i)) gj.add_child(popup) m.add_child(gj) # 地図をhtml形式で出力 m.save(outfile=savename) print("save to {}".format(savename))
def test_super_res(): tile_coord = mercantile.tile(-115.24, 36.1986, 17) super_res_tile = tile_generator.create_super_tile_image( tile_coord, address=raster_address, zoom_level=2) np.testing.assert_array_equal(super_res_tile, mask_address_np)
def _make_tiles(bbox, src_crs, minz, maxz): ''' Given a bounding box, zoom range, and source crs, find all tiles that would intersect Parameters ----------- bbox: list [w, s, e, n] bounds src_crs: str the source crs of the input bbox minz: int minumum zoom to find tiles for maxz: int maximum zoom to find tiles for Returns -------- tiles: generator generator of [x, y, z] tiles that intersect the provided bounding box ''' w, s, e, n = transform_bounds(*[src_crs, 'epsg:4326'] + bbox, densify_pts=0) EPSILON = 1.0e-10 w += EPSILON s += EPSILON e -= EPSILON n -= EPSILON for z in range(minz, maxz + 1): for x, y in _tile_range( mercantile.tile(w, n, z), mercantile.tile(e, s, z)): yield [x, y, z]
def test_tile_truncate(): """Input is truncated""" assert mercantile.tile(-181.0, 0.0, 9, truncate=True) == mercantile.tile(-180.0, 0.0, 9)
return (xtile, ytile) def tile2degree(xtile, ytile, zoom): n = 2.0 ** zoom lng = xtile / n * 360.0 - 180.0 lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n))) lat = math.degrees(lat_rad) return (lng, lat) zoom = 22 # chongqing lng, lat = 106.516034, 29.543124 print lng, lat tile = mercantile.tile(lng, lat, zoom) print tile print mercantile.ul(*tile) box = mercantile.bounds(*tile) print box distance = great_circle((lat, box.west), (lat, box.east)) print distance.meters, 'm' distance = great_circle((box.north, lng), (box.south, lng)) print distance.meters, 'm' # beijing lng, lat = 116.324662, 39.961028 xtile, ytile = degree2tile(lng, lat, zoom) print lng, lat print xtile, ytile print tile2degree(xtile, ytile, zoom)
def test_tile(): tile = mercantile.tile(20.6852, 40.1222, 9) expected = (285, 193) assert tile[0] == expected[0] assert tile[1] == expected[1]