def rpc_renderArea(self, minlat, minlon, maxlat, maxlon): """ Renders a map for the given coordin """ Map = None LandmassShapefile = 'cape/Interface/ne_110m_admin_0_countries.shp' merc = mapnik.Projection( '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null ' '+no_defs +over') # long/lat in degrees, aka ESPG:4326 and "WGS 84" longlat = mapnik.Projection( '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # can also be constructed as: #longlat = mapnik.Projection('+init=epsg:4326') im = mapnik.Image(self.mapsize) m = self.rendermap m.srs = merc.params() bbox = mapnik.Box2d(minlat, minlon, maxlat, maxlon) transform = mapnik.ProjTransform(longlat, merc) merc_bbox = transform.forward(bbox) m.zoom_to_box(merc_bbox) mapnik.render(m, im) Map = im.tostring('png') return (True, Map)
def render_location(self): # spherical mercator (most common target map projection of osm data imported with osm2pgsql) merc = mapnik.Projection('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over') longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') mapfile = "renderer/map_data/styles/bs_complete.xml" bounds = (self.lon-self.size, self.lat-self.size, self.lon+self.size,self.lat+self.size) z = 1 imgx = 224 * z imgy = 224 * z m = mapnik.Map(imgx,imgy) mapnik.load_map(m,mapfile) m.srs = merc.params() if hasattr(mapnik,'Box2d'): bbox = mapnik.Box2d(*bounds) else: bbox = mapnik.Envelope(*bounds) transform = mapnik.ProjTransform(longlat,merc) merc_bbox = transform.forward(bbox) m.zoom_to_box(merc_bbox) #render the map to an image im = mapnik.Image(imgx,imgy) mapnik.render(m, im) img = im.tostring('png256') img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), 1) img =np.asarray(img) window_name = "Location" cv2.imshow(window_name, img) cv2.waitKey(0)
def render_location_with_variants(self, variants): # target projection #merc = mapnik.Projection('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over') data = [] for item in range(0,variants): if item == 0: teta = 0 zoom = 20 shift_lat = 0 shift_lon = 0 else: shift_lat = 0.1*self.size*(random.random()-random.random()) shift_lon = 0.1*self.size*(random.random()-random.random()) teta = 45 * (random.random()-random.random()) zoom = random.randint(17,21) layer = "complete" projec = mapnik.Projection('+proj=aeqd +ellps=WGS84 +lat_0=90 +lon_0='+str(teta)) # WGS lat/long source projection of centre longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # make a new Map object for the given mapfile m = mapnik.Map(self.width, self.height) mapfile = "renderer/map_data/styles/bs_" + layer + ".xml" mapnik.load_map(m, mapfile) # ensure the target map projection is mercator m.srs = projec.params() # transform the centre point into the target coord sys centre = mapnik.Coord(self.lon+shift_lon, self.lat+shift_lat) transform = mapnik.ProjTransform(longlat, projec) merc_centre = transform.forward(centre) # 360/(2**zoom) degrees = 256 px # so in merc 1px = (20037508.34*2) / (256 * 2**zoom) # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units dx = ((20037508.34*2*(self.width/2)))/(256*(2 ** (zoom))) minx = merc_centre.x - dx maxx = merc_centre.x + dx # grow the height bbox, as we only accurately set the width bbox m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT bounds = mapnik.Box2d(minx, merc_centre.y-10, maxx, merc_centre.y+10) # the y bounds will be fixed by mapnik due to ADJUST_BBOX_HEIGHT m.zoom_to_box(bounds) # render the map image to a file # mapnik.render_to_file(m, output) #render the map to an image im = mapnik.Image(self.width,self.height) mapnik.render(m, im) img = im.tostring('png256') img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), 1) img =np.asarray(img) data.append(img) data = np.stack(data) return data
def loop(self, nb): self.m = mapnik.Map(TILES_SIZE, TILES_SIZE) # Load style XML mapnik.load_map(self.m, self.mapfile, True) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = GoogleProjection(self.maxZoom + 1) while True: #Fetch a tile from the queue and render it r = self.q.get() if (r == None): self.q.task_done() break else: (name, tile_uri, x, y, z) = r exists = "" if os.path.isfile(tile_uri + '.' + FILE_EXTENSION): exists = "exists" else: self.render_tile(tile_uri, x, y, z) self.printLock.acquire() print name, ":", z, x, y, exists self.printLock.release() self.q.task_done()
def loop(self): self.m = mapnik.Map(128, 128) # Load style XML #mapnik.load_map(self.m, self.mapfile, True) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) #self.tileproj = GoogleProjection(self.maxZoom+1) while True: #Fetch a tile from the queue and render it r = self.q.get() if (r == None): self.q.task_done() break else: (name, bounds, data, item, label, lat, layer, lon, num_items, projec) = r self.rendertiles(bounds, data, item, label, lat, layer, lon, num_items, projec) self.printLock.acquire() self.printLock.release() self.q.task_done()
def render_legend(mapfile, tile_uri): m = mapnik.Map(1024, 2048) # Load style XML mapnik.load_map(m, mapfile, True) # Obtain <Map> projection prj = mapnik.Projection(m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) tileproj = GoogleProjection(20) # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = prj.forward(mapnik.Coord(14.4503,50.0673)) c1 = prj.forward(mapnik.Coord(14.457,50.0678)) # Bounding box for the tile if hasattr(mapnik,'mapnik_version') and mapnik.mapnik_version() >= 800: bbox = mapnik.Box2d(c0.x,c0.y, c1.x,c1.y) else: bbox = mapnik.Envelope(c0.x,c0.y, c1.x,c1.y) render_size_x = 1024 render_size_y = 1500 m.resize(render_size_x, render_size_y) m.zoom_to_box(bbox) m.buffer_size = 128 # Render image with default Agg renderer im = mapnik.Image(render_size_x, render_size_y) mapnik.render(m, im) im.save(tile_uri, 'png256') surface = cairo.SVGSurface('legend.svg', render_size_x, render_size_y) mapnik.render(m, surface) surface.finish()
def loop(self): self.m = mapnik.Map(256, 256) # Load style XML mapnik.load_map(self.m, self.mapfile, True) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = spherical_mercator.SphericalMercator(self.maxZoom + 1) while True: # Fetch a tile from the queue and render it r = self.q.get() if (r == None): self.q.task_done() break else: (name, tile_uri, x, y, z) = r exists = "" if os.path.isfile(tile_uri): exists = "exists" else: self.render_tile(tile_uri, x, y, z) bytes = os.stat(tile_uri)[6] empty = '' if bytes == 103: empty = " Empty Tile " self.printLock.acquire() print(name, ":", z, x, y, exists, empty) self.printLock.release() self.q.task_done()
def test_wgs84_inverse_forward(): p = mapnik2.Projection('+init=epsg:4326') c = mapnik2.Coord(3.01331418311, 43.3333092669) e = mapnik2.Box2d(-122.54345245, 45.12312553, 68.2335581353, 48.231231233) # It appears that the y component changes very slightly, is this OK? # so we test for 'almost equal float values' assert_almost_equal(p.inverse(c).y, c.y) assert_almost_equal(p.inverse(c).x, c.x) assert_almost_equal(p.forward(c).y, c.y) assert_almost_equal(p.forward(c).x, c.x) assert_almost_equal(p.inverse(e).center().y, e.center().y) assert_almost_equal(p.inverse(e).center().x, e.center().x) assert_almost_equal(p.forward(e).center().y, e.center().y) assert_almost_equal(p.forward(e).center().x, e.center().x) assert_almost_equal(c.inverse(p).y, c.y) assert_almost_equal(c.inverse(p).x, c.x) assert_almost_equal(c.forward(p).y, c.y) assert_almost_equal(c.forward(p).x, c.x) assert_almost_equal(e.inverse(p).center().y, e.center().y) assert_almost_equal(e.inverse(p).center().x, e.center().x) assert_almost_equal(e.forward(p).center().y, e.center().y) assert_almost_equal(e.forward(p).center().x, e.center().x)
def run(self): self.mapnik_map = mapnik2.Map(self.width, self.height) mapnik2.load_map(self.mapnik_map, self.config, True) self.map_projection = mapnik2.Projection(self.mapnik_map.srs) self.tile_projection = projections.GoogleProjection() while True: tile_parameters = None # Try to fetch a tile from any queue for tile_queue in self.tile_queues: try: tile_parameters = tile_queue.get_nowait() break except Queue.Empty: pass # Couldn't get tile parameters from any queue--all done if not tile_parameters: return # Skip rendering existing tiles if self.skip_existing: filename = tile_parameters[0] if os.path.exists(filename): print 'Skipping %s' % (filename) tile_queue.task_done() continue self.render(*tile_parameters) tile_queue.task_done()
def render_location_with_zoom(self, zoom): # target projection merc = mapnik.Projection('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over') # WGS lat/long source projection of centrel longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # make a new Map object for the given mapfile m = mapnik.Map(self.width, self.height) mapnik.load_map(m, self.mapfile) # ensure the target map projection is mercator m.srs = merc.params() # transform the centre point into the target coord sys centre = mapnik.Coord(self.lon, self.lat) transform = mapnik.ProjTransform(longlat, merc) merc_centre = transform.forward(centre) # 360/(2**zoom) degrees = 256 px # so in merc 1px = (20037508.34*2) / (256 * 2**zoom) # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units dx = ((20037508.34*2*(self.width/2)))/(256*(2 ** (zoom))) minx = merc_centre.x - dx maxx = merc_centre.x + dx # grow the height bbox, as we only accurately set the width bbox m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT bounds = mapnik.Box2d(minx, merc_centre.y-10, maxx, merc_centre.y+10) # the y bounds will be fixed by mapnik due to ADJUST_BBOX_HEIGHT m.zoom_to_box(bounds) # render the map image to a file # mapnik.render_to_file(m, output) #render the map to an image im = mapnik.Image(self.width,self.height) mapnik.render(m, im) img = im.tostring('png256') img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), 1) img =np.asarray(img) window_name = "Location" cv2.imshow(window_name, img) cv2.waitKey(1)
def __init__(self, tile_dir, mapfile, q, maxZoom): self.tile_dir = tile_dir self.q = q self.m = mapnik.Map(256, 256) # Load style XML mapnik.load_map(self.m, mapfile, False) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = GoogleProjection(maxZoom+1)
def __init__(self, tile_dir, mapfile, q, printLock, maxZoom): self.tile_dir = tile_dir self.q = q self.m = mapnik.Map(256, 256) self.printLock = printLock # Load style XML mapnik.load_map(self.m, mapfile, True) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = spherical_mercator.SphericalMercator(maxZoom + 1)
def test_render_points(): # Test for effectivenes of ticket #402 (borderline points get lost on reprojection) raise Todo("See: http://trac.mapnik2.org/ticket/402") if not mapnik2.has_pycairo(): return # create and populate point datasource (WGS84 lat-lon coordinates) places_ds = mapnik2.PointDatasource() places_ds.add_point(142.48, -38.38, 'Name', 'Westernmost Point') # westernmost places_ds.add_point(143.10, -38.60, 'Name', 'Southernmost Point') # southernmost # create layer/rule/style s = mapnik2.Style() r = mapnik2.Rule() symb = mapnik2.PointSymbolizer() symb.allow_overlap = True r.symbols.append(symb) s.rules.append(r) lyr = mapnik2.Layer('Places', '+proj=latlon +datum=WGS84') lyr.datasource = places_ds lyr.styles.append('places_labels') # latlon bounding box corners ul_lonlat = mapnik2.Coord(142.30, -38.20) lr_lonlat = mapnik2.Coord(143.40, -38.80) # render for different projections projs = { 'latlon': '+proj=latlon +datum=WGS84', 'merc': '+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs', 'google': '+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m', 'utm': '+proj=utm +zone=54 +datum=WGS84' } from cairo import SVGSurface for projdescr in projs.iterkeys(): m = mapnik2.Map(1000, 500, projs[projdescr]) m.append_style('places_labels', s) m.layers.append(lyr) p = mapnik2.Projection(projs[projdescr]) m.zoom_to_box(p.forward(mapnik2.Box2d(ul_lonlat, lr_lonlat))) # Render to SVG so that it can be checked how many points are there with string comparison import StringIO svg_memory_file = StringIO.StringIO() surface = SVGSurface(svg_memory_file, m.width, m.height) mapnik2.render(m, surface) surface.flush() surface.finish() svg = svg_memory_file.getvalue() svg_memory_file.close() num_points_present = len(places_ds.all_features()) num_points_rendered = svg.count('<image ') eq_( num_points_present, num_points_rendered, "Not all points were rendered (%d instead of %d) at projection %s" % (num_points_rendered, num_points_present, projdescr))
def __init__(self, areas): self.areas = areas self.tiles = None self.style = None # Set up projections # long/lat in degrees, aka ESPG:4326 and "WGS 84" # we get data in this projection longlat = mapnik2.Projection( '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # Map uses spherical mercator (most common target map projection of osm data imported with osm2pgsql) self.merc = mapnik2.Projection( '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over' ) # transform objects (Box2d and Coord) to another projection self.lnglat_to_merc_transform = mapnik2.ProjTransform( longlat, self.merc) self.merc_to_lnglat_transform = mapnik2.ProjTransform( self.merc, longlat)
def render_location(label, layers, location, num_items, num_threads, size, pano, writer): lat = location[0] lon = location[1] cpoint = [lon, lat] loc = GSV(lat, lon, 1) if loc.pano_list != [None]: with multiprocessing.Manager() as manager: data = manager.dict( ) # Create a list that can be shared between processes queue = multiprocessing.JoinableQueue(32) printLock = multiprocessing.Lock() renderers = {} for i in range(num_threads): renderer = RenderThread(queue, printLock) render_thread = multiprocessing.Process(target=renderer.loop) render_thread.start() #print "Started render thread %s" % render_thread.getName() renderers[i] = render_thread #---Generate num_tems images from shifting in the range [0,0.8*size] and rotating for item in range(0, num_items): if item == 0: shift_lat = 0 shift_lon = 0 teta = 0 zoom = 19 else: shift_lat = 0.1 * size * (rd.random() - rd.random()) shift_lon = 0.1 * size * (rd.random() - rd.random()) teta = 45 * (rd.random() - rd.random()) #45*rd.random() zoom = rd.randint(18, 21) for layer in layers: new_cpoint = [cpoint[0] + shift_lon, cpoint[1] + shift_lat] aeqd = mapnik.Projection( '+proj=aeqd +ellps=WGS84 +lat_0=90 +lon_0=' + str(teta)) t = ("Bristol", new_cpoint, data, item, label, lat, layer, lon, num_items, aeqd, zoom) queue.put(t) # Signal render threads to exit by sending empty request to queue for i in range(num_threads): queue.put(None) # wait for pending rendering jobs to complete queue.join() for i in range(num_threads): renderers[i].join() save_data(data, layers, label, lat, lon, num_items, pano, writer) else: print("No GSV for this location, not saving this location")
def load_map(self): start = time.perf_counter() self.m = mapnik.Map(0, 0) # Load style XML if not self.opts.dry_run: mapnik.load_map(self.m, self.opts.mapfile, self.opts.mapnik_strict) end = time.perf_counter() info('[%s] Map loading took %.6fs', self.name, end - start) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = map_utils.GoogleProjection(opts.max_zoom + 1)
def __init__(self, d, m): QObject.__init__(self) self.map_file = m self.tile_dir = d if not self.tile_dir.endswith('/'): self.tile_dir = self.tile_dir + '/' if not os.path.isdir(self.tile_dir): os.makedirs(self.tile_dir) self.m = mapnik2.Map(TILESIZE, TILESIZE) mapnik2.load_map(self.m, self.map_file, True) self.prj = mapnik2.Projection(self.m.srs) self.tileproj = GoogleProjection(MAX_ZOOM + 1) self.render_thread = RenderThread(self.m, self.prj, self.tileproj)
def render_location(label, layers, location, num_items, num_threads, size, writer): with multiprocessing.Manager() as manager: data = manager.dict( ) # Create a list that can be shared between processes queue = multiprocessing.JoinableQueue(32) printLock = multiprocessing.Lock() renderers = {} for i in range(num_threads): renderer = RenderThread(queue, printLock) render_thread = multiprocessing.Process(target=renderer.loop) render_thread.start() #print "Started render thread %s" % render_thread.getName() renderers[i] = render_thread lon = float(location[1].split('(')[1].split(')')[0].split()[0]) lat = float(location[1].split('(')[1].split(')')[0].split()[1]) cpoint = [lon, lat] #---Generate num_tems images from shifting in the range [0,0.8*size] and rotating for item in range(0, num_items + 1): if item == 0: shift_lat = 0 shift_lon = 0 teta = 0 else: shift_lat = 0.8 * size * (rd.random() - rd.random()) shift_lon = 0.8 * size * (rd.random() - rd.random()) teta = 360 * rd.random() for layer in layers: new_cpoint = [cpoint[0] + shift_lon, cpoint[1] + shift_lat] bounds = (new_cpoint[0] - size, new_cpoint[1] + size, new_cpoint[0] + size, new_cpoint[1] - size) aeqd = mapnik.Projection( '+proj=aeqd +ellps=WGS84 +lat_0=90 +lon_0=' + str(teta)) t = ("Bristol", bounds, data, item, label, lat, layer, lon, num_items, aeqd) queue.put(t) # Signal render threads to exit by sending empty request to queue for i in range(num_threads): queue.put(None) # wait for pending rendering jobs to complete queue.join() for i in range(num_threads): renderers[i].join() save_data(data, layers, label, lat, lon, num_items, writer)
def test_render_points(): if not mapnik2.has_cairo(): return # create and populate point datasource (WGS84 lat-lon coordinates) places_ds = mapnik2.PointDatasource() places_ds.add_point(142.48, -38.38, 'Name', 'Westernmost Point') # westernmost places_ds.add_point(143.10, -38.60, 'Name', 'Southernmost Point') # southernmost # create layer/rule/style s = mapnik2.Style() r = mapnik2.Rule() symb = mapnik2.PointSymbolizer() symb.allow_overlap = True r.symbols.append(symb) s.rules.append(r) lyr = mapnik2.Layer('Places', '+proj=latlon +datum=WGS84') lyr.datasource = places_ds lyr.styles.append('places_labels') # latlon bounding box corners ul_lonlat = mapnik2.Coord(142.30, -38.20) lr_lonlat = mapnik2.Coord(143.40, -38.80) # render for different projections projs = { 'latlon': '+proj=latlon +datum=WGS84', 'merc': '+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs', 'google': '+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m', 'utm': '+proj=utm +zone=54 +datum=WGS84' } for projdescr in projs.iterkeys(): m = mapnik2.Map(1000, 500, projs[projdescr]) m.append_style('places_labels', s) m.layers.append(lyr) p = mapnik2.Projection(projs[projdescr]) m.zoom_to_box(p.forward(mapnik2.Box2d(ul_lonlat, lr_lonlat))) # Render to SVG so that it can be checked how many points are there with string comparison svg_file = '/tmp/%s.svg' mapnik2.render_to_file(m, svg_file) num_points_present = len(places_ds.all_features()) svg = open(svg_file, 'r').read() num_points_rendered = svg.count('<image ') eq_( num_points_present, num_points_rendered, "Not all points were rendered (%d instead of %d) at projection %s" % (num_points_rendered, num_points_present, projdescr))
def rendertiles(self, cpoint, data, item, label, lat, layer, lon, num_items, projec, zoom): # target projection #merc = mapnik.Projection('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over') merc = projec # WGS lat/long source projection of centre longlat = mapnik.Projection( '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # make a new Map object for the given mapfile m = mapnik.Map(self.width, self.height) mapfile = "/map_data/styles/bs_" + layer + ".xml" mapnik.load_map(m, mapfile) # ensure the target map projection is mercator m.srs = merc.params() # transform the centre point into the target coord sys centre = mapnik.Coord(cpoint[0], cpoint[1]) transform = mapnik.ProjTransform(longlat, merc) merc_centre = transform.forward(centre) # 360/(2**zoom) degrees = 256 px # so in merc 1px = (20037508.34*2) / (256 * 2**zoom) # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units dx = ((20037508.34 * 2 * (self.width / 2))) / (256 * (2**(zoom))) minx = merc_centre.x - dx maxx = merc_centre.x + dx # grow the height bbox, as we only accurately set the width bbox m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT bounds = mapnik.Box2d( minx, merc_centre.y - 10, maxx, merc_centre.y + 10 ) # the y bounds will be fixed by mapnik due to ADJUST_BBOX_HEIGHT m.zoom_to_box(bounds) # render the map image to a file # mapnik.render_to_file(m, output) #render the map to an image im = mapnik.Image(self.width, self.height) mapnik.render(m, im) img = im.tostring('png256') data[(item, layer)] = img
def render_location(label, layers, location, size, writer): lon = float(location[1].split('(')[1].split(')')[0].split()[0]) lat = float(location[1].split('(')[1].split(')')[0].split()[1]) cpoint = [lon, lat] #---Generate 21 images from shifting in the range [0,0.8*size] and rotating for item in range(0 , 21) : if item == 0: shift_lat = 0 shift_lon = 0 teta = 0 else: shift_lat = 0.8*size*(rd.random()-rd.random()) shift_lon = 0.8*size*(rd.random()-rd.random()) teta = 360*rd.random() new_cpoint = [cpoint[0]+shift_lon, cpoint[1]+shift_lat] bounds = (new_cpoint[0]-size, new_cpoint[1]+size, new_cpoint[0]+size, new_cpoint[1]-size ) aeqd = mapnik.Projection('+proj=aeqd +ellps=WGS84 +lat_0=90 +lon_0='+str(teta)) rendertiles(bounds, item, label, lat, layers, lon, aeqd, writer)
def loop(self): self.m = mapnik.Map(TILE_SIZE, TILE_SIZE) # Load style XML mapnik.load_map(self.m, self.mapfile, True) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = GoogleProjection() while True: # Fetch a tile from the queue and render it r = self.q.get() if (r == None): self.q.task_done() break else: (x, y, z) = r exists = "" if self.writer.exists(x, y, z): exists = "exists" elif self.writer.need_image(): self.render_tile(x, y, z) else: self.writer.write(x, y, z) empty = '' # if os.path.exists(tile_uri): # bytes=os.stat(tile_uri)[6] # empty= '' # if bytes == 103: # empty = " Empty Tile " # else: # empty = " Missing " if self.verbose: self.printLock.acquire() print z, x, y, exists, empty self.printLock.release() self.q.task_done()
def generate_map_tile(self, m, filename, z, x, y): # Code taken from OSM generate_tiles.py proj = GoogleProjection() mprj = mapnik.Projection(m.srs) p0 = (x * 256, (y + 1) * 256) p1 = ((x + 1) * 256, y * 256) l0 = proj.fromPixelToLL(p0, z); l1 = proj.fromPixelToLL(p1, z); c0 = mprj.forward(mapnik.Coord(l0[0], l0[1])) c1 = mprj.forward(mapnik.Coord(l1[0], l1[1])) if hasattr(mapnik,'mapnik_version') and mapnik.mapnik_version() >= 800: bbox = mapnik.Box2d(c0.x, c0.y, c1.x, c1.y) else: bbox = mapnik.Envelope(c0.x, c0.y, c1.x, c1.y) m.resize(256, 256) m.zoom_to_box(bbox) im = mapnik.Image(256, 256) mapnik.render(m, im) im.save(str(filename), "png256")
#!/usr/bin/env python try: import mapnik2 as mapnik except: import mapnik import sys, os # Set up projections # spherical mercator (most common target map projection of osm data imported with osm2pgsql) merc = mapnik.Projection('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over') # long/lat in degrees, aka ESPG:4326 and "WGS 84" longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # can also be constructed as: #longlat = mapnik.Projection('+init=epsg:4326') # ensure minimum mapnik version if not hasattr(mapnik,'mapnik_version') and not mapnik.mapnik_version() >= 600: raise SystemExit('This script requires Mapnik >=0.6.0)') if __name__ == "__main__": try: mapfile = os.environ['MAPNIK_MAP_FILE'] except KeyError: mapfile = "/home/simon/osm/GWR/cantonal/namestats_road_ag.xml" map_uri = "/var/www/qa/ch-roads/namestats_road_ag.png" #---------------------------------------------------
class TileWorker(object): def __init__(self, map, instance, queue, xml): self.map = map self.label = "%s::%d" % (map.name, instance) self.queue = queue self.log("Running TileWorker") self.xml = xml def render_tile(self, zoom, x, y): t0 = time.time() tl = "(zoom=%s x=%s y=%s)" % (zoom, x, y) self.log("Rendering tile %s" % tl) # Convert tile index to LatLong (EPSG:4326) l0 = xy_to_ll(zoom, (x, y + 1)) l1 = xy_to_ll(zoom, (x + 1, y)) # Convert to map projection (e.g. mercator co-ords EPSG:900913) # and get tile's bounding box c0 = self.prj.forward(mapnik2.Coord(l0[0], l0[1])) c1 = self.prj.forward(mapnik2.Coord(l1[0], l1[1])) bbox = mapnik2.Box2d(c0.x, c0.y, c1.x, c1.y) # Render self.m.resize(TS, TS) self.m.zoom_to_box(bbox) self.m.buffer_size = 128 im = mapnik2.Image(TS, TS) mapnik2.render(self.m, im) data = im.tostring("png256") # Save to database tc = TileCache.objects.filter(map=self.map.id, zoom=zoom, x=x, y=y).first() if tc: tc.ready = True tc.last_updated = datetime.datetime.now() tc.data = data tc.save() else: TileCache(map=self.map.id, zoom=zoom, x=x, y=y, ready=True, last_updated=datetime.datetime.now(), data=data).save() self.log("Tile %s completed in %dms" % (tl, (time.time() - t0) * 1000)) def log(self, msg): logging.info("[%s]: %s" % (self.label, msg)) def run(self): self.log("Loading map XML") self.m = mapnik2.Map(TS, TS) try: mapnik2.load_map_from_string(self.m, self.xml) except RuntimeError, why: logging.error("Cannot load map: %s" % why) os._exit(1) self.prj = mapnik2.Projection(self.m.srs) self.log("Waiting for tasks") while True: t = self.queue.get() if t is None: self.log("Stopping") self.queue.task_done() break zoom, x, y = t self.render_tile(zoom, x, y) self.queue.task_done() self.log("Stopped")
map_uri = "image.png" #--------------------------------------------------- # Change this to the bounding box you want # #ll = (10.95,63.85, 11.05, 63.9) #ll = (10,63,11,64) ll = (6.8, 46.8, 7.2, 47.2) #ll= (0,10,0,10) #--------------------------------------------------- z = 10 imgx = 200 * z imgy = 200 * z m = mapnik2.Map(imgx, imgy) mapnik2.load_map(m, mapfile) prj = mapnik2.Projection("+init=epsg:3857 +over") #prj = mapnik2.Projection("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over") c0 = prj.forward(mapnik2.Coord(ll[0], ll[1])) c1 = prj.forward(mapnik2.Coord(ll[2], ll[3])) bbox = mapnik2.Box2d(c0.x, c0.y, c1.x, c1.y) #bbox=mapnik2.Box2d(-626172.1357121642,0,0,626172.1357121639) print c0, c1 print bbox m.zoom_to_box(bbox) im = mapnik2.Image(imgx, imgy) mapnik2.render(m, im) view = im.view(0, 0, imgx, imgy) # x,y,width,height view.save(map_uri, 'png256')
def loop(self): start = time.perf_counter() self.m = mapnik.Map(self.image_size, self.image_size) # Load style XML if not self.opts.dry_run: mapnik.load_map(self.m, self.opts.mapfile, True) end = time.perf_counter() debug('Map loading took %.6fs', end - start) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = map_utils.GoogleProjection(opts.max_zoom + 1) debug('%s looping the loop', self) while True: # Fetch a tile from the queue and render it t = self.queues[0].get() debug("[%s] ==> %r" % ( getpid(), t, )) if t is None: # self.q.task_done() debug('[%s] ending loop' % getpid()) break if self.opts.skip_existing or self.opts.skip_newer is not None: debug('skip test existing:%s, newer:%s', self.opts.skip_existing, self.opts.skip_newer) skip = True # we use min() so we can support low zoom levels # with less than metatile_size tiles for tile in t.tiles: if self.opts.skip_existing: skip = skip and self.backend.exists( tile.z, tile.x, tile.y) else: skip = (skip and self.backend.newer_than( tile.z, tile.x, tile.y, self.opts.skip_newer)) else: skip = False if not skip: render_children = self.render_metatile(t) else: if self.opts.skip_existing: info("%r: present, skipping" % t) else: info("%r: too new, skipping" % t) # but notify the children, so they get a chance to be rendered semi_metatile_size = max(self.metatile_size // 2, 1) render_children = {} for i in (0, semi_metatile_size): render_children[i] = {} for j in (0, semi_metatile_size): # we have no other info about whether they should be # rendered or not, so render them just in case. at worst, # they could either be empty tiles or too new too render_children[i][j] = True self.notify_children(render_children)
def test_normalizing_definition(): p = mapnik2.Projection('+init=epsg:4326') expanded = p.expanded() eq_('+proj=longlat' in expanded,True)
con.close() # Call function to create the views create_views(dsn, dbprefix, viewprefix, hstore, columns, date) # Create map with width height m = mapnik2.Map(pic_output_width, pic_output_height) # Load osm-xml-stylesheet for rendering the views # DB has to have the same name as cmd user mapnik2.load_map(m, path_to_osm_xml) # Define projection prj = mapnik2.Projection( "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" ) # Map bounds. Bound values come from SQL-query if hasattr(mapnik2, 'Box2d'): bbox = mapnik2.Box2d(xmin, ymin, xmax, ymax) else: bbox = mapnik2.Envelope(xmin, ymin, xmax, ymax) # Project bounds to map projection e = mapnik2.forward_(bbox, prj) # Zoom map to bounding box m.zoom_to_box(e) ###
class MapRenderer(RPCComponent.RPCComponent): """ """ mapsize = 1024, 768 mapfile = "./cape/Static/world_boundaries.xml" backgroundColor = '#114B7F' foregroundColor = '#6494BF' # long/lat in degrees, aka ESPG:4326 and "WGS 84" longlat = mapnik.Projection( '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # can also be constructed as: #longlat = mapnik.Projection('+init=epsg:4326') merc = mapnik.Projection( '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null ' '+no_defs +over') def rpc_renderCoord(self, lat, lon, zoom): im = mapnik.Image(self.mapsize[0], self.mapsize[1]) center = mapnik.Coord(lat, lon) transform = mapnik.ProjTransform(self.longlat, self.merc) merc_center = transform.forward(center) dx = (20037508.34 * 2 * (self.mapsize[0] / 2)) / (256 * (2**(zoom))) minx = merc_center.x - dx maxx = merc_center.x + dx self.rendermap.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT merc_bbox = mapnik.Box2d(minx, merc_center.y - 1, maxx, merc_center.y + 1) self.rendermap.zoom_to_box(merc_bbox) mapnik.render(self.rendermap, im) Map = im.tostring('png') return (True, Map) def rpc_renderCoordOld(self, lat, lon, zoom): """ Renders a map for the given coordinates. """ Map = None LandmassShapefile = 'cape/Interface/ne_110m_admin_0_countries.shp' im = mapnik.Image(self.mapsize[0], self.mapsize[1]) m = mapnik.Map(self.mapsize[0], self.mapsize[1]) m.background = mapnik.Color(self.backgroundColor) s = mapnik.Style() r = mapnik.Rule() polygon_symbolizer = mapnik.PolygonSymbolizer( mapnik.Color(self.foregroundColor)) r.symbols.append(polygon_symbolizer) line_symbolizer = mapnik.LineSymbolizer( mapnik.Color('rgb(50%,50%,50%)'), 0.1) r.symbols.append(line_symbolizer) s.rules.append(r) m.append_style('My Style', s) ds = mapnik.Shapefile(file=LandmassShapefile) layer = mapnik.Layer('world') layer.datasource = ds layer.styles.append('My Style') m.layers.append(layer) center = mapnik.Coord(lat, lon) transform = mapnik.ProjTransform(self.longlat, self.merc) merc_center = transform.forward(center) dx = (20037508.34 * 2 * (self.mapsize[0] / 2)) / (256 * (2**(zoom))) minx = merc_center.x - dx maxx = merc_center.x + dx m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT merc_bbox = mapnik.Box2d(minx, merc_center.y - 1, maxx, merc_center.y + 1) m.zoom_to_box(merc_bbox) mapnik.render(m, im) Map = im.tostring('png') return (True, Map) def rpc_renderArea(self, minlat, minlon, maxlat, maxlon): """ Renders a map for the given coordin """ Map = None LandmassShapefile = 'cape/Interface/ne_110m_admin_0_countries.shp' merc = mapnik.Projection( '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null ' '+no_defs +over') # long/lat in degrees, aka ESPG:4326 and "WGS 84" longlat = mapnik.Projection( '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # can also be constructed as: #longlat = mapnik.Projection('+init=epsg:4326') im = mapnik.Image(self.mapsize) m = self.rendermap m.srs = merc.params() bbox = mapnik.Box2d(minlat, minlon, maxlat, maxlon) transform = mapnik.ProjTransform(longlat, merc) merc_bbox = transform.forward(bbox) m.zoom_to_box(merc_bbox) mapnik.render(m, im) Map = im.tostring('png') return (True, Map) def __init__(self): self.MR['rpc_renderArea'] = { 'minlat': [float, "Minimal latitude of map."], 'minlon': [float, "Minimal longitude of map."], 'maxlat': [float, "Maximal latitude of map."], 'maxlon': [float, "Maximal longitude of map."], } self.MR['rpc_renderCoord'] = { 'lat': [float, "Minimal latitude of map."], 'lon': [float, "Minimal longitude of map."], 'zoom': [float, "Maximal longitude of map."], } self.rendermap = mapnik.Map(self.mapsize[0], self.mapsize[1]) mapnik.load_map(self.rendermap, self.mapfile) super(MapRenderer, self).__init__()