Factbook Map Table

From XPUB & Lens-Based wiki
Revision as of 12:57, 21 May 2008 by Michael Murtaugh (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Making a map with no overlaps

The map is interesting, but it might be useful to draw the names of countries without any overlapping. You could consider making a more sophisticated layout algorithm that remembers where country names have been placed and avoids reusing the same space. On the other hand, what if you could use the browsers built in mechanism for doing "flow layouts" (that is, placing elements left to right, wrapping when necessary). If you could, for instance, create a grid of <div> boxes which you use to approximately place a given country name, then allow the browser to "flow layout" the names in each box -- you can keep the code relatively simple.

What you need, however, is a simple way to work with a grid of cells. In HTML, this can be most readily realized with a <table> -- in Python, this is close to what is called a Sparse Matrix in HowToThink, chapter 10.4. see MakingTables

#!python numbers=off
#!/usr/bin/python

def maketablefromsparsematrix (matrix, rows, cols):
	print "<table>"
	for row in range(0, rows):
		print "<tr>"
		for col in range(0, cols):
			if matrix.has_key((row, col)):
				print "<td>%s</td>" % matrix[row, col]
			else:
				print "<td> </td>"
		print "</tr>"
	print "</table>"

ROWS=12
COLS=8

from settings import *
from [[MySQLdb]].cursors import [[DictCursor]]

conn = connect_to_db()
cursor = conn.cursor([[DictCursor]])
cursor.execute("SELECT * F ROM countries ORDER BY name")

print "Content-type: text/html"
print

print """<html>
<head>
<style lang="text/css">
a		{ text-decoration: none }
a:hover	{ background: black; color: white }
</style>
</head>
<body>"""

MINLONG = -180; MAXLONG = 180
MINLAT = -90; MAXLAT = 90
mapmatrix = {}

print "<h1>map table</h1>"
print """<div style="position: relative">"""
while 1:
	dbrow = cursor.fetchone()
	if (dbrow == None): break
	clat = dbrow['latitude']
	clong = dbrow['longitude']
	
	if (clat and clong):
		centerx = 400
		centery = 200
		
		# longitude goes from -180 to +180
		# latitude goes from -90 to +90
		
		col_scaler = (1.0 * clong - MINLONG) / (MAXLONG - MINLONG)
		col = int(col_scaler * COLS-1)
		
		row_scaler = (1.0 * clat - MINLAT) / (MAXLAT - MINLAT)
		row_scaler = 1.0 - row_scaler
		row = int(row_scaler * ROWS-1)
		
		country = """<div style="float: left; margin-right: 1px; font-size: 10px;">"""
		country += """<a href="country.cgi?id=%s">%s<a></div>""" % (dbrow['id'], dbrow['name'])
		mapmatrix[row, col] = mapmatrix.get((row, col), "") + country
		
maketablefromsparsematrix(mapmatrix, ROWS, COLS)

print "</div>"
print "</body>"
print "</html>"

http://pzwart2.wdka.hro.nl/~techday/cgi-bin/factbook/maptable.cgi