Processing/LLToBNG: bnglookup.py

File bnglookup.py, 2.4 KB (added by benj, 16 years ago)
Line 
1# Script for converting BNG transverse mercator co-ordinates (eastings northings in km) to OS grid square co-ordinates
2#
3# Author: Ben Taylor
4# Created: 05/06/2008
5# Last edit: 05/06/2008
6
7import math
8import sys
9import alphaconv
10
11if (len(sys.argv) != 3):
12    print "Usage: python bnglookup.py eastings northings"
13    sys.exit(1)
14# end if
15
16eastings_in = float(sys.argv[1])
17northings_in = float(sys.argv[2])
18eastings_out = "S0000"
19northings_out = "V0000"
20firstletter = "S"
21secondletter = "V"
22subeasting = eastings_in
23subnorthing = northings_in
24
25if ((eastings_in < 0) or (eastings_in > 700000) or (northings_in < 0) or (northings_in > 1300000)):
26    print "One or both co-ordinates are out of range.\nEastings may be 0-700000, northings may be 0-1300000."
27    sys.exit(1)
28# end if
29
30# Check first letter - 500km grid squares
31if (northings_in < 500000):
32    if (eastings_in < 500000):
33        firstletter = "S"
34    else:
35        subeasting = eastings_in - 500000
36        firstletter = "T"
37    # end if
38else:
39    if (northings_in < 1000000):
40        subnorthing = northings_in - 500000
41        if (eastings_in < 500000):
42            firstletter = "N"
43        else:
44            subeasting = eastings_in - 500000
45            firstletter = "O"
46        # end if
47    else:
48        subnorthing = northings_in - 1000000
49        if (eastings_in < 500000):
50            firstletter = "H"
51        else:
52            subeasting = eastings_in - 500000
53            firstletter = "J"
54        # end if
55    # end if
56# end if
57
58# Work out grid square we're in
59letterconv = (math.ceil(subeasting/100000)) + (5 * (5 - math.ceil(subnorthing/100000)))
60
61# Letter I is skipped in national grid, so add one if we're at or past I
62if (letterconv >= 9):
63    letterconv = letterconv + 1
64# end if
65
66secondletter = alphaconv.num2letter(letterconv)
67
68# Subtract the number of hundred thousand metres from each coordinate - that's covered by the grid letter
69subgrid_e = int(math.floor(subeasting - (100000 * math.floor(subeasting/100000))))
70subgrid_n = int(math.floor(subnorthing - (100000 * math.floor(subnorthing/100000))))
71
72# Get the number of ten thousand metres for each coordinate for the 10km tile
73e_10km = (int(10000 * math.floor(subgrid_e/10000)))/10000
74n_10km = (int(10000 * math.floor(subgrid_n/10000)))/10000
75
76easting_out = firstletter + str(subgrid_e)
77northing_out = secondletter + str(subgrid_n)
78
79print("Grid reference: " + easting_out + " " + northing_out)
80print("10km Tile: " + firstletter + secondletter + str(e_10km) + str(n_10km))