Map projection on a two-dimensional terminal with Go
Programming Snapshot – Go Map Projections
While searching for a method to draw geodata right into the terminal, Mike Schilli discovers the wondrous world of map projections.
While I was working on hikefind
, a command-line program that chooses a trail from a collection of GPX files with track points, for a recent issue [1], I got the idea of drawing the trail contours the program found in a terminal window. Unfortunately, a GPX file generated by an app such as Komoot or a Garmin tracker only contains geocoordinates as floating-point numbers. They refer to the points of the globe through which the trail passes (Figure 1).
These geopoints on a spherical surface now need to be converted to a two-dimensional coordinate system so that they look as natural as possible on a flat map. This problem was solved centuries ago. Any map, whether paper or digital, is based on the genius idea of projecting geopoints on the globe, which are available as latitude and longitude values, onto an XY coordinate system on a plane.
Back to the Year 1569
As early as 1569, Gerhard Mercator, a cartographer from Flanders, set out to flatten the spherical data determined by early sea navigators. To do this, he simply projected the spherical surface of the Earth onto a cylinder wound around it (Figure 2). The outer layer of the cylinder, in turn, can be easily unrolled and viewed as a flat map. However, this projection (with a vertical winding cylinder) is only 100 percent correct at the equator and suffers from distortions to the north or south of it, until – finally – grotesquely inflated land masses appear in the polar regions.
But when it comes to drawing my trails in a terminal window, an even simpler mechanism will do the trick. The algorithm simply interprets the numerical degrees for longitude and latitude as values that increase linearly with the actual distance on the globe. In other words, the method interprets an area on the surface of a sphere constrained by longitude and latitude as a simple rectangle, even though the actual object is curved. This is not exactly accurate, of course, but it comes very close to the truth for relatively small areas in the context of the gigantic spherical radius of the Earth.
Minima and Maxima
For example, if a trail extends between longitudes -31.002 and -31.001 (longitudes west of the prime meridian have negative values), and the display terminal has a width of 80 characters, the linear projection maps the longitudes to integer X-values between 0 and 79 (Figure 3). The sample principle applies to latitudes and their projected Y-values.
To do this, Listing 1 uses the projectSimple()
function starting in line 28 to first determine the minimum and maximum values for the geographical latitude and longitude of all track points of the recorded trail as the latMin
/latMax
and lonMin
/lonMax
variables. During the first round of the for
loop starting in line 33, the variable first
is set to true
, and the function initializes the overall min/max values found to the position of the first track point. In the following rounds, first
is set to false
, and the extremes only change if the current track point is outside the previously defined window.
Listing 1
gpx.go
01 package main 02 import ( 03 "flag" 04 "fmt" 05 "github.com/tkrajina/gpxgo/gpx" 06 "image" 07 "os" 08 "path" 09 ) 10 11 func gpxPoints(path string) ([]gpx.GPXPoint, error) { 12 gpxData, err := gpx.ParseFile(path) 13 points := []gpx.GPXPoint{} 14 if err != nil { 15 return points, err 16 } 17 18 for _, trk := range gpxData.Tracks { 19 for _, seg := range trk.Segments { 20 for _, pt := range seg.Points { 21 points = append(points, pt) 22 } 23 } 24 } 25 return points, nil 26 } 27 28 func projectSimple(geo []gpx.GPXPoint, width int, height int) []image.Point { 29 xy := []image.Point{} 30 var latMin, latMax, lonMin, lonMax float64 31 first := true 32 33 for _, gpxp := range geo { 34 if first { 35 latMin = gpxp.Latitude 36 latMax = gpxp.Latitude 37 lonMin = gpxp.Longitude 38 lonMax = gpxp.Longitude 39 first = false 40 continue 41 } 42 if gpxp.Latitude < latMin { 43 latMin = gpxp.Latitude 44 } 45 if gpxp.Latitude > latMax { 46 latMax = gpxp.Latitude 47 } 48 if gpxp.Longitude < lonMin { 49 lonMin = gpxp.Longitude 50 } 51 if gpxp.Longitude > lonMax { 52 lonMax = gpxp.Longitude 53 } 54 } 55 56 latSpan := latMax - latMin 57 lonSpan := lonMax - lonMin 58 for _, gpxp := range geo { 59 x := int((gpxp.Longitude - lonMin) / lonSpan * float64(width-1)) 60 y := int((gpxp.Latitude - latMin) / latSpan * float64(height-1)) 61 y = height - y - 1 // y counts top to bottom 62 xy = append(xy, image.Pt(x, y)) 63 } 64 return xy 65 } 66 67 func cmdLineParse() (string, string) { 68 flag.Parse() 69 prog := path.Base(os.Args[0]) 70 flag.Usage = func() { 71 fmt.Printf("usage: %s gpxfile\n", prog) 72 os.Exit(1) 73 } 74 args := flag.Args() 75 if len(args) != 1 { 76 flag.Usage() 77 } 78 return prog, args[0] 79 }
Once the for
loop is done with all the track points, lines 56 and 57 set the widths of these windows to latSpan
and lonSpan
. Given this maximum bandwidth, lines 59 and 60 compute the X- and Y-coordinates for the target coordinate system in the terminal window. To do this, they determine the distance of the current track points in the GPX data from the left or bottom edge of the window, divide this by the window width, and multiply the resulting floating-point value by the width of the target system.
This gives me the X- and Y-values from
to width-1
and height-1
in the target window, which is width
characters wide and height
characters high. Because the X-coordinates in the terminal window later run from left to right, but the Y-coordinates (especially in the GUI shown below) run from top to bottom, line 61 turns the Y-values on their heads.
Initially, the gpxPoints()
function reads the data from the GPX file starting in line 11 in Listing 1 and conveniently provides it to the caller as an array slice of floating-point values. The gpx package from GitHub lends a hand in interpreting the GPX format here; it will be downloaded and included in the source code automatically later on when you compile the binary.
At the end of Listing 1 there is a cmdLineParse()
function, which you need in the various main programs to analyze the command-line parameters, as submitted by users typing them in the shell.
On Screen!
The main program for easy plotting of the GPX data in a terminal (Listing 2) expects a GPX file with the XML-encoded geodata of a trail as an argument on the command line. It uses the gpxPoints()
function from Listing 1 to extract the track points. Line 18 in Listing 2 calls the projectSimple()
function from Listing 1 and passes both an array slice of GPX points and the dimensions of the current terminal, which are dynamically determined by the GitHub term package. The returned object is an array slice with the XY coordinates of the track points projected onto the flat terminal area.
Listing 2
gpx-plot.go
01 package main 02 import ( 03 "fmt" 04 "golang.org/x/term" 05 "log" 06 ) 07 08 func main() { 09 _, file := cmdLineParse() 10 geo, err := gpxPoints(file) 11 if err != nil { 12 log.Fatalf("Parse error: %v\n", err) 13 } 14 15 width, height, _ := term.GetSize(0) 16 height -= 2 17 isSet := map[int]bool{} 18 xy := projectSimple(geo, width, height) 19 20 for _, pt := range xy { 21 isSet[pt.Y*width+pt.X] = true 22 } 23 24 for row := 0; row < height; row++ { 25 for col := 0; col < width; col++ { 26 ch := " " 27 if isSet[row*width+col] { 28 ch = "*" 29 } 30 fmt.Print(ch) 31 } 32 fmt.Print("\n") 33 } 34 }
To allow the line-by-line output starting in line 24 to quickly check whether the terminal cell in the current output contains the trail's track point, line 17 creates a map named isSet
. It uses a row and column index to reference a Boolean value that is true for track points and false everywhere else. In a scripting language such as Python, this could be done easily with a two-dimensional hashmap or matrix. But doing this in Go is a Sisyphean task, because the program code needs to manually handle second-order memory management, which bloats the code disproportionately. This is why Listing 2 resorts to a trick and uses a one-dimensional map. The index here is the integer value y*width+x
(i.e., the offset of the current element if you treat the cells along all the terminal rows as a continuous array).
The double for
loop starting in line 24 then finally outputs the trail line-by-line on the terminal (Figure 4). To do this, the code first assumes that there isn't a track point for the coordinate currently being processed; this is why it sets the output string ch
to a space character. But if the lookup in the isSet()
map reveals that there indeed is a track point, it sets the string to an asterisk character *
. Line 30 outputs the contents of the current cell and then moves on to the next round; it does this until it reaches the end of the current line and then moves on to the next line.
The usual three-card trick, shown in Listing 3, compiles the source files and links in the packages I referenced from GitHub. The result is a binary named gpx-plot
, which expects the name of a GPX file, as shown in Figure 5, and then draws the track points from the file on standard output in the terminal.
Listing 3
Compiling
$ go mod init hikemap $ go mod tidy $ go build gpx-plot.go gpx.go
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters
Support Our Work
Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.
News
-
Gnome 48 Debuts New Audio Player
To date, the audio player found within the Gnome desktop has been meh at best, but with the upcoming release that all changes.
-
Plasma 6.3 Ready for Public Beta Testing
Plasma 6.3 will ship with KDE Gear 24.12.1 and KDE Frameworks 6.10, along with some new and exciting features.
-
Budgie 10.10 Scheduled for Q1 2025 with a Surprising Desktop Update
If Budgie is your desktop environment of choice, 2025 is going to be a great year for you.
-
Firefox 134 Offers Improvements for Linux Version
Fans of Linux and Firefox rejoice, as there's a new version available that includes some handy updates.
-
Serpent OS Arrives with a New Alpha Release
After months of silence, Ikey Doherty has released a new alpha for his Serpent OS.
-
HashiCorp Cofounder Unveils Ghostty, a Linux Terminal App
Ghostty is a new Linux terminal app that's fast, feature-rich, and offers a platform-native GUI while remaining cross-platform.
-
Fedora Asahi Remix 41 Available for Apple Silicon
If you have an Apple Silicon Mac and you're hoping to install Fedora, you're in luck because the latest release supports the M1 and M2 chips.
-
Systemd Fixes Bug While Facing New Challenger in GNU Shepherd
The systemd developers have fixed a really nasty bug amid the release of the new GNU Shepherd init system.
-
AlmaLinux 10.0 Beta Released
The AlmaLinux OS Foundation has announced the availability of AlmaLinux 10.0 Beta ("Purple Lion") for all supported devices with significant changes.
-
Gnome 47.2 Now Available
Gnome 47.2 is now available for general use but don't expect much in the way of newness, as this is all about improvements and bug fixes.