An A4 Route Map: Compressing 39 km While Keeping True Bearings
A map that drivers can follow does not have to be to scale, but it must not lie about direction. Distances can be read from labels, while drivers compare road directions and the side a place is on against what they see at every junction. Getting those wrong sends them the wrong way.
1-minute summary
- Symptom / problem
- A 46.7 km route must fit on one A4 page, and drawing it to scale makes both ends unreadable.
- Who should read
- Anyone preparing a document that needs a location map drivers can follow.
- Fix in short
- Generate a schematic SVG with Python that compresses each stretch non-linearly, takes bearings from real coordinates, and puts pins on the correct side of the road.
A set of documents I was preparing for a client needed a location map on one A4 sheet that visitors could follow while driving, from a landmark in town to the destination. The actual route was 46.7 km long. I drew the first version to scale over a map image, and the result was one long line across the middle of the page. Details at the start and end, the parts people actually needed, were too small to read. So I rebuilt it as a schematic map that deliberately ignores scale but preserves the true bearing of every segment.
The place names, junction names, highway numbers, and coordinates in this article are all fictional. The distances, formulas, and positioning constants are the ones I actually used.
The brief: detailed at both ends, short in the middle
This route has a shape that does not suit paper. The first 3.4 km out of town has frequent turns, followed by roughly 39 km of straight highway with almost no decisions to make, then a final few kilometers with junctions, a U-turn, and the destination entrance. The total driving time is 35-40 minutes.
The client specified four requirements.
- Show details at both ends.
- Shorten the long straight highway stretch in the middle.
- Keep the true bearing of every segment.
- Make junctions look like actual junctions, not just bends in a line.
The first version: drawn to scale over a map, and unreadable
For the first version, I used the approach that came to mind first: create a 2480 x 3508 px image, equivalent to A4 at 300 dpi, load map tiles and arrange them using Web Mercator, then draw the route over them with a QR code and icons. The script was 334 lines long.
The problem was the arithmetic of scale. Fitting 46.7 km into a length of 160 mm gives roughly 3.4 mm per kilometer. The first 3.4 km through town, with 6 route points, shrank to less than 12 mm. It was impossible to tell which point was which, while almost the entire page was taken up by a straight line with nothing to read. Another issue was that the output was a raster image. Once embedded in the document and resized to fit the page, the text was not sharp.
Raster image at true scale
- 2480 x 3508 px image drawn over map tiles
- Paper distances match actual distances
- Town section shrinks to less than 12 mm
- Text loses sharpness when embedded
Schematic SVG with compressed distances
- 178 x 160 viewBox in mm
- Nonlinear length compression with a cap
- Every segment's bearing calculated from actual coordinates
- Vector output, sharp at any print size
This job was the reverse of the electrical panel drawing that had to be measurable on paper I wrote about before. There, scale was a promise I could not break. Here, scale was what I had to give up to make room for the parts people needed to read. What I could not give up changed from length to direction.
Input data: a route from a routing service and cumulative distances
There was just one input file: the output from an OSRM-style routing service, requesting the full route geometry as GeoJSON.
# ขอเส้นทางขับรถจากจุดเริ่มถึงปลายทาง พิกัดเรียงเป็น lon,lat (ค่าในตัวอย่างเป็นค่าสมมุติ)
curl -s "https://router.example.com/route/v1/driving/100.2000,15.1000;100.3500,14.7500?overview=full&geometries=geojson" -o route.json
I used two things from the file: routes[0].geometry.coordinates, the list of [lon, lat] points along the route, and routes[0].distance, the total distance in meters. From these points, I calculated cumulative distances myself using haversine so I could ask for the coordinates at a given kilometer along the route.
import io, json, math
route = json.load(io.open('route.json', encoding='utf-8'))['routes'][0]
G = route['geometry']['coordinates'] # [[lon, lat], ...]
TOTAL = route['distance'] / 1000.0 # กม.
def hav(a, b):
R = 6371.0
la1, lo1, la2, lo2 = map(math.radians, [a[1], a[0], b[1], b[0]])
h = math.sin((la2 - la1) / 2) ** 2 + math.cos(la1) * math.cos(la2) * math.sin((lo2 - lo1) / 2) ** 2
return 2 * R * math.asin(math.sqrt(h))
CUM = [0.0] # ระยะสะสมถึงจุดที่ i
for i in range(1, len(G)):
CUM.append(CUM[-1] + hav(G[i - 1], G[i]))
def at(km):
"""พิกัดบนเส้นทางที่ระยะสะสมใกล้ km ที่สุด"""
i = min(range(len(G)), key=lambda j: abs(CUM[j] - km))
return G[i]
I then defined roughly 17 points to appear on the map. Each point specifies its kilometer along the route, its name, its type, which side its label goes on, and, for roadside places, the coordinates of the place itself.
# (กม., ชื่อ, คำอธิบาย, ชนิด, ด้านป้าย, พิกัดสถานที่ถ้ามี) — ชื่อและพิกัดเป็นค่าสมมุติ
NODES = [
(0.00, 'วงเวียนกลางเมือง', 'จุดเริ่มต้น', 'start', 'R', None),
(0.60, 'แยก A', 'เลี้ยวซ้าย', 'turn', 'L', None),
(1.70, 'สะพานข้ามแม่น้ำ', '', 'bridge', 'R', None),
(3.40, 'แยก B', 'เลี้ยวซ้ายเข้าทางหลวง', 'cross', 'L', None),
(11.40, 'ปั๊มน้ำมันริมทาง', 'อยู่ซ้ายมือ', 'poi', 'L', (15.0400, 100.2300)),
(21.10, 'ที่ทำการริมทาง', 'อยู่ขวามือ', 'poi', 'R', (14.9600, 100.2600)),
(43.02, 'แยก C', 'ตรงไป ไม่เลี้ยว', 'cross', 'L', None),
(45.80, 'ปั๊มตรงข้าม', 'จุดสังเกตก่อนกลับรถ', 'poi', 'L', (14.7600, 100.3400)),
# ... จุดที่เหลือ ...
]
BREAK_AFTER = {11.40, 21.10} # ช่วงที่ออกจากจุดเหล่านี้ถูกย่นมาก ให้ใส่เครื่องหมายตัดระยะ
Referencing points by their kilometer along the route, instead of typing every point's coordinates manually, makes editing easy. Moving a point takes one number change, and every point always lies on the actual route because it comes from the geometry.
The core: direction from actual coordinates, length from a formula
The heart of the entire script is in these dozen or so lines. Between two adjacent points, I separate the vector into two parts. Direction comes from the actual coordinates, while length does not come from the coordinates at all; it comes from a distance-compression formula.
LAT0 = sum(p[1] for p in G) / len(G)
KX = 111.320 * math.cos(math.radians(LAT0)) # กม. ต่อองศาลองจิจูด ที่ละติจูดนี้
KY = 110.574 # กม. ต่อองศาละติจูด
def seg_len(dkm):
"""ความยาวบนกระดาษ (มม.) จากระยะจริงของช่วง — ใกล้ละเอียด ไกลบีบ"""
return min(24.0, 11.0 + 4.6 * (dkm ** 0.40))
pos = [(0.0, 0.0)]
for i in range(1, len(NODES)):
a = at(NODES[i - 1][0]); b = at(NODES[i][0])
dx = (b[0] - a[0]) * KX # ตะวันออก (กม.)
dy = (b[1] - a[1]) * KY # เหนือ (กม.)
ang = math.atan2(dy, dx) # ทิศจริงของช่วงนี้
dkm = max(0.02, NODES[i][0] - NODES[i - 1][0])
L = seg_len(dkm) * (1.75 if NODES[i][0] <= 3.4 else 1.0) # ในเมืองเลี้ยวถี่ ขยายเพิ่ม
x, y = pos[-1]
pos.append((x + L * math.cos(ang), y - L * math.sin(ang))) # y กลับด้าน ให้เหนืออยู่บน
KX and KY convert differences in degrees to kilometers before passing them to atan2. Calculating the angle directly from raw degrees would distort the direction because one degree of longitude is shorter than one degree of latitude, with the difference increasing farther from the equator. The minus sign before L * sin flips the y-axis because y increases downward on screen, but north must be up on the map.
The seg_len formula has three parts. The constant 11 sets the minimum length, so even the shortest segment has room for a label. The exponent 0.4 makes length grow progressively more slowly as the segment gets longer, and min with 24 sets the cap. No matter how long the segment is, it cannot exceed that.
The actual numbers work out to roughly 14.5 mm for a 0.5 km segment and 24 mm for a 16 km segment, which hits the cap. In mm per kilometer, the short segment gets 29 and the long one gets 1.5, a difference of roughly 19 times. If I applied the short segment's rate linearly to the entire route, the 16 km segment would need to be 464 mm long, already exceeding the height of A4. The multiplier 1.75 applies to the first 3.4 km through town, where turns are close together and there are many labels. All these mm values are before fitting to the frame.
The final step is to scale the whole set down to fit a 178 x 160 frame, reserving 56 on the left and 40 on the right for labels.
PW, PH = 178.0, 160.0
PAD_L, PAD_R, PAD_T, PAD_B = 56.0, 40.0, 14.0, 20.0
xs = [p[0] for p in pos]; ys = [p[1] for p in pos]
sx = (PW - PAD_L - PAD_R) / max(0.01, max(xs) - min(xs))
sy = (PH - PAD_T - PAD_B) / max(0.01, max(ys) - min(ys))
S = min(sx, sy) # ค่าเดียว ใช้ทั้งสองแกน
ox = PAD_L - min(xs) * S
oy = PAD_T - min(ys) * S
P = [(ox + x * S, oy + y * S) for x, y in pos]
If I scale the x-axis by sx and the y-axis by sy to fill the frame exactly in both dimensions, the image stretches unevenly and every line's angle changes. The bearings carefully calculated from actual coordinates disappear in a single line. Leaving empty space along one dimension is better than losing the bearings, and for the same reason, distance compression must act on each segment's length, not by stretching or shrinking either axis.
For the heavily compressed segments, those leaving kilometer points 11.4 and 21.1, I used dashed lines, added break symbols, and rotated the word "Compressed" to follow each line's angle. This tells readers that these stretches are much shorter on paper than in reality. The actual distances can be read from the cumulative kilometer labels at every point.
Place markers must be on the correct side of the road
For roadside landmarks such as gas stations or offices, placing a marker directly on the road line does not tell readers whether it is on the left or the right. Choosing the side from memory could also be wrong. So I let the place's actual coordinates decide, using the cross product of two vectors: the direction of travel and the vector from the road to the place.
OFF = 5.2 # ระยะดึงหมุดออกจากแนวถนน (มม.)
def pin_position(i, x, y, ux, uy):
"""x,y = ตำแหน่งจุดบนกระดาษ, (ux,uy) = ทิศเดินทางบนจอ"""
km, ll = NODES[i][0], NODES[i][5] # ll = (lat, lon) ของตัวสถานที่
if not ll:
return x, y
a = at(km)
b = at(NODES[min(i + 1, len(NODES) - 1)][0])
ge = (b[0] - a[0]) * KX; gn = (b[1] - a[1]) * KY # ทิศเดินทาง (ตะวันออก, เหนือ)
ve = (ll[1] - a[0]) * KX; vn = (ll[0] - a[1]) * KY # จากถนนไปสถานที่
cross = ge * vn - gn * ve # > 0 = สถานที่อยู่ซ้ายมือของทิศเดินทาง
sgn = 1.0 if cross > 0 else -1.0
lx, ly = uy, -ux # ด้านซ้ายของทิศเดินทาง บนจอที่ y ชี้ลง
return x + lx * OFF * sgn, y + ly * OFF * sgn
The sign of cross indicates the side. A positive value means the place is to the left of the direction of travel. I then offset the marker 5.2 mm from the road on that side and move its name label with it. The thing to watch is the leftward vector on screen, which is (uy, -ux), not (-uy, ux) as in textbooks where the y-axis points up. Get this wrong and every marker swaps sides at once.
For ordinary point labels, I use a simple rule: place labels above or below horizontal segments, and to the left or right of vertical segments. But one rule cannot handle every point. In the end, I still needed an OVERRIDE table specifying individual label positions where labels collided. I did not try to write a complete automatic label layout engine. For a single map with a dozen or so points, a manual override table is shorter and gives more predictable control over the result.
Junctions, bridges, and a close-up of the U-turn
A bent line tells drivers to turn, but it does not tell them what kind of junction is there. So I added a function to draw short arms for the roads not taken, making it clear that these are actual junctions. Each arm is specified with a word relative to the incoming and outgoing directions at that point.
def unit(ax, ay, bx, by):
d = ((bx - ax) ** 2 + (by - ay) ** 2) ** 0.5 or 1.0
return (bx - ax) / d, (by - ay) / d
def junction(km, arms):
"""arms = [(ชนิด, ความยาว มม., ป้าย), ...] ชนิด: ahead / back / left / right"""
i = [j for j, n in enumerate(NODES) if abs(n[0] - km) < 0.001][0]
jx, jy = P[i]
bx, by = unit(P[i - 1][0], P[i - 1][1], jx, jy) # ทิศที่วิ่งเข้ามา
fx, fy = unit(jx, jy, P[i + 1][0], P[i + 1][1]) # ทิศที่วิ่งต่อไป
out = []
for kind, L, label in arms:
if kind == 'ahead': ux, uy = bx, by # ตรงไปตามทิศเดิม
elif kind == 'back': ux, uy = -fx, -fy # ด้านตรงข้ามของทางที่จะไป
elif kind == 'left': ux, uy = fy, -fx # ซ้ายของทิศเดินทาง
else: ux, uy = -fy, fx # ขวาของทิศเดินทาง
out.append('<line x1="%.2f" y1="%.2f" x2="%.2f" y2="%.2f" class="arm"/>'
% (jx, jy, jx + ux * L, jy + uy * L))
out.append('<text x="%.2f" y="%.2f" class="ns">%s</text>'
% (jx + ux * (L + 1.6), jy + uy * (L + 1.6), label))
return out
svg = junction(3.40, [('ahead', 11.0, 'ทางเดิมตรงไป'), ('back', 9.0, 'ทางหลวงอีกฝั่ง')])
svg += junction(43.02, [('left', 15.0, 'ทางแยกซ้าย')])
River bridges use a similar principle: draw the river as a band perpendicular to the road, but do not place it exactly at the point. I move it back to 70% of the segment so the river band does not straddle a corner in the route and look as though the river follows the road.
The part the main map cannot explain is the destination entrance. That stretch of road has a median, and the destination is on the opposite side. Drivers must pass it first, make a U-turn, drive back, and then turn left into it. Drawing this on the main map would mean three overlapping lines within a few millimeters. So I separated it into a close-up with a viewBox of 178 x 66, not to scale, but still with north at the top and the road angled along its true bearing for that stretch: 161.7 degrees from north.
BRG = 161.7 # ทิศของถนนช่วงนี้ (องศาจากเหนือ ตามเข็ม)
th = math.radians(BRG)
UX, UY = math.sin(th), -math.cos(th) # เวกเตอร์ทิศเดินทางบนจอ (มุ่งลงใต้)
EX, EY = UY, -UX # ตั้งฉากกับถนน ชี้ไปทางตะวันออก
CX, CY = 74.0, 36.0 # จุดอ้างอิงกลางภาพ
LANE = 2.3 # เลนห่างจากแกนถนน
def pt(t, o=0.0):
"""t = ระยะตามแนวถนน, o = ระยะขวางถนน (บวก = ตะวันออก)"""
return (CX + t * UX + o * EX, CY + t * UY + o * EY)
go_down = [pt(-30, +LANE), pt(18, +LANE)] # ขาไป: เลนฝั่งหนึ่ง ขับเลยสถานที่ไปก่อน
u_turn = [pt(18, +LANE), pt(21, 0), pt(18, -LANE)]
go_back = [pt(18, -LANE), pt(-6, -LANE)] # ขากลับ: ย้อนขึ้นมาแล้วเลี้ยวซ้ายเข้า
With the pt function in place, I can position everything in the close-up in terms a driver would use: this far along the road, this far to the side. I do not have to calculate screen coordinates for a single point. If the road's bearing changes, changing one number rotates the entire drawing, and a compass in the corner shows true north.
Mistakes I was asked to fix
First, I added 4 lines of explanation below the map, saying things along the lines of every segment following its true bearing, the labels showing actual distances, and the 39 km straight stretch being compressed. The client asked me to remove them. This text came from the generator, so I had to remove it from the generator too, or it would return every time I regenerated the map.
If I am asked to remove or change something in a generated file and only edit the output, the next generation run brings all the old content back. The person who requested the removal then sees something they already asked to have removed reappear. My rule is never to edit output files by hand: change the generator and regenerate them. Then search the output again for the text that was supposed to be removed to confirm none remains.
Second, the document contained 2 copies of the map page, so one had to be removed. This was not the generator's fault, but the person assembling the document had to count the pages.
Third, the map was generated as a fragment: a single piece of HTML without a head, intended to be inserted into the document page. When someone opened the fragment's URL directly, all the Thai text was garbled because the server sent it as text/html without specifying a charset, and the file had no meta declaration either. Images referenced with relative paths were also missing because the image folder returned 403. The fix was to create a separate standalone page specifically for sharing a viewing link, with a doctype, a meta charset declaration, and images embedded as data URIs. Its total size was 240 KB.
import base64, io
def data_uri(path, mime='image/png'):
return 'data:%s;base64,%s' % (mime, base64.b64encode(open(path, 'rb').read()).decode('ascii'))
frag = io.open('map_frag.html', encoding='utf-8').read()
frag = frag.replace('src="img/compass.png"', 'src="%s"' % data_uri('img/compass.png'))
page = ('<!doctype html><html lang="th"><head><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width, initial-scale=1">'
'<title>แผนที่เส้นทาง</title></head><body>%s</body></html>') % frag
io.open('map_standalone.html', 'w', encoding='utf-8', newline='\n').write(page)
The sequence I will reuse for my next route map
- Request the full route geometry from a routing service, save it to a file, and calculate cumulative distances myself.
- Define map points by their kilometer along the route, without manually typing coordinates for points on the road.
- Separate direction from length. Direction comes from atan2 of coordinate differences converted to kilometers; length comes from a formula with a minimum and a cap.
- Fit to the frame using the same multiplier for both axes, leaving margins on the left and right for labels.
- Heavily compressed segments must have break marks, and every point must show its actual cumulative distance.
- Let the cross product determine which side a place is on from actual coordinates, rather than relying on memory.
- Draw junction arms for roads not taken, and put complex areas in close-ups that still preserve bearings.
- Make every change in the generator, then create a standalone page with a charset declaration and embedded images for sharing a link.
In summary, this kind of map makes a deliberate choice about what it will get wrong and what it will not compromise on. Lengths on paper are deliberately wrong, and break marks and kilometer labels make that clear to readers. Bearings, the side of the road each place is on, and junction shapes all come from actual coordinates. Formula constants such as 11, 4.6, and 0.4, and the cap of 24, are values that worked for this route and this paper size. For another route with a different balance of short and long segments, they can be adjusted as needed. The principle that should stay the same is separating direction from length. If I have left anything out or made any typos, I will come back and fix them later.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first