def tilelist(data,zooms): if (data["filetype"]): coordinates = MBTiles.list_tiles(data["filename"]) else: lat1, lon1, lat2, lon2 = data["bbox"] south, west = min(lat1, lat2), min(lon1, lon2) north, east = max(lat1, lat2), max(lon1, lon2) northwest = Location(north, west) southeast = Location(south, east) osm = Provider() ul = osm.locationCoordinate(northwest) lr = osm.locationCoordinate(southeast) for (i, zoom) in enumerate(zooms): if not zoom.isdigit(): raise KnownUnknown('"%s" is not a valid numeric zoom level.' % zoom) zooms[i] = int(zoom) if data["padding"] < 0: raise KnownUnknown('A negative padding will not work.') coordinates = generateCoordinates(ul, lr, zooms, data["padding"]) return coordinates
def clean_resource_cache(tile): # get the tile model's bounds datatype_factory = DataTypeFactory() nodegroup = models.NodeGroup.objects.get(pk=tile.nodegroup_id) for node in nodegroup.node_set.all(): datatype = datatype_factory.get_instance(node.datatype) if datatype.should_cache(node) and datatype.should_manage_cache(node): bounds = datatype.get_bounds(tile, node) if bounds is not None: zooms = range(20) config = TileStache.parseConfig( get_tileserver_config(node.nodeid)) layer = config.layers[str(node.nodeid)] mimetype, format = layer.getTypeByExtension('pbf') lon1, lat1, lon2, lat2 = bounds south, west = min(lat1, lat2), min(lon1, lon2) north, east = max(lat1, lat2), max(lon1, lon2) northwest = Location(north, west) southeast = Location(south, east) ul = layer.projection.locationCoordinate(northwest) lr = layer.projection.locationCoordinate(southeast) padding = 0 coordinates = generateCoordinates(ul, lr, zooms, padding) for (offset, count, coord) in coordinates: config.cache.remove(layer, coord, format) for key, tile_list in tile.tiles.iteritems(): for child_tile in tile_list: clean_resource_cache(child_tile)
def geometry_to_bounds(geometry): """ converts a django geometry to an envelope, and then converts this to TileStache's bounds """ if not geometry: raise ValueError('geometry is required') if geometry.empty: raise ValueError('empty geometries cannot be converted') if geometry.geom_type == 'Point': geometry = geometry.buffer(0.0001) envelope = geometry.envelope if not envelope: raise ValueError( 'this geometry does not have an envelope and its invalid') # this is an envelope, so for sure we have 5 coordinates dic = { 'south': envelope.coords[0][0][1], 'west': envelope.coords[0][0][0], 'north': envelope.coords[0][2][1], 'east': envelope.coords[0][2][0] } northwest = Location(dic['north'], dic['west']) southeast = Location(dic['south'], dic['east']) return {'nw': northwest, 'se': southeast}
def seed_resource_cache(): zooms = range(settings.CACHE_SEED_MAX_ZOOM + 1) extension = 'pbf' lat1, lon1, lat2, lon2 = settings.CACHE_SEED_BOUNDS south, west = min(lat1, lat2), min(lon1, lon2) north, east = max(lat1, lat2), max(lon1, lon2) northwest = Location(north, west) southeast = Location(south, east) padding = 0 datatypes = [ d.pk for d in models.DDataType.objects.filter(isgeometric=True) ] nodes = models.Node.objects.filter(graph__isresource=True, datatype__in=datatypes) for node in nodes: datatype = datatype_factory.get_instance(node.datatype) count = models.TileModel.objects.filter( data__has_key=str(node.nodeid)).count() if datatype.should_cache(node) and count > 0: config = TileStache.parseConfig(get_tileserver_config(node.nodeid)) layer = config.layers[str(node.nodeid)] ul = layer.projection.locationCoordinate(northwest) lr = layer.projection.locationCoordinate(southeast) coordinates = generateCoordinates(ul, lr, zooms, padding) for (offset, count, coord) in coordinates: path = '%s/%d/%d/%d.%s' % (layer.name(), coord.zoom, coord.column, coord.row, extension) progress = {"tile": path, "offset": offset + 1, "total": count} attempts = 3 rendered = False while not rendered: print '%(offset)d of %(total)d...' % progress, try: mimetype, content = TileStache.getTile( layer, coord, extension, True) except: attempts -= 1 print 'Failed %s, will try %s more.' % ( progress['tile'], ['no', 'once', 'twice' ][attempts]) if attempts == 0: print 'Failed %(zoom)d/%(column)d/%(row)d, trying next tile.\n' % coord.__dict__ break else: rendered = True progress['size'] = '%dKB' % (len(content) / 1024) print '%(tile)s (%(size)s)' % progress
def iterate_squares(ds, zoom): ''' ''' xoff, xstride, _, yoff, _, ystride = ds.GetGeoTransform() minlon, maxlat = xoff, yoff maxlon = xoff + ds.RasterXSize * xstride minlat = yoff + ds.RasterYSize * ystride if zoom > 11: maxlat = min(58, maxlat) osm = Provider() ul = osm.locationCoordinate(Location(maxlat, minlon)).zoomTo(zoom) lr = osm.locationCoordinate(Location(minlat, maxlon)).zoomTo(zoom) #lr = osm.locationCoordinate(Location(20, -60)).zoomTo(zoom) row = int(ul.row) while row < lr.row: lat = osm.coordinateLocation(Coordinate(row, 0, zoom)).lat print >> sys.stderr, 'lat:', round(lat, 2) col = int(ul.column) while col < lr.column: coord = Coordinate(row, col, zoom) sw = osm.coordinateLocation(coord.down()) ne = osm.coordinateLocation(coord.right()) west = max(minlon, sw.lon) north = min(maxlat, ne.lat) east = min(maxlon, ne.lon) south = max(minlat, sw.lat) left = round((west - xoff) / xstride) top = round((north - yoff) / ystride) width = round((east - xoff) / xstride) - left height = round((south - yoff) / ystride) - top yield (coord, south, north, int(left), int(top), int(width), int(height)) col += 1 row += 1 return x = xmin while x < xmax: print >> sys.stderr, 'lon:', x y = ymin while y < ymax: left = round((x - xoff) / xstride) top = round((y + size - yoff) / ystride) width, height = round(size / xstride), round(size / -ystride) yield (round(x, 2), round(y, 2), int(left), int(top), int(width), int(height)) y += size x += size
def invalidate_feature_cache(layer_key, features): """ invaldiates the cached tiles that contain the features @:param features: array of feature objects :return: """ logger.info("Invalidating features: {0}".format(features)) # get bbox of features dj_config = Config.objects.get() config = dj_config.tilestache_config_object logger.info("Config Cache: {0}".format(config.cache)) from TileStache.Caches import S3, Test if isinstance(config.cache, Test): return osm = Provider() try: ts_layer = config.layers[layer_key] except IndexError: logger.exception('Cannot invalidate %r', layer_key) return cleared = 0 keys = [] for f in features: lon1, lat1, lon2, lat2 = f.wkb_geometry.extent south, west = min(lat1, lat2), min(lon1, lon2) north, east = max(lat1, lat2), max(lon1, lon2) northwest = Location(north, west) southeast = Location(south, east) ul = osm.locationCoordinate(northwest) lr = osm.locationCoordinate(southeast) for coord in generate_coordinates(ul, lr, range(4, 19), padding=0): if isinstance(config.cache, S3.Cache): keys.append( S3.tile_key(ts_layer, coord, 'png', config.cache.path)) else: logger.info("ts_layer: {0}, coord: {1}".format( ts_layer, coord)) config.cache.remove(ts_layer, coord, 'png') cleared += 1 if keys: config.cache.bucket.delete_keys(keys) logger.info("cleared {0} TILES".format(cleared))
def list_tiles_for_bounds(image, s2p, paper_width_pt, paper_height_pt, north, west, south, east): """ Return a list of coordinates and scan-to-coord functions for a full set of zoom levels. Internal work is done by list_tiles_for_bounds_zoom(). """ osm = OpenStreetMapProvider() coords = [] for zoom in range(19): # # Coordinates of three print corners # ul = osm.locationCoordinate(Location(north, west)).zoomTo(zoom) ur = osm.locationCoordinate(Location(north, east)).zoomTo(zoom) lr = osm.locationCoordinate(Location(south, east)).zoomTo(zoom) # # Matching points in print and coordinate spaces # ul_pt = Point(1 * ptpin - paper_width_pt, 1.5 * ptpin - paper_height_pt) ul_co = Point(ul.column, ul.row) ur_pt = Point(0, 1.5 * ptpin - paper_height_pt) ur_co = Point(ur.column, ur.row) lr_pt = Point(0, 0) lr_co = Point(lr.column, lr.row) scan_dim = hypot(image.size[0], image.size[1]) zoom_dim = hypot((lr_co.x - ul_co.x) * 256, (lr_co.y - ul_co.y) * 256) if zoom_dim / scan_dim < .05: # too zoomed-out continue if zoom_dim / scan_dim > 3.: # too zoomed-in break # # scan2coord by way of scan2print and print2coord # p2c = triangle2triangle(ul_pt, ul_co, ur_pt, ur_co, lr_pt, lr_co) s2c = s2p.multiply(p2c) coords += list_tiles_for_bounds_zoom(image, s2c, zoom) return coords
def _parseLayerBounds(bounds_dict, projection): """ """ north, west = bounds_dict.get('north', 89), bounds_dict.get('west', -180) south, east = bounds_dict.get('south', -89), bounds_dict.get('east', 180) high, low = bounds_dict.get('high', 31), bounds_dict.get('low', 0) try: ul_hi = projection.locationCoordinate(Location(north, west)).zoomTo(high) lr_lo = projection.locationCoordinate(Location(south, east)).zoomTo(low) except TypeError: raise Core.KnownUnknown('Bad bounds for layer, need north, south, east, west, high, and low: ' + dumps(bounds_dict)) return Bounds(ul_hi, lr_lo)
def get_features(point, include_geom, layer_names): ''' Get a list of features found at the given point location. Thread calls to retrieve_zoom_features(). ''' loc = Location(point.GetY(), point.GetX()) def _retrieve_zoom_features(zoom, results): for result in retrieve_zoom_features(loc, zoom, include_geom, layer_names or None): results.append(result) start = time() results = [] if layer_names: # # Prepare one thread for each zoom_layer needed to get the named layers. # layer_needs = [(z, layer_names & zoom_layers[z]) for z in zoom_layers] layer_args = [(zoom, results) for (zoom, layers) in layer_needs if layers] else: layer_args = [(zoom, results) for zoom in zoom_layers] threads = [Thread(target=_retrieve_zoom_features, args=a) for a in layer_args] for t in threads: t.start() for t in threads: t.join() debug('results took %.3f seconds' % (time() - start)) return results
def get_extent(gjson): extent = {} m = MercatorProjection(0) b = get_bbox(extract_coords(gjson)) points = [[b[3], b[0]], [b[1], b[2]]] if (points[0][0] - points[1][0] == 0) or (points[1][1] - points[0][1] == 0): extent['lat'] = points[0][0] extent['lon'] = points[1][1] extent['zoom'] = 18 else: i = float('inf') w = 800 h = 600 tl = [ min(map(lambda x: x[0], points)), min(map(lambda x: x[1], points)) ] br = [ max(map(lambda x: x[0], points)), max(map(lambda x: x[1], points)) ] c1 = m.locationCoordinate(Location(tl[0], tl[1])) c2 = m.locationCoordinate(Location(br[0], br[1])) while (abs(c1.column - c2.column) * 256.0) < w and (abs(c1.row - c2.row) * 256.0) < h: c1 = c1.zoomBy(1) c2 = c2.zoomBy(1) center = m.coordinateLocation( Coordinate((c1.row + c2.row) / 2, (c1.column + c2.column) / 2, c1.zoom)) extent['lat'] = center.lat extent['lon'] = center.lon if c1.zoom > 18: extent['zoom'] = 18 else: extent['zoom'] = c1.zoom return extent
def location_point(self, lat, lon): """ Return a location and point object for the lat, lon pair. """ location = Location(float(lat), float(lon)) x, y = self.proj(location.lon, location.lat) point = Point(x / self.scale, y / self.scale) return location, point
def starting_tiles(buildings): ''' Get tile coordinates at min_zoom for a list of buildings. ''' minlat = min([b['latitude'] for b in buildings]) minlon = min([b['longitude'] for b in buildings]) maxlat = max([b['latitude'] for b in buildings]) maxlon = max([b['longitude'] for b in buildings]) osm = Provider() ul = osm.locationCoordinate(Location(maxlat, minlon)).zoomTo(min_zoom).container() lr = osm.locationCoordinate(Location(minlat, maxlon)).zoomTo(min_zoom).container() rows, cols = range(int(ul.row), int(lr.row+1)), range(int(ul.column), int(lr.column+1)) coords = [Coordinate(row, col, min_zoom) for (row, col) in product(rows, cols)] return coords
def location_point(self, lat, lon): """ Return a location and point object for the lat, lon pair. """ try: location = Location(float(lat), float(lon)) coord = _osm.locationCoordinate(location).zoomTo(self.zoom + 8) point = Point(coord.column - self.radius, self.radius - coord.row) return location, point except ValueError: raise Exception((lat, lon, zoom))
def location_point(lat, lon, zoom): """ Return a point that maps to pixels at the requested zoom level for 2^8 tile size. """ try: location = Location(float(lat), float(lon)) coord = _osm.locationCoordinate(location).zoomTo(zoom + 8) point = Point(coord.column, coord.row) return location, point except ValueError: raise Exception((lat, lon, zoom))
def projLocation(self, point): """ Convert from Point object in EPSG:4326 to a Location object """ return Location(point.y, point.x)
# output.writerow(fields) if options.radius > 0: others = PointIndex(options.zoom, options.radius) for place in input: if 'point size' not in place: place['point size'] = '8' if int(place['zoom start']) > options.zoom: continue if options.radius > 0: try: loc = Location(float(place['latitude']), float(place['longitude'])) except KeyError: try: loc = Location(float(place['lat']), float(place['long'])) except KeyError: loc = Location(float(place['lat']), float(place['lon'])) other = others.blocks(loc) if other: print >> stderr, place['name'], 'blocked by', other continue others.add(place['name'], loc) try: value = int(place[options.font_field])
label_geometry = bbox_polygon(place.label_bbox(), osm, zoom).__geo_interface__ label_features.append({'type': 'Feature', 'geometry': label_geometry, 'properties': properties }) dumpjson({'type': 'FeatureCollection', 'features': point_features}, open(pointsfile, 'w')) dumpjson({'type': 'FeatureCollection', 'features': label_features}, open(labelsfile, 'w')) print 'Wrote %d points to %s and %s.' % (len(point_features), pointsfile, labelsfile) print '-' * 80 map = mapByCenterZoom(osm, Location(0, 0), zoom, Point(2 ** (zoom + 8), 2 ** (zoom + 8))) if zoom > 5: map = mapByCenterZoom(osm, Location(40.078, -96.987), zoom, Point(1400, 800)) map = mapByCenterZoom(osm, Location(38.889, -77.050), zoom, Point(1200, 900)) img = map.draw(False) # newimg('RGB', (map.dimensions.x, map.dimensions.y), (0xFF, 0xFF, 0xFF)) draw = drawimg(img) print '-' * 80 sw = map.pointLocation(Point(-100, map.dimensions.y + 100)) ne = map.pointLocation(Point(map.dimensions.x + 100, -100)) previewed_places = [place for place in visible_places if (sw.lat < place.location.lat and place.location.lat < ne.lat
def main(apibase, password, print_id, pages, paper_size, orientation, layout): """ """ print_path = 'atlas.php?' + urlencode({'id': print_id}) print_href = print_id and urljoin(apibase.rstrip('/')+'/', print_path) or None print_info = {} # # Prepare a shorthands for pushing data. # _append_file = lambda name, body: print_id and append_print_file(print_id, name, body, apibase, password) or None _finish_print = lambda print_info: print_id and finish_print(apibase, password, print_id, print_info) or None _update_print = lambda progress: print_id and update_print(apibase, password, print_id, progress) or None print 'Print:', print_id print 'Paper:', orientation, paper_size, layout # # Prepare output context. # handle, print_filename = mkstemp(suffix='.pdf') close(handle) page_width_pt, page_height_pt, points_FG, hm2pt_ratio = paper_info(paper_size, orientation) print_context, finish_drawing = get_drawing_context(print_filename, page_width_pt, page_height_pt) try: map_xmin_pt = .5 * ptpin map_ymin_pt = 1 * ptpin map_xmax_pt = page_width_pt - .5 * ptpin map_ymax_pt = page_height_pt - .5 * ptpin map_bounds_pt = map_xmin_pt, map_ymin_pt, map_xmax_pt, map_ymax_pt # # Add pages to the PDF one by one. # for (index, page) in enumerate(pages): _update_print(0.1 + 0.9 * float(index) / len(pages)) page_href = print_href and (print_href + '/%(number)s' % page) or None provider = TemplatedMercatorProvider(page['provider']) zoom = page['zoom'] mark = page.get('mark', None) or None fuzzy = page.get('fuzzy', None) or None text = unicode(page.get('text', None) or '').encode('utf8') role = page.get('role', None) or None north, west, south, east = page['bounds'] northwest = Location(north, west) southeast = Location(south, east) page_mmap = mapByExtentZoom(provider, northwest, southeast, zoom) if role == 'index': indexees = [pages[other] for other in range(len(pages)) if other != index] else: indexees = [] add_print_page(print_context, page_mmap, page_href, map_bounds_pt, points_FG, hm2pt_ratio, layout, text, mark, fuzzy, indexees) # # Now make a smaller preview map for the page, # 600px looking like a reasonable upper bound. # preview_mmap = copy(page_mmap) while preview_mmap.dimensions.x > 600: preview_zoom = preview_mmap.coordinate.zoom - 1 preview_mmap = mapByExtentZoom(provider, northwest, southeast, preview_zoom) out = StringIO() preview_mmap.draw(fatbits_ok=True).save(out, format='JPEG', quality=85) preview_url = _append_file('preview-p%(number)s.jpg' % page, out.getvalue()) print_info['pages[%(number)s][preview_url]' % page] = preview_url # # Complete the PDF and upload it. # finish_drawing() pdf_name = 'field-paper-%s.pdf' % print_id pdf_url = _append_file(pdf_name, open(print_filename, 'r').read()) print_info['pdf_url'] = pdf_url except: raise finally: unlink(print_filename) # # Make a small preview map of the whole print coverage area. # provider = TemplatedMercatorProvider(pages[0]['provider']) norths, wests, souths, easts = zip(*[page['bounds'] for page in pages]) northwest = Location(max(norths), min(wests)) southeast = Location(min(souths), max(easts)) dimensions = Point(*get_preview_map_size(orientation, paper_size)) preview_mmap = mapByExtent(provider, northwest, southeast, dimensions) out = StringIO() preview_mmap.draw(fatbits_ok=True).save(out, format='JPEG', quality=85) preview_url = _append_file('preview.jpg' % page, out.getvalue()) print_info['preview_url'] = preview_url # # All done, wrap it up. # _finish_print(print_info)
start = time() results = [] threads = [ Thread(target=_retrieve_zoom_features, args=(loc, 10, results)), Thread(target=_retrieve_zoom_features, args=(loc, 8, results)) ] for t in threads: t.start() for t in threads: t.join() print >> stderr, 'results took', (time() - start), 'seconds' return results if __name__ == '__main__': print get_features(Location(47.620510, -122.349305)) # Space Needle print get_features(Location(37.805311, -122.272540)) # Oakland City Hall print get_features(Location(37.775793, -122.413549)) # Code for America print get_features(Location(40.753526, -73.976626)) # Grand Central Station print get_features(Location(38.871006, -77.055963)) # The Pentagon print get_features(Location(29.951057, -90.081090)) # The Superdome print get_features(Location(41.878874, -87.635907)) # Sears Tower
def clean_resource_cache(tile): if not settings.CACHE_RESOURCE_TILES: return # get the tile model's bounds bounds = None nodegroup = models.NodeGroup.objects.get(pk=tile.nodegroup_id) for node in nodegroup.node_set.all(): if node.datatype == 'geojson-feature-collection': node_data = tile.data[str(node.pk)] for feature in node_data['features']: shape = asShape(feature['geometry']) if bounds is None: bounds = shape.bounds else: minx, miny, maxx, maxy = bounds if shape.bounds[0] < minx: minx = shape.bounds[0] if shape.bounds[1] < miny: miny = shape.bounds[1] if shape.bounds[2] > maxx: maxx = shape.bounds[2] if shape.bounds[3] > maxy: maxy = shape.bounds[3] bounds = (minx, miny, maxx, maxy) if bounds is None: return zooms = range(20) config = parseConfig(get_tileserver_config()) layer = config.layers['resources'] mimetype, format = layer.getTypeByExtension('pbf') lon1, lat1, lon2, lat2 = bounds south, west = min(lat1, lat2), min(lon1, lon2) north, east = max(lat1, lat2), max(lon1, lon2) northwest = Location(north, west) southeast = Location(south, east) ul = layer.projection.locationCoordinate(northwest) lr = layer.projection.locationCoordinate(southeast) # start with a simple total of all the coordinates we will need. for zoom in zooms: ul_ = ul.zoomTo(zoom).container() lr_ = lr.zoomTo(zoom).container() rows = lr_.row + 1 - ul_.row cols = lr_.column + 1 - ul_.column # now generate the actual coordinates. coordinates = [] for zoom in zooms: ul_ = ul.zoomTo(zoom).container() lr_ = lr.zoomTo(zoom).container() for row in range(int(ul_.row), int(lr_.row + 1)): for column in range(int(ul_.column), int(lr_.column + 1)): coord = Coordinate(row, column, zoom) coordinates.append(coord) for coord in coordinates: config.cache.remove(layer, coord, format)
(just before the <a href="http://lists.openstreetmap.org/pipermail/talk/2012-January/061800.html">April, 2012</a> <a href="http://www.osmfoundation.org/wiki/License/We_Are_Changing_The_License">license changeover</a>) is available at <a href="http://archive.org/download/metro.teczno.com">archive.org</a>. Extracts here will continue to be updated into the future. </p> <ul> ''' cities.sort(key=lambda city: city['name']) for city in cities: slug = city['slug'] name = city['name'] try: ul = Location(float(city['top']), float(city['left'])) lr = Location(float(city['bottom']), float(city['right'])) except ValueError: print >> stderr, 'Failed on %(name)s (%(slug)s)' % city raise else: mmap = mapByExtent(provider, ul, lr, dimensions) if slug in files: bz2_file, bz2_size, bz2_href = files[slug]['bz2'] pbf_file, pbf_size, pbf_href = files[slug]['pbf'] list = ('<li class="file"><a href="%s">%s %s OSM data</a></li>' * 2) \ % (bz2_href, nice_size(bz2_size), 'bzip’ed XML', pbf_href, nice_size(pbf_size), 'binary PBF')
if value > min_value: place['point size'] = size # # suppress irrelevant compilations # if int(place[ options.zoom_field ]) > options.zoom: continue # # should we do a rough spatial filter where this town blows out other towns? # if options.radius > 0: loc = Location(*row_location(place)) other = others.blocks(loc) if other: print >> stderr, place['name'], 'blocked by', other continue others.add(place['name'], loc) try: value = int(place[options.population_field.lower()]) except ValueError: value = place[options.population_field.lower()] for (min_value, font, size) in fonts: if value > min_value:
def add_print_page(ctx, mmap, href, well_bounds_pt, points_FG, hm2pt_ratio, layout, text, mark, fuzzy, indexees): """ """ print 'Adding print page:', href well_xmin_pt, well_ymin_pt, well_xmax_pt, well_ymax_pt = well_bounds_pt well_width_pt, well_height_pt = well_xmax_pt - well_xmin_pt, well_ymax_pt - well_ymin_pt well_aspect_ratio = well_width_pt / well_height_pt # # Offset drawing area to top-left of map area # ctx.translate(well_xmin_pt, well_ymin_pt) # # Build up map area # img = get_mmap_image(mmap) if layout == 'half-page' and well_aspect_ratio > 1: map_width_pt, map_height_pt = well_width_pt/2, well_height_pt add_page_text(ctx, text, map_width_pt + 24, 24, map_width_pt - 48, map_height_pt - 48) elif layout == 'half-page' and well_aspect_ratio < 1: map_width_pt, map_height_pt = well_width_pt, well_height_pt/2 add_page_text(ctx, text, 32, map_height_pt + 16, map_width_pt - 64, map_height_pt - 32) else: map_width_pt, map_height_pt = well_width_pt, well_height_pt place_image(ctx, img, 0, 0, map_width_pt, map_height_pt) # # Draw a dot if need be # if fuzzy is not None: loc = Location(fuzzy[1], fuzzy[0]) pt = mmap.locationPoint(loc) x = map_width_pt * float(pt.x) / mmap.dimensions.x y = map_height_pt * float(pt.y) / mmap.dimensions.y draw_circle(ctx, x, y, 20) ctx.set_source_rgb(0, 0, 0) ctx.set_line_width(2) ctx.set_dash([2, 6]) ctx.stroke() # # X marks the spot, if needed # if mark is not None: loc = Location(mark[1], mark[0]) pt = mmap.locationPoint(loc) x = map_width_pt * float(pt.x) / mmap.dimensions.x y = map_height_pt * float(pt.y) / mmap.dimensions.y draw_cross(ctx, x, y, 8, 6) ctx.set_source_rgb(1, 1, 1) ctx.fill() draw_cross(ctx, x, y, 8, 4) ctx.set_source_rgb(0, 0, 0) ctx.fill() # # Perhaps some boxes? # page_numbers = [] for page in indexees: north, west, south, east = page['bounds'] ul = mmap.locationPoint(Location(north, west)) lr = mmap.locationPoint(Location(south, east)) x1 = map_width_pt * float(ul.x) / mmap.dimensions.x x2 = map_width_pt * float(lr.x) / mmap.dimensions.x y1 = map_height_pt * float(ul.y) / mmap.dimensions.y y2 = map_height_pt * float(lr.y) / mmap.dimensions.y draw_box(ctx, x1, y1, x2-x1, y2-y1) ctx.set_source_rgb(0, 0, 0) ctx.set_line_width(1) ctx.set_dash([]) ctx.stroke() page_numbers.append((x1, y1, x2, y2, page['number'])) # # Calculate positions of registration points # ctx.save() ctx.translate(well_width_pt, well_height_pt) ctx.scale(1/hm2pt_ratio, 1/hm2pt_ratio) reg_points = (point_A, point_B, point_C, point_D, point_E) + points_FG device_points = [ctx.user_to_device(pt.x, pt.y) for pt in reg_points] ctx.restore() # # Draw QR code area # ctx.save() ctx.translate(well_width_pt, well_height_pt) draw_box(ctx, 0, 0, -90, -90) ctx.set_source_rgb(1, 1, 1) ctx.fill() place_image(ctx, get_qrcode_image(href), -83, -83, 83, 83) ctx.restore() # # Draw registration points # for (x, y) in device_points: x, y = ctx.device_to_user(x, y) draw_circle(ctx, x, y, .12 * ptpin) ctx.set_source_rgb(0, 0, 0) ctx.set_line_width(.5) ctx.set_dash([1.5, 3]) ctx.stroke() for (x, y) in device_points: x, y = ctx.device_to_user(x, y) draw_circle(ctx, x, y, .12 * ptpin) ctx.set_source_rgb(1, 1, 1) ctx.fill() for (x, y) in device_points: x, y = ctx.device_to_user(x, y) draw_circle(ctx, x, y, .06 * ptpin) ctx.set_source_rgb(0, 0, 0) ctx.fill() # # Draw top-left icon # icon = pathjoin(dirname(__file__), 'images/logo.png') img = ImageSurface.create_from_png(icon) place_image(ctx, img, 0, -36, 129.1, 36) try: font_file = realpath('fonts/LiberationSans-Regular.ttf') if font_file not in cached_fonts: cached_fonts[font_file] = create_cairo_font_face_for_file(font_file) font = cached_fonts[font_file] except: # no text for us. pass else: ctx.set_font_face(font) ctx.set_font_size(12) line = href text_width = ctx.text_extents(line)[2] ctx.move_to(well_width_pt - text_width, -6) ctx.show_text(line) add_scale_bar(ctx, mmap, map_height_pt) ctx.set_font_face(font) ctx.set_font_size(18) for (x1, y1, x2, y2, number) in page_numbers: number_w, number_h = ctx.text_extents(number)[2:4] offset_x, offset_y = (x1 + x2 - number_w) / 2, (y1 + y2 + number_h) / 2 draw_box(ctx, offset_x - 4, offset_y - number_h - 4, number_w + 8, number_h + 8) ctx.set_source_rgb(1, 1, 1) ctx.fill() ctx.set_source_rgb(0, 0, 0) ctx.move_to(offset_x, offset_y) ctx.show_text(number) ctx.show_page()
def projLocation(self, point): """Convert from Point object in the defined projection to a Location object""" x,y = self.proj(point.x, point.y, inverse=True) return Location(y, x)
def start_seed(self): print("TilestacheSeeder run seed") options = self.assign_default_value(self.options) config = buildConfiguration(options['config']) layer = config.layers[options['name']] bbox = self.get_bbox(options['bbox']) self.validate_bbox(bbox) northwest = Location(bbox['north'], bbox['west']) southeast = Location(bbox['south'], bbox['east']) ul = layer.projection.locationCoordinate(northwest) lr = layer.projection.locationCoordinate(southeast) coordinates = self.get_coordinates( options, { 'ul': ul, 'lr': lr, 'zooms': options['zooms'], 'padding': options['padding'] }) ignore_cached = options['ignore_cached'] extension = options['extension'] verbose = options['verbose'] for (offset, count, coord) in coordinates: path = '%s/%d/%d/%d.%s' % (layer.name(), coord.zoom, coord.column, coord.row, options['extension']) progress = {"tile": path, "offset": offset + 1, "total": count} # # Fetch a tile. # attempts = options['enable_retries'] rendered = False while not rendered: if verbose: print('%(offset)d of %(total)d...' % progress, end=' ', file=stderr) # print("{offset} of {total}...".format(offset=progress['offset'], total=progress['total'])) try: mimetype, content = getTile(layer, coord, extension, ignore_cached) if mimetype and 'json' in mimetype and options['callback']: js_path = '%s/%d/%d/%d.js' % (layer.name(), coord.zoom, coord.column, coord.row) js_body = '%s(%s);' % (options['callback'], content) js_size = len(js_body) / 1024 layer.config.cache.save(js_body, layer, coord, 'JS') print('%s (%dKB)' % (js_path, js_size), end=' ', file=stderr) elif options['callback']: print('(callback ignored)', end=' ', file=stderr) except: # # Something went wrong: try again? Log the error? # attempts -= 1 if verbose: print('Failed %s, will try %s more.' % (progress['tile'], ['no', 'once', 'twice' ][attempts]), file=stderr) if attempts == 0: if not options['error_list']: raise fp = open(options['error_list'], 'a') fp.write('%(zoom)d/%(column)d/%(row)d\n' % coord.__dict__) fp.close() break else: # # Successfully got the tile. # rendered = True progress['size'] = '%dKB' % (len(content) / 1024) if verbose: print('%(tile)s (%(size)s)' % progress, file=stderr) if options['progressfile']: fp = open(options['progressfile'], 'w') json_dump(progress, fp) fp.close()
from TileStache import requestHandler from ModestMaps.OpenStreetMap import Provider from ModestMaps.Geo import Location from json import loads osm = Provider() loc = Location(37.795545, -122.393422) stuff = [ ('highroad', 10), ('highroad', 11), ('highroad', 12), ('highroad', 13), ('highroad', 14), ('highroad', 15), ('highroad-2x', 9), ('highroad-2x', 10), ('highroad-2x', 11), ('highroad-2x', 12), ('highroad-2x', 13), ('highroad-2x', 14), ('skeletron', 12), ('skeletron', 13), ('skeletron', 14), ('skeletron', 15), ('skeletron', 16), ('skeletron-2x', 11), ('skeletron-2x', 12), ('skeletron-2x', 13), ('skeletron-2x', 14), ('skeletron-2x', 15),
try: (previews, ) = argv[1:] except ValueError: print >> stderr, 'Usage: compose-city-previews.py <previews directory>' exit(1) for city in cities: if not city['name']: raise Exception('Need a name for ' + str(city)) print >> stderr, city['name'], '...', north, west = float(city['top']), float(city['left']) south, east = float(city['bottom']), float(city['right']) mmap = mapByExtent(provider, Location(north, west), Location(south, east), dimensions) ul = mmap.locationPoint(Location(north, west)) lr = mmap.locationPoint(Location(south, east)) bbox = [(p.x, p.y) for p in (ul, lr)] img = mmap.draw() mask = Image.new('L', img.size, 0x99) ImageDraw(mask).rectangle(bbox, fill=0x00) img.paste((0xFF, 0xFF, 0xFF), (0, 0), mask) frame = Image.new('L', img.size, 0x00) ImageDraw(frame).rectangle(bbox, outline=0x33) img.paste((0x00, 0x00, 0x00), (0, 0), frame)
# do the actual work lat1, lon1, lat2, lon2 = options.bbox south, west = min(lat1, lat2), min(lon1, lon2) north, east = max(lat1, lat2), max(lon1, lon2) if not (-90.0 < south < 90.0) or not (-90.0 < north < 90.0): raise KnownUnknown( 'Latitude must be a value between -90 and 90 ' '(Hint: Maybe you did long/lat instead of lat/long?).') if not (-180.0 < west < 180.0) or not (-180.0 < east < 180.0): raise KnownUnknown( 'Longitude must be a value between -180 and 180.') northwest = Location(north, west) southeast = Location(south, east) ul = layer.projection.locationCoordinate(northwest) lr = layer.projection.locationCoordinate(southeast) for (i, zoom) in enumerate(zooms): if not zoom.isdigit(): raise KnownUnknown('"%s" is not a valid numeric zoom level.' % zoom) zooms[i] = int(zoom) if options.padding < 0: raise KnownUnknown('A negative padding will not work.')
logging.basicConfig(level=logging.DEBUG, format='%(filename)s %(lineno)d - %(msg)s') p = get_projection() if len(argv) == 1: lat, lon = 37.804310, -122.271164 zoom = 16 elif len(argv) == 4: lat, lon = map(float, argv[1:3]) zoom = int(argv[3]) else: raise Exception('oops') loc = Location(lat, lon) coord = p.locationCoordinate(loc).zoomTo(zoom) textures = get_tile_data(coord) # # Output .obj files and JPEGs locally. # for (index, (vertices, faces, image_url)) in enumerate(textures): obj = open('out-%d.obj' % index, 'w') for (x, y, z, u, v) in vertices: print >> obj, 'v %.1f %.1f %.1f' % (x, y, z)