The upcoming release of Maperitive comes with a new and exciting feature: Python scripting.
What I’ll describe here is just an initial introduction of Python into Maperitive and right now is more of an experimental nature. I have great plans with Python, but there is still a lot of work to do and I wanted to release something to users so they can test it out and give some feedback.
Writing Python Functions
In the new release Python scripting can be used to define text labels. Let me give you an example with a piece of Python code:
def cycleLabel(e): str_list =  for set in e.tagSets: if set.hasTag('ref'): str_list.append(set['ref']) str_list.sort() return '+'.join(str_list)
So what does this code do? I won’t go into Python syntax (since I think it’s not that hard to understand for anyone with a little bit of programming inclination), but I’ll explain some basics.
We wrote a nice little function called cycleLabel which receives a map element (e) as an input argument. The function goes through the list of element tags and looks for ref tags, which it then puts into a list. The list is then sorted and transformed into a single string using the plus sign as a delimiter.
The above function can be used to render cycle route names. In OSM these are usually represented using cycle relations. Each route has its own relation, but several routes can share the same OSM way, so we need a way to show all the route names in a single label for that way. This is where the cycleLabel function comes into play.
A name of a route is stored in the ref tag and we collect all ref tags to be able to show them as a single label:
Using Python Code
Once we have our labeling function, we need to tell Maperitive to use it. Here’s an excerpt of rendering rules I used to produce the above map:
import-script:test.py features lines cycle route : osmnetwork[type=route] ... rules target : cycle route define line-width : 3 line-color : red draw : line define text-func : cycleLabel(e) draw : text
The important things are:
- import-script tells Maperitive to load a Python source file
- text-func is a new rendering property which you can use to call a Python function to prepare the text label.
In the next post we’ll go through element variable attributes which can be used in Python code to access various properties of the element.
- braincrunch posted this