def render_map(args): cfg = read_map_descriptor(args.config) K = Kartograph() if args.format: format = args.format elif args.output and args.output != '-': format = os.path.splitext(args.output)[1][1:] else: format = 'svg' try: # generate the map if args.style: css = args.style.read() else: css = None if args.output is None and not args.preview: args.output = '-' if args.output and args.output != '-': args.output = open(args.output, 'w') K.generate(cfg, args.output, preview=args.preview, format=format, stylesheet=css) if not args.output: # output to stdout # print str(r) pass except Exception, e: print_error(e) exit(-1)
def render_map(args): cfg = read_map_descriptor(args.config) K = Kartograph() if args.format: format = args.format elif args.output and args.output != '-': format = os.path.splitext(args.output)[1][1:] else: format = 'svg' try: # generate the map if args.style: css = args.style.read() else: css = None if args.output is None and not args.preview: args.output = '-' if args.output and args.output != '-': args.output = open(args.output, 'w') K.generate(cfg, args.output, preview=args.preview, format=format, stylesheet=css) if not args.output: # output to stdout # print str(r) pass except Exception, e: print_error(e) exit(-1)
def main(): k = Kartograph() k.generate({ 'proj': { 'id': 'ortho', 'lon0': -97.7428, 'lat0': 30.2669, }, 'layers': [{ 'special': 'sea', 'styles': { 'fill': 'D0DDF0', } }, { 'id': 'countries', 'src': 'countries/fixtures/countries/ne_10m_admin_0_sovereignty.shp', 'styles': { 'fill': 'EEE9E6', } }], 'export': { 'width': 300, 'height': 300, } }, 'output.svg')
def svg(args): cfg = parse_config(args.config) K = Kartograph() try: K.generate(cfg, args.output) except KartographError, e: print e exit(-1)
def svg(args): cfg = parse_config(args.config) K = Kartograph() try: K.generate(cfg, args.output) except KartographError, e: print e exit(-1)
def create_svg_file(config, svgName, id): K = Kartograph() directory = os.path.join('static', 'img', str(id)) if not os.path.exists(directory): os.makedirs(directory) tempName = os.path.splitext(svgName)[0] file_name = os.path.join(directory, tempName + ".svg") K.generate(config, outfile=file_name)
def generate_map(self, config, name): K = Kartograph() directory = 'map' if not os.path.exists(directory): os.makedirs(directory) file_name = os.path.join(directory, name + '.svg') K.generate(config, outfile=file_name) SingleMapGenerator().codes_hacks(file_name) print "generated map:", file_name print " to view it in google-chrome run: ' google-chrome", file_name, "'"
def generate_place(cfg, the_file, css, curr_state, curr_place): # configurations for Kartography K = Kartograph() K.generate(cfg, outfile=the_file, stylesheet=css, render_format='Moo', curr_place=curr_place)
def generate(): path = os.path.dirname(os.path.realpath(__file__)) script_dir = os.path.dirname(__file__) rel_path="c:/users/seansaito/dev/aviato/app/sample/world_countries_boundary_file_world_2002.shp" abs_path = os.path.join(script_dir, rel_path) d = { "layers":{ "world": { "src": rel_path, "simplify": 2, "attributes" : { "iso3":"ISO_3_CODE" }, "filter": ["ISO_3_CODE", "in", ["PHL", "MYS", "THA", "VNM", "LAO", "SGP", "IDN", "KHM", "BRN", "TLS", "MMR"]] } } } K = Kartograph() K.generate(d, outfile=os.path.dirname(os.path.realpath(__file__)) + "\static\\resources\sea.svg")
def create_map(cc): cfg = { "layers": { "nutsregions": { "src": "../data/NUTS_RG_03M_2010.shp", "attributes": "all", "filter": { "NUTS_ID": country[cc] } } }, "proj": { "id": "satellite", "lon0": "auto", "lat0": "auto" } } K = Kartograph() K.generate(cfg, outfile=cc+'.svg')
def create_map(cc): cfg = { "layers": { "nutsregions": { "src": "../data/NUTS_RG_03M_2010.shp", "attributes": "all", "filter": { "NUTS_ID": country[cc] } } }, "proj": { "id": "satellite", "lon0": "auto", "lat0": "auto" } } K = Kartograph() K.generate(cfg, outfile=cc + '.svg')
def merp(place, bbox): bbox = bbox.split(",") bbox = [float(ll) for ll in bbox] new_bbox = geometry.LineString([(bbox[0], bbox[1]), (bbox[2], bbox[3]) ]).envelope.buffer(0.05).bounds K = Kartograph() css = open('styles.css').read() config = { 'layers': [{ 'src': 'shapefiles/' + place + '/' + place + '_out.shp', 'class': 'runways' }], 'bounds': { 'mode': 'bbox', 'data': [bbox[1], bbox[0], bbox[3], bbox[2]] } } K.generate(config, outfile='svg3/' + place + '.svg', stylesheet=css)
class Map(Drawable): def __init__( self, path="", codes=None, difficulties=None, df=None, user=None, place_asked=None, lower_bound=50, upper_bound=236, session_numbers=True, ): """Draws world map by default. All other defaults are same as in Drawable. """ Drawable.__init__( self, path, codes, difficulties, df, user, place_asked, lower_bound, upper_bound, session_numbers ) config = { "layers": { "states": { "src": self.current_dir + "/ne_110m_admin_1_countries/ne_110m_admin_0_countries.shp", "filter": [ "continent", "in", ["Europe", "Asia", "Africa", "South America", "Oceania", "North America"], ], "class": "states", } } } self.set_config(config) self._k = Kartograph() def set_config(self, config): self.config = config @staticmethod def bin_data( data, binning_function=None, number_of_bins=6, additional_countries=None, additional_labels=[], colour_range="YlOrRd", ): """Combines classification methods with colouring, returns binned data with assigned colours :param data: values to bin :param binning_function: which function to use for binning -- default is None (-> jenks_classification) :param number_of_bins: how many bins to divide data-- default is 6 :param reverse_colours: whether to reverse generated color scheme :param additional_countries: whether to add additional countries AFTER binning -- default is None :param additional_labels: whether to add additional labels AFTER calculations -- default is [] :param colours: use these colours instead of predefined ones """ if binning_function is None: binning_function = jenks_classification binned = pd.DataFrame(data) binned = binned.reset_index() binned.columns = ["country", "counts"] bins = binning_function(binned["counts"], number_of_bins) binned["bin"] = pd.cut(binned["counts"], bins=bins, labels=False) if colour_range == "RdYlGn": colours = colorbrewer.RdYlGn[len(bins) - 1] # Red, Yellow, Green else: colours = colorbrewer.YlOrRd[len(bins) - 1] # Yellow, Orange, Red binned["rgb"] = binned.bin.apply(lambda x: colours[x]) binned = binned.append(additional_countries) colours = list(reversed(colours)) colours = pd.DataFrame(zip(colours)) if additional_countries is not None: colours = colours.append([[additional_countries.rgb.values[0]]], ignore_index=True) colours = colours.append([[(255, 255, 255)]], ignore_index=True) # white for No data bin colours.columns = ["rgb"] colours["label"] = Map.bins_to_string(bins) + additional_labels + ["No data"] return (binned, colours) @staticmethod def bins_to_string(bins): """ Returns list of strings from the bins in the interval form: (lower,upper] :param bins: bins to get strings from """ bins[0] += 1 # corrections for bins bins[-1] -= 1 bins = [round(x, 2) for x in bins] labels = ["(" + str(bins[curr]) + ", " + str(bins[curr + 1]) + "]" for curr in range(len(bins) - 1)] labels.reverse() return labels def generate_css(self, data, path, optional_css=""): """Generates css for coloring in countries. :param data: df with columns [country,rgb], where country is an ID and rgb are colour values :param path: output directory :param optional_css: append additional css at the end of the calculated css-- default is '' """ with open(path, "w+") as css: if not data.empty: data.apply( lambda x: css.write( ".states[iso_a2=" + self.codes[self.codes.id == int(x.country)]["code"].values[0].upper() + "]" + "{\n\tfill: " + self.colour_value_rgb_string(x.rgb[0], x.rgb[1], x.rgb[2]) + ";\n}\n" ), axis=1, ) if optional_css: optional = open(optional_css, "r") css.write(optional.read()) @staticmethod def colour_value_rgb_string(r, g, b): """Returns string in format 'rgb(r,g,b)'. """ return "'rgb(" + str(r) + ", " + str(g) + ", " + str(b) + ")'" @staticmethod def draw_bins(data, path, x=5, y=175, bin_width=15, font_size=12): """Draws bins into svg. :param data: data with columns [label,r,g,b] where label is text next to the bin and rgb are colour values :param path: path to svg :param x: starting x position of the legend :param y: starting y position of the legend :param bin_width: width of each individual bin -- default is 15 :param font_size: font size of labels -- default is 12 """ with copen(path, "r+", "utf-8") as svg: svg.seek(-6, 2) # skip to the position right before </svg> tag svg.write('\n<g transform = "translate(' + str(x) + " " + str(y) + ')">\n') # group for i in range(len(data)): svg.write( '<rect x="0" y="' + str((i + 1) * bin_width) + '" width="' + str(bin_width) + '" height="' + str(bin_width) + '" fill=' + Map.colour_value_rgb_string(data.rgb.values[i][0], data.rgb.values[i][1], data.rgb.values[i][2]) + "/>\n" ) svg.write( '<text x="20" y="' + str((i + 1) * bin_width + 11) + '" stroke="none" fill="black" font-size="' + str(font_size) + '" font-family="sans-serif">' + data.label.values[i] + "</text>\n" ) svg.write("</g>\n</svg>") # group @staticmethod def draw_title(path, title="", x=400, y=410, font_size=20, colour="black"): """Draws title into svg. :param path: path to svg :param title: text do input into picture :param x: starting x position of the title :param y: starting y position of the title :param font_size: font size of labels -- default is 20 :param colour: title colour """ with copen(path, "r+", "utf-8") as svg: svg.seek(-6, 2) svg.write( '\n<text x ="' + str(x) + '" y="' + str(y) + '" stroke="none" font-size="' + str(font_size) + '" fill="' + colour + '" font-family="sans-serif">' + title + "</text>\n</svg>" ) def draw_map(self, path, title="", colours=None): """General drawing method through kartograph. Looks for css in current_dir+'/style.css' for styling css. :param path: output directory :param title: name of map :param colours: dataframe with colours for bins -- default is None """ with open(self.current_dir + "/style.css") as css: self._k.generate(self.config, outfile=path, stylesheet=css.read()) if colours is not None: self.draw_bins(colours, path) if title: self.draw_title(path, title) ############################################################################ def mistaken_countries(self, binning_function=None, path="", number_of_bins=6): """ Draws map of most mistaken countries for this specific one :param binning_function: which function to use for binning -- default is None (-> jenks_classification) :param path: output directory -- default is '' (current dir) :param number_of_bins: how many bins to divide data into-- default is 6 """ if not path: path = self.current_dir + "/maps/" data = analysis.mistaken_countries(self.frame) colours = None if not (data.empty or self.place_asked is None): place = pd.DataFrame([[self.place_asked, (0, 255, 255)]], columns=["country", "rgb"]) (data, colours) = self.bin_data( data, binning_function, number_of_bins, additional_countries=place, additional_labels=[self.get_country_name(self.place_asked)], ) self.generate_css(data[["country", "rgb"]], path=self.current_dir + "/style.css") self.draw_map(path + "mistaken_countries.svg", "Mistaken countries", colours) def number_of_answers(self, binning_function=None, path="", number_of_bins=6): """Draws map of total number of answers per country. :param binning_function: which function to use for binning -- default is None (-> jenks_classification) :param path: output directory -- default is '' (current dir) :param number_of_bins: how many bins to divide data into-- default is 6 """ if not path: path = self.current_dir + "/maps/" data = analysis.number_of_answers(self.frame) colours = None if not data.empty: (data, colours) = self.bin_data(data, binning_function, number_of_bins) self.generate_css(data[["country", "rgb"]], path=self.current_dir + "/style.css") self.draw_map(path + "number_of_answers.svg", "Number of answers", colours) def response_time(self, binning_function=None, path="", number_of_bins=6): """Draws map of mean response time per country. :param binning_function: which function to use for binning -- default is None (-> jenks_classification) :param path: output directory -- default is '' (current dir) :param number_of_bins: how many bins to divide data into-- default is 6 """ if not path: path = self.current_dir + "/maps/" data = analysis.response_time(self.frame) colours = None if not data.empty: (data, colours) = self.bin_data(data, binning_function, number_of_bins) self.generate_css(data[["country", "rgb"]], path=self.current_dir + "/style.css") self.draw_map(path + "response_time.svg", "Response time", colours) def difficulty(self, binning_function=None, path="", number_of_bins=6): """Draws map of total number of answers per country. :param binning_function: which function to use for binning -- default is None (-> jenks_classification) :param path: output directory -- default is '' (current dir) :param number_of_bins: how many bins to divide data into-- default is 6 """ if not path: path = self.current_dir + "/maps/" data = analysis.difficulty_probabilities(self.difficulties) colours = None if not data.empty: (data, colours) = self.bin_data(data, binning_function, number_of_bins, colour_range="RdYlGn") self.generate_css(data[["country", "rgb"]], path=self.current_dir + "/style.css") self.draw_map(path + "difficulty.svg", "Difficulty for an average user", colours) def success(self, binning_function=None, path="", number_of_bins=6): """Draws map of mean success rate per country. :param binning_function: which function to use for binning -- default is None (-> jenks_classification) :param path: output directory -- default is '' (current dir) :param number_of_bins: how many bins to divide data into-- default is 6 """ if not path: path = self.current_dir + "/maps/" data = analysis.mean_success(self.frame) colours = None if not data.empty: (data, colours) = self.bin_data(data, binning_function, number_of_bins, colour_range="RdYlGn") self.generate_css(data[["country", "rgb"]], path=self.current_dir + "/style.css") self.draw_map(path + "success.svg", "Mean success rate", colours) def skill(self, binning_function=None, path="", number_of_bins=6): """Draws map of skill per country. :param binning_function: which function to use for binning -- default is None (-> jenks_classification) :param path: output directory -- default is '' (current dir) :param number_of_bins: how many bins to divide data into-- default is 6 """ if not path: path = self.current_dir + "/maps/" data = analysis.mean_skill_session(self.frame, self.difficulties, threshold=None)[1] data = analysis.success_probabilities(data, self.difficulties) colours = None if not data.empty: (data, colours) = self.bin_data(data, binning_function, number_of_bins, colour_range="RdYlGn") self.generate_css(data[["country", "rgb"]], path=self.current_dir + "/style.css") self.draw_map(path + "skill.svg", "Skill ", colours)
print "starting", country, m config['layers']['country']['filter'] = (lambda r: r['ISO_A3'] in m['iso']) if 'proj' in m: config['proj']['id'] = m['proj'] else: config['proj'] = {} # write location dict to tmp.csv with open('tmp.csv', 'wb') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=['name', 'lat', 'lon', 'r']) writer.writeheader() for name, loc in m['location'].items(): writer.writerow({'name': name, 'lat': loc[0], 'lon': loc[1], 'r': 10}) fn = 'svg/%s.svg' % country K.generate(config, outfile=fn, stylesheet=css) print "generated", fn if not GENERATE_WORLD: print "done" sys.exit(0) # now generate world map country_list = [] print "starting world" with open('tmp.csv', 'wb') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=['name', 'lat', 'lon', 'r']) writer.writeheader() for (country, m) in MAPS.items(): country_list.extend(m['iso'])
def generate_zipcodes_map(data, zipcode, identifier, key_field, algorithm): """ Generate a map with provided data. It will cache the maps based on the identifier, which will be the name. The zipcode is used to find the kml. The key_field will be the field taken into account for the heat map. The algorithm must be one of the "Algorithms" (e.g., Algorithms.LINEAR). Example. Providing this data: { '28004' : { # Each external zipcode 'key1' : 154, 'key2' : 153, 'key3' : 155, }, '28009' : { # Each external zipcode 'key1' : 300, 'key2' : 100, 'key3' : 50, } } A zipcode called '28008', an identifier 'heatmap_incomes', and a key_field 'key1', it will generate and cache a map where the zipcodes 28004 and 28009 will appear, being the latter closer to red since its 'key1' is higher. """ data_hash = hashlib.new("md5", repr(data)).hexdigest() svg_file = 'intellidata/static/geo/%s_%s_%s_%s_%s.svg' % (zipcode, identifier, key_field, algorithm, data_hash) json_svg_file = 'intellidata/static/geo/%s_%s_%s_%s_%s.svg.json' % (zipcode, identifier, key_field, algorithm, data_hash) if CACHE_MAP and os.path.exists(svg_file): return svg_file shp_file_path = obtain_shp_file(data, zipcode, identifier, key_field, data_hash, algorithm) # TODO: improve this. It's already done before all_fields = set() for zdata in data.values(): for field in zdata: all_fields.add(field) sorted_fields = sorted(list(all_fields)) attributes = {'Position' : 'Position', 'ZCode' : 'ZCode'} for sorted_field in sorted_fields: attributes[sorted_field.title()] = sorted_field.title() kartograph_settings = OrderedDict() kartograph_settings["proj"] = { "id": "sinusoidal", "lon0": 20 } kartograph_settings["layers"] = OrderedDict() kartograph_settings["layers"]["background"] = {"special": "sea"} kartograph_settings["layers"]["graticule"] = { "special": "graticule", "latitudes": 1, "longitudes": 1, "styles": { "stroke-width": "0.3px" } } kartograph_settings["layers"]["world"] = { "src": "data/geo/ne_10m_admin_0_countries_cropped.shp" } kartograph_settings["layers"]["provinces"] = { "src" : "data/geo/provincias.shp" } # kartograph_settings["layers"]["world"] = { # "src": "data/geo/ne_10m_admin_0_countries.shp" # } kartograph_settings["layers"]["zipcodes"] = { "src": shp_file_path, "attributes": attributes } kartograph_settings["bounds"] = { "mode": "bbox", "data": [-10, 35, 5, 45], "crop": [-12, 33, 7, 47] } json_svg_file_sio = StringIO.StringIO(json.dumps(kartograph_settings, indent = 4)) json_svg_file_sio.name = json_svg_file K = Kartograph() css = open("intellidata/static/geo/maps.css").read() cfg = read_map_config(json_svg_file_sio) K.generate(cfg, outfile=svg_file, format='svg', stylesheet=css) return svg_file
(options, args) = parser.parse_args() input = fiona.open(options.filename, 'r') f = next(input) attributes = f['properties'].keys() input.close() from kartograph import Kartograph cfg = { "layers": { "mylayer": { "labeling": { "key": options.label }, "attributes": attributes, "src": options.filename } }, "export": { "width": int(options.width) } } K = Kartograph() filename = options.filename + '.svg' print filename K.generate(cfg, outfile=filename)
cfg = { "layers": { "china": { "src": "bou2_4p.shp" , "simplify":2, "attributes":{ "ISO": "iso", "NAME_1": "name", "FIPS_1": "fips"} } }, "bounds": { "mode": "bbox", "data": [80, 17, 125, 54], "padding": 0.06 } } K = Kartograph() K.generate(cfg, 'map-china.svg', preview=True, format='svg')
cfg = json.loads(open('worldmap.json').read()) #print 'world' cfg['export']['width'] = width #K.generate(cfg, map_output_dir + 'world.svg', preview=False) regions = get_json('region-bbox.json') for region in regions: cfg = json.loads(open('continent-template.json').read()) del cfg['proj']['id'] cfg['bounds']['data'] = regions[region] cfg['export']['width'] = width map_filename = map_output_dir + region + '.svg' if not os.path.exists(map_filename): print region K.generate(cfg, map_filename, preview=True) err = [] ignore = set(get_json('ignore-countries.json')) # render country maps for adm_code in adm_codes: if adm_code in ignore: continue map_filename = map_output_dir + adm_code + '.svg' l = 1 if not os.path.exists(map_filename) or adm_code in force_countries: tmpl = json.loads(open('country-template.json').read()) if os.path.exists('shp/custom/%s.shp' % adm_code): tmpl['layers'][l]['src'] = 'shp/custom/%s.shp' % adm_code tmpl['export']['width'] = width
from kartograph import Kartograph from collections import OrderedDict c = { 'layers': { 'provinces': { 'src': '../../nd/ne_10m_admin_1_states_provinces_shp.shp', 'attributes': { 'id': 'adm1_code', } } }, } c['layers'] = OrderedDict(c['layers']) K = Kartograph() K.generate(c, outfile='simp.svg')
from kartograph import Kartograph from kartograph.options import read_map_descriptor import sys K = Kartograph() css = open("elections.css").read() cfg = read_map_descriptor(open("elections.json")) K.generate(cfg, outfile='elections.svg', format='svg', stylesheet=css)
from kartograph import Kartograph import sys cfg = { "layers": { "china": { "src": "bou2_4p.shp", "simplify": 2, "attributes": { "ISO": "iso", "NAME_1": "name", "FIPS_1": "fips" } } }, "bounds": { "mode": "bbox", "data": [80, 17, 125, 54], "padding": 0.06 } } K = Kartograph() K.generate(cfg, 'map-china.svg', preview=True, format='svg')
"id" : "background", "special" : "sea", }] #Add simplification settings to nation layer in config.layers if "simplify" in mapSettings[mapType]: config["layers"][0]["simplify"] = mapSettings[mapType]["simplify"] #Chose size by height config["export"] = { "round": 1, # "height": 768, } K = Kartograph() K.generate(config, outfile=fileAfterKartograph) print ("Map created as %s" % fileAfterKartograph) ########################################################################################################################### #Prepare for svg processing print ("Processing svg file") #Register SVG namespace SVG_NS = "http://www.w3.org/2000/svg" ET.register_namespace('',SVG_NS) #get xml from svg print ("Loading map..."), tree = ET.parse(fileAfterKartograph) root = tree.getroot() print ("done")
class MapInput(QtGui.QWidget): def __init__(self): super(MapInput, self).__init__() self.initUI() def initUI(self): self.countries = [] self.existingChecks = [] self.K = Kartograph() self.CountryInput = QtGui.QLineEdit(self) #self.CountryList = QtGui.QTextEdit(self) #self.CountryList.setReadOnly(True) self.AddButton = QtGui.QPushButton("Add", self) self.AddButton.clicked.connect(self.buttonClicked) self.GenButton = QtGui.QPushButton('Generate', self) self.GenButton.clicked.connect(self.generateClicked) self.DispButton = QtGui.QPushButton('Display', self) self.DispButton.clicked.connect(self.displayClicked) self.statusBar = QtGui.QStatusBar(self) self.br = QtSvg.QGraphicsSvgItem("world.svg").boundingRect() self.scene = QtGui.QGraphicsScene() self.view = QtGui.QGraphicsView(self.scene) self.SvgItem = QtSvg.QGraphicsSvgItem("world.svg").boundingRect() self.webview = QGraphicsWebView() self.webview.load(QtCore.QUrl("world.svg")) self.webview.setFlags(QtGui.QGraphicsItem.ItemClipsToShape) self.webview.setCacheMode(QtGui.QGraphicsItem.NoCache) self.webview.resize(self.br.width(), self.br.height()) self.scene.addItem(self.webview) self.view.resize(self.br.width()+10, self.br.height()+10) self.grid = QtGui.QGridLayout() self.grid.setSpacing(10) self.bottomCheck = 4 self.grid.addWidget(self.AddButton, 1, 1) self.grid.addWidget(self.GenButton, 2, 1) self.grid.addWidget(self.DispButton, 3, 1) #grid.addWidget(self.CountryList, 4, 1) self.grid.addWidget(self.CountryInput, 1, 2) self.grid.addWidget(self.statusBar, 36, 0, 1, 3, QtCore.Qt.AlignBottom) self.grid.addWidget(self.view, 2, 2, 34, 50) self.setLayout(self.grid) #self.center() self.setWindowTitle('Map Display - Width ' + str(self.br.width()) + ', Height ' + str(self.br.height())) self.generateClicked() self.displayClicked() self.show() def buttonClicked(self): country = self.CountryInput.text() #add a check for if countries contains country #if not (self.countries.contains(country)): self.countries.append(country) self.generateClicked() self.displayClicked() self.CountryInput.setText('') self.countries = [c for c in self.countries if not c == ''] def generateClicked(self): self.generateMap(self.countries) #self.updateSB("Map generated.") self.statusBar.showMessage("Map generated.") def displayClicked(self): #add an SVG object to the main window, make this re-render that self.statusBar.showMessage("Displaying, please wait...") css = open('world2.css').read() cfg = options.read_map_config(open('world.json')) self.K.generate(cfg, outfile='world.svg', stylesheet=css, preview = False) self.webview.load(QtCore.QUrl("world.svg")) self.statusBar.showMessage("Map Displayed.") if self.CountryInput.text() and not self.CountryInput.text() in self.existingChecks: tempWidget = QtGui.QCheckBox(self.CountryInput.text(), self) tempWidget.toggle() tempWidget.stateChanged.connect(self.toggleDisplay) self.grid.addWidget(tempWidget, self.bottomCheck, 1) self.bottomCheck += 1 self.existingChecks.append(self.CountryInput.text()) self.updateCountryText() def generateMap(self, countrylist): self.generateCSS(countrylist) def generateCSS(self, countrylist): x = 0 css = open('world2.css', 'w') #print "css opened" css.write('#world {\n fill: #f5f3f2;\n},\n') css.write('#countries {\n fill: #f5f3f2;\n stroke: #882222;\n stroke-width: 0.5px;\n stroke-opacity: 0.4;\n}') for c in countrylist: countryString = ',\n#countries[name=%s]{\n fill: #ff0000;\n}' % c css.write(countryString) #print c #print x x+=x css.close() def toggleDisplay(self): senderText = self.sender().text() print self.sender().isChecked() if not self.sender().isChecked(): print self.sender().text() self.countries = [c for c in self.countries if not c == self.sender().text()] print self.countries if self.sender().isChecked(): self.countries.append(self.sender().text()) print self.countries self.buttonClicked() def updateCountryText(self): CountryList = self.countries displayString = QtCore.QString('') for country in CountryList: displayString.append(country) displayString.append('\n')
from kartograph import Kartograph from kartograph.options import read_map_config import sys cfg=read_map_config(open("map.json")) K = Kartograph() K.generate(cfg, outfile='level3_wgs84.svg',format='svg')
#!/usr/bin/env python # -*- coding: utf-8 -*- from kartograph import Kartograph from geonamescache import GeonamesCache K = Kartograph() gc = GeonamesCache() countries = gc.get_countries() for iso2 in list(countries.keys()): #for iso2 in ['FR', 'ES']: cfg = { 'layers': [{ 'id': 'country', 'src': 'shp/ne_50m_admin_0_countries.shp', # 'src': 'shp/ne_10m_admin_1_states_provinces.shp', 'filter': { 'iso_a2': iso2 }, }] } svg = 'svg/%s.svg' % iso2 try: K.generate(cfg, outfile=svg, stylesheet='#country {fill: #000;}') except Exception as err: print( ('Exception for country %s:\n%r' % (countries[iso2]['name'], err)))
def svg(args): cfg = parse_config(args.config) K = Kartograph() K.generate(cfg, args.output)
log = open('log.txt', 'w') for fn in glob('configs/*.*'): fn_parts = splitext(basename(fn)) print 'running text', basename(fn), '...', try: cfg = read_map_config(open(fn)) K = Kartograph() css_url = 'styles/' + fn_parts[0] + '.css' css = None if exists(css_url): css = open(css_url).read() svg_url = 'results/' + fn_parts[0] + '.svg' if exists(svg_url): remove(svg_url) K.generate(cfg, 'results/' + fn_parts[0] + '.svg', preview=False, format='svg', stylesheet=css) print 'ok.' passed += 1 except Exception, e: import traceback ignore_path_len = len(__file__) - 7 exc = sys.exc_info() log.write('\n\nError in test %s' % fn) for (filename, line, func, code) in traceback.extract_tb(exc[2]): log.write(' %s, in %s()\n %d: %s\n' % (filename, func, line, code)) log.write('\n') log.write(str(e)) print 'failed.' failed += 1 print 'passed: %d\nfailed: %d' % (passed, failed)
#!/usr/bin/env python # -*- coding: utf-8 -*- from kartograph import Kartograph import os K = Kartograph() css = '#country {fill: #000;}' for iso3 in os.listdir('shp/countries'): source_file = 'shp/countries/%s/%s.shp' % (iso3, iso3) target_file = 'svg/countries/%s.svg' % iso3 cfg = { 'layers': [{ 'id': 'country', 'src': source_file, }] } try: K.generate(cfg, outfile=target_file, stylesheet=css) except Exception as err: print(('Exception for country %s:\n%r' % iso3))
"proj": { "id": "sinusoidal" }, "layers": [ { "id": "grid", "special": "graticule", "latitudes": 5, "longitudes": 5, "fill": "blue" }, { "id": "countries", "src": "ne_50m_admin_0_countries.shp", "attributes": "all", "styles": { "stroke-width": "0.4px", "color": "#aaaaaa", "fill": "red" } } ], "bounds": { "mode": "bbox", "data": [70, 17, 135, 54] } } K = Kartograph() K.generate(config, outfile='mymap.svg', stylesheet="world.css")
cfg = json.loads(open('worldmap.json').read()) #print 'world' cfg['export']['width'] = width #K.generate(cfg, map_output_dir + 'world.svg', preview=False) regions = get_json('region-bbox.json') for region in regions: cfg = json.loads(open('continent-template.json').read()) del cfg['proj']['id'] cfg['bounds']['data'] = regions[region] cfg['export']['width'] = width map_filename = map_output_dir + region + '.svg' if not os.path.exists(map_filename): print region K.generate(cfg, map_filename, preview=True) err = [] ignore = set(get_json('ignore-countries.json')) # render country maps for adm_code in adm_codes: if adm_code in ignore: continue map_filename = map_output_dir + adm_code + '.svg' l = 1 if not os.path.exists(map_filename) or adm_code in force_countries: tmpl = json.loads(open('country-template.json').read()) if os.path.exists('shp/custom/%s.shp' % adm_code): tmpl['layers'][l]['src'] = 'shp/custom/%s.shp' % adm_code
from kartograph import Kartograph from kartograph.errors import KartographError from countryInfo import countries from countryInfo import iso2latlon import json tpl = open('src/templates/admin1.json').read() K = Kartograph() for country in countries: iso = country['ISO3'] print iso cfg = json.loads(tpl.replace('{{ ISO }}', iso)) if iso in iso2latlon: (lat, lon) = iso2latlon[iso] else: lat = lon = 'auto' cfg['proj']['lat0'] = lat cfg['proj']['lon0'] = lon try: K.generate(cfg, 'maps/' + country['Continent'] + '/' + country['ISO3'] + '.svg') except KartographError, e: print e
#!/usr/bin/env python # -*- coding: utf-8 -*- from kartograph import Kartograph K = Kartograph() cfg = { 'layers': [{ 'id': 'country', 'src': 'shp/ne_50m_admin_0_countries.shp' }] } svg = 'svg/world.svg' K.generate(cfg, outfile=svg, stylesheet='#country {fill: #000;}')
#"data": [-85.8635, 38.2127, -85.6, 38.4] #"data": [-85.8635, 38.2127, -85.6, 38.5] # "data": [-85.8635, 38.2127, -85.6, 38.7] # -big1 # "data": [-85.8635, 38.2927, -85.6, 38.7] #}, "export": { "width": 10000, #"prettyprint": True, } } # TODO: Add css # Because I don't want to deal with getting everything else in python 3 right now # I use subprocess, lame, I know. k.generate(config, outfile='map.svg') subprocess.call(['cairosvg', '-o', 'map.pdf', 'map.svg', '--unsafe']) ipdf = PdfReader('map.pdf') p = ipdf.pages[0] pdf = PdfWriter() # width_to_height_ratio = 1.3 # 10 pages wide is 85" # 2 pages down is 22" # It's printing at 10.75" x 6.5" width_pages = 8 height_pages = 5
def main(): start = time.time() from errors import KartographError if len(sys.argv) < 3: print "try: kartograph svg map-config.yaml" sys.exit(1) command = sys.argv[1] if command in ("generate", "kml", "svg"): cfg = {} output = None opt_src = None opts, args = getopt.getopt(sys.argv[2:], 'c:o:', ['config=', 'output=']) for o, a in opts: if o in ('-c', '--config'): opt_src = a elif o in ('-o', '--output'): output = a # check and load map configuration if os.path.exists(opt_src): t = open(opt_src, 'r').read() if opt_src[-5:].lower() == '.json': cfg = json.loads(t) elif opt_src[-5:].lower() == '.yaml': import yaml cfg = yaml.load(t) else: raise KartographError('supported config formats are .json and .yaml') else: raise KartographError('configuration not found') K = Kartograph() try: if command == "kml": K.generate_kml(cfg, output) else: K.generate(cfg, output) except KartographError as e: print e elapsed = (time.time() - start) print 'execution time: %.4f secs' % elapsed sys.exit(0) elif command == "cartogram": map = sys.argv[2] attr = sys.argv[3] data = sys.argv[4] key = sys.argv[5] val = sys.argv[6] C = Cartogram() C.generate(map, attr, data, key, val)
# write location dict to tmp.csv with open('tmp.csv', 'wb') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=['name', 'lat', 'lon', 'r']) writer.writeheader() for name, loc in m['location'].items(): writer.writerow({ 'name': name, 'lat': loc[0], 'lon': loc[1], 'r': 10 }) fn = 'svg/%s.svg' % country K.generate(config, outfile=fn, stylesheet=css) print("generated", fn) if not GENERATE_WORLD: print("done") sys.exit(0) # now generate world map country_list = [] print("starting world") with open('tmp.csv', 'wb') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=['name', 'lat', 'lon', 'r']) writer.writeheader() for (country, m) in MAPS.items():
#!/usr/bin/python2.7 from kartograph import Kartograph # conda execute # env: # - python>=2.7.0 import argparse parser = argparse.ArgumentParser() parser.add_argument("-source") parser.add_argument("-proj") parser.add_argument("-outfile") args = parser.parse_args() print(args) config = { "layers": { "mylayer": { "src": args.source, "attributes": "all" } }, "proj": { "id": args.proj } } K = Kartograph() K.generate(config, outfile=args.outfile)
from kartograph import Kartograph from collections import OrderedDict c = { 'layers': { 'provinces': { 'src': '../../nd/ne_10m_admin_1_states_provinces_shp.shp', 'attributes': { 'id': 'adm1_code', } } }, } c['layers'] = OrderedDict(c['layers']) K = Kartograph() K.generate(c, outfile='simp.svg')