def main(file, **kwargs):
    """ Given an input layers file and a directory, print the compiled
        XML file to stdout and save any encountered external image files
        to the named directory.
    """
    mmap = mapnik.Map(1, 1)
    # allow [zoom] filters to work
    mmap.srs = '+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'
    cascadenik.load_map(mmap, file, **kwargs)
    
    (handle, filename) = tempfile.mkstemp(suffix='.xml', prefix='cascadenik-mapnik-')
    os.close(handle)
    mapnik.save_map(mmap, filename)
    
    if kwargs.get('pretty'):
        doc = ElementTree.fromstring(open(filename, 'rb').read())
        cascadenik._compile.indent(doc)
        f = open(filename, 'wb')
        doc.write(f)
        f.close()
        
    if kwargs.get('compiled'):
        os.rename(filename, kwargs['compiled'])
    else:
        print open(filename, 'r').read()
        os.unlink(filename)
    return 0
def main(src_file, dest_file, **kwargs):
    """ Given an input layers file and a directory, print the compiled
        XML file to stdout and save any encountered external image files
        to the named directory.
    """
    mmap = mapnik.Map(1, 1)
    # allow [zoom] filters to work
    mmap.srs = '+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'
    load_kwargs = dict([(k, v) for (k, v) in kwargs.items() if k in ('cache_dir', 'scale', 'verbose', 'datasources_cfg', 'user_styles')])
    cascadenik.load_map(mmap, src_file, dirname(realpath(dest_file)), **load_kwargs)
    
    (handle, tmp_file) = tempfile.mkstemp(suffix='.xml', prefix='cascadenik-mapnik-')
    os.close(handle)
    mapnik.save_map(mmap, tmp_file)
    
    if kwargs.get('pretty'):
        doc = ElementTree.fromstring(open(tmp_file, 'rb').read())
        cascadenik._compile.indent(doc)
        f = open(tmp_file, 'wb')
        ElementTree.ElementTree(doc).write(f)
        f.close()
        
    # manually unlinking seems to be required on windows
    if os.path.exists(dest_file):
        os.unlink(dest_file)

    os.chmod(tmp_file, 0666^os.umask(0))
    shutil.move(tmp_file, dest_file)
    return 0
Exemple #3
0
 def load_mml(self, m):
     import cascadenik
     if hasattr(cascadenik, 'VERSION'):
         major = int(cascadenik.VERSION.split('.')[0])
         if major < 1:
             from cascadenik import compile as _compile
             compiled = '%s_compiled.xml' % os.path.splitext(
                 self.mapfile)[0]
             open(compiled, 'w').write(_compile(self.mapfile))
             mapnik.load_map(m, compiled, True)
         elif major == 1:
             cascadenik.load_map(m,
                                 self.mapfile,
                                 self.output_dir,
                                 verbose=self.verbose)
         elif major > 1:
             raise NotImplementedError(
                 'This nik2img version does not yet support Cascadenik > 1.x, please upgrade nik2img to the latest release'
             )
     else:
         from cascadenik import compile as _compile
         compiled = os.path.join(
             self.output_dir, '%s_compiled.xml' %
             os.path.splitext(os.path.basename(self.mapfile))[0])
         output = _compile(self.mapfile)
         open(compiled, 'w').write(output)
         mapnik.load_map(m, compiled, True)
Exemple #4
0
def main(src_file, dest_file, **kwargs):
    """ Given an input layers file and a directory, print the compiled
        XML file to stdout and save any encountered external image files
        to the named directory.
    """
    mmap = mapnik.Map(1, 1)
    # allow [zoom] filters to work
    mmap.srs = '+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'
    load_kwargs = dict([(k, v) for (k, v) in kwargs.items() if k in ('cache_dir', 'verbose', 'datasources_cfg')])
    cascadenik.load_map(mmap, src_file, dirname(realpath(dest_file)), **load_kwargs)
    
    (handle, tmp_file) = tempfile.mkstemp(suffix='.xml', prefix='cascadenik-mapnik-')
    os.close(handle)
    mapnik.save_map(mmap, tmp_file)
    
    if kwargs.get('pretty'):
        doc = ElementTree.fromstring(open(tmp_file, 'rb').read())
        cascadenik._compile.indent(doc)
        f = open(tmp_file, 'wb')
        ElementTree.ElementTree(doc).write(f)
        f.close()
        
    # manually unlinking seems to be required on windows
    if os.path.exists(dest_file):
        os.unlink(dest_file)
    shutil.move(tmp_file, dest_file)
    return 0
Exemple #5
0
def main(file, **kwargs):
    """ Given an input layers file and a directory, print the compiled
        XML file to stdout and save any encountered external image files
        to the named directory.
    """
    mmap = mapnik.Map(1, 1)
    # allow [zoom] filters to work
    mmap.srs = '+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'
    cascadenik.load_map(mmap, file, **kwargs)

    (handle, filename) = tempfile.mkstemp(suffix='.xml',
                                          prefix='cascadenik-mapnik-')
    os.close(handle)
    mapnik.save_map(mmap, filename)

    if kwargs.get('pretty'):
        doc = ElementTree.fromstring(open(filename, 'rb').read())
        cascadenik._compile.indent(doc)
        f = open(filename, 'wb')
        doc.write(f)
        f.close()

    if kwargs.get('compiled'):
        os.rename(filename, kwargs['compiled'])
    else:
        print open(filename, 'r').read()
        os.unlink(filename)
    return 0
Exemple #6
0
def import_style_mml(url):
    """
    """
    # Create a local style.xml file by way of a dummy mapnik.Map instance.
    
    mmap = mapnik.Map(1, 1)
    mmap.srs = epsg3857
    cascadenik.load_map(mmap, url, 'gunicorn', verbose=False)
    mapnik.save_map(mmap, 'gunicorn/style.xml')
    
    # Build a new TileStache configuration file.
    
    config = json.load(open('gunicorn/tilestache.cfg'))
    
    config['layers'] = {'tiles': {'provider': {}}}
    layer = config['layers']['tiles']
    
    layer['provider']['name'] = 'mapnik'
    layer['provider']['mapfile'] = 'style.xml'
    layer['bounds'] = dict(zip('south west north east'.split(), options.bbox))
    layer['bounds'].update(dict(low=0, high=18))
    layer['preview'] = dict(zoom=15, lat=(options.bbox[0]/2 + options.bbox[2]/2), lon=(options.bbox[1]/2 + options.bbox[3]/2))
    
    # Done.
    
    json.dump(config, open('gunicorn/tilestache.cfg', 'w'), indent=2)
Exemple #7
0
 def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
     """ Mostly hand off functionality to Mapnik.ImageProvider.renderArea()
     """
     if self.mapnik is None:
         self.mapnik = mapnik.Map(0, 0)
         load_map(self.mapnik, str(self.mapfile), self.workdir, cache_dir=self.workdir)
     
     return ImageProvider.renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom)
Exemple #8
0
    def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
        """ Mostly hand off functionality to Mapnik.ImageProvider.renderArea()
        """
        if self.mapnik is None:
            self.mapnik = mapnik.Map(0, 0)
            load_map(self.mapnik,
                     str(self.mapfile),
                     self.workdir,
                     cache_dir=self.workdir)

        return ImageProvider.renderArea(self, width, height, srs, xmin, ymin,
                                        xmax, ymax, zoom)
def main(file, dir):
    """ Given an input layers file and a directory, print the compiled
        XML file to stdout and save any encountered external image files
        to the named directory.
    """
    mmap = mapnik.Map(1, 1)
    cascadenik.load_map(mmap, file, dir)
    
    (handle, filename) = tempfile.mkstemp(suffix='.xml', prefix='cascadenik-mapnik-')
    os.close(handle)
    
    mapnik.save_map(mmap, filename)
    print open(filename, 'r').read()
    
    os.unlink(filename)
    return 0
Exemple #10
0
def import_style_tdcfg(url):
    """ Load a Cascadenik style and its constituent pieces from a URL.
    """
    style = json.loads(urlopen(url).read())
    mapfile = urljoin(options.style, style['mapfile'])

    # Create a local style.xml file by way of a dummy mapnik.Map instance.
    
    mmap = mapnik.Map(1, 1)
    mmap.srs = epsg3857
    cascadenik.load_map(mmap, mapfile, 'gunicorn', verbose=False)
    mapnik.save_map(mmap, 'gunicorn/style.xml')
    
    # Build a new TileStache configuration file.
    
    config = json.load(open('gunicorn/tilestache.cfg'))
    
    config['layers'] = {'tiles': {'provider': {}}}
    layer = config['layers']['tiles']
    
    layer['provider']['name'] = 'mapnik'
    layer['provider']['mapfile'] = 'style.xml'
    layer['bounds'] = dict(zip('south west north east'.split(), options.bbox))
    layer['bounds'].update(dict(low=0, high=18))
    layer['preview'] = dict(zoom=15, lat=(options.bbox[0]/2 + options.bbox[2]/2), lon=(options.bbox[1]/2 + options.bbox[3]/2))
    
    # Apply various layer options.
    
    for (parameter, value) in style['layer'].items():
        if parameter == 'png options' and 'palette' in value:
            palette_url = urljoin(url, value['palette'])
            palette_data = urlopen(palette_url).read()
            palette_file = 'gunicorn/palette.act'
            
            print >> stderr, ' ', palette_file, '<--', palette_url
            
            open(palette_file, 'w').write(palette_data)
            value['palette'] = 'palette.act'
        
        layer[parameter] = value
    
    # Done.
    
    json.dump(config, open('gunicorn/tilestache.cfg', 'w'), indent=2)
Exemple #11
0
 def load_mml(self,m):
     import cascadenik
     if hasattr(cascadenik,'VERSION'):
         major = int(cascadenik.VERSION.split('.')[0])
         if major < 1:
             from cascadenik import compile as _compile
             compiled = '%s_compiled.xml' % os.path.splitext(self.mapfile)[0]
             open(compiled, 'w').write(_compile(self.mapfile))
             mapnik.load_map(m, compiled,True)
         elif major == 1:
             cascadenik.load_map(m,self.mapfile,self.output_dir,verbose=self.verbose)
         elif major > 1:
             raise NotImplementedError('This nik2img version does not yet support Cascadenik > 1.x, please upgrade nik2img to the latest release')
     else:
         from cascadenik import compile as _compile
         compiled = os.path.join(self.output_dir,'%s_compiled.xml' % os.path.splitext(os.path.basename(self.mapfile))[0])
         output = _compile(self.mapfile)
         open(compiled, 'w').write(output)
         mapnik.load_map(m, compiled,True)
Exemple #12
0
    def load_mml(self, refresh=False):
        self.from_mapfile = True
        self.mapfile_format = 'Cascadenik mml'
        if self.loaded_mapfile and refresh:
            mapfile = self.loaded_mapfile
        else:
            mapfile = QFileDialog.getOpenFileName(None, "Open file dialog", '',
                                                  "Cascadenik MML (*.mml)")
        if mapfile:
            self.mapnik_map = mapnik.Map(1, 1)
            import cascadenik
            if hasattr(cascadenik, 'VERSION'):
                major = int(cascadenik.VERSION.split('.')[0])
                if major < 1:
                    from cascadenik import compile
                    compiled = '%s_compiled.xml' % os.path.splitext(
                        str(mapfile))[0]
                    open(compiled, 'w').write(compile(str(mapfile)))
                    mapnik.load_map(self.mapnik_map, compiled)
                elif major == 1:
                    output_dir = os.path.dirname(str(mapfile))
                    cascadenik.load_map(self.mapnik_map,
                                        str(mapfile),
                                        output_dir,
                                        verbose=False)
                elif major > 1:
                    raise NotImplementedError(
                        'This nik2img version does not yet support Cascadenik > 1.x, please upgrade nik2img to the latest release'
                    )
            else:
                from cascadenik import compile
                compiled = '%s_compiled.xml' % os.path.splitext(
                    str(mapfile))[0]
                #if os.path.exits(compiled):
                #pass
                open(compiled, 'w').write(compile(str(mapfile)))
                mapnik.load_map(self.mapnik_map, compiled)

            if self.loaded_mapfile and refresh:
                self.set_mapnik_to_canvas()
            else:
                self.set_canvas_from_mapnik()
            self.loaded_mapfile = str(mapfile)
Exemple #13
0
    def load_mml(self, refresh=False):
        self.from_mapfile = True
        self.mapfile_format = "Cascadenik mml"
        if self.loaded_mapfile and refresh:
            mapfile = self.loaded_mapfile
        else:
            mapfile = QFileDialog.getOpenFileName(None, "Open file dialog", "", "Cascadenik MML (*.mml)")
        if mapfile:
            self.mapnik_map = mapnik.Map(1, 1)
            import cascadenik

            if hasattr(cascadenik, "VERSION"):
                major = int(cascadenik.VERSION.split(".")[0])
                if major < 1:
                    from cascadenik import compile

                    compiled = "%s_compiled.xml" % os.path.splitext(str(mapfile))[0]
                    open(compiled, "w").write(compile(str(mapfile)))
                    mapnik.load_map(self.mapnik_map, compiled)
                elif major == 1:
                    output_dir = os.path.dirname(str(mapfile))
                    cascadenik.load_map(self.mapnik_map, str(mapfile), output_dir, verbose=False)
                elif major > 1:
                    raise NotImplementedError(
                        "This nik2img version does not yet support Cascadenik > 1.x, please upgrade nik2img to the latest release"
                    )
            else:
                from cascadenik import compile

                compiled = "%s_compiled.xml" % os.path.splitext(str(mapfile))[0]
                # if os.path.exits(compiled):
                # pass
                open(compiled, "w").write(compile(str(mapfile)))
                mapnik.load_map(self.mapnik_map, compiled)

            if self.loaded_mapfile and refresh:
                self.set_mapnik_to_canvas()
            else:
                self.set_canvas_from_mapnik()
            self.loaded_mapfile = str(mapfile)
Exemple #14
0
    def __init__(self, mapfile, config=None):
        # private
        self._changed = []
        self._config = config
        self._locked = False

        self._log = logging.getLogger('tilelite')
        
        # mutable
        self.size = 256
        self.buffer_size = 128
        self.format = 'png'
        self.paletted = False
        self.max_zoom = 22
        self.debug = True
        self.watch_mapfile = False
        self.watch_interval = 2
        self.max_failures = 6

        self.caching = False
        self.cache_force = False
        self.cache_path = '/tmp' #tempfile.gettempdir()
        self.metatile = 0

        self._mapnik_map = mapnik.Map(self.size,self.size)

        if self._config:
            self.absorb_options(parse_config(self._config))

        self._mapfile = mapfile
        if mapfile.endswith('.xml'):
            mapnik.load_map(self._mapnik_map, self._mapfile)
        elif mapfile.endswith('.mml'):
            import cascadenik
            if hasattr(cascadenik,'VERSION'):
                major = int(cascadenik.VERSION.split('.')[0])
                if major < 1:
                    from cascadenik import compile as _compile
                    compiled = '%s_compiled.xml' % os.path.splitext(str(mapfile))[0]
                    open(compiled, 'w').write(_compile(self._mapfile))
                    mapnik.load_map(self._mapnik_map, compiled)
                elif major == 1:
                    if str(mapfile).startswith('http'):
                        output_dir = os.getcwd() #os.path.expanduser('~/.cascadenik')
                    else:
                        output_dir = os.path.dirname(str(mapfile))
                    cascadenik.load_map(self._mapnik_map,mapfile,output_dir,verbose=self.debug)
                elif major > 1:
                    raise NotImplementedError('This TileLite version does not yet support Cascadenik > 1.x, please upgrade to the latest release')
            else:
                from cascadenik import compile as _compile
                compiled = '%s_compiled.xml' % os.path.splitext(str(mapfile))[0]
                open(compiled, 'w').write(_compile(self._mapfile))
                mapnik.load_map(self._mapnik_map, compiled)

        self.post_init_setup()
        
        if self.watch_mapfile:
            self.modified = os.path.getmtime(self._mapfile)
            import thread
            thread.start_new_thread(self.watcher, ())
        self._mapnik_map.zoom_all()
        self.envelope = self._mapnik_map.envelope()

        self.empty_tile = mapnik.Image(self.size, self.size)
        if self._mapnik_map.background:
            self.empty_tile.background = self._mapnik_map.background