Jump to the following:

We use cookies to improve this website. Read about cookies

OS OpenSpace: Eastings & Northings from Grid Reference

Supplied by our customer Bill Chadwick

Use this to make an OpenSpace MapPoint from a grid reference string (1-5 digits). Return is null if the grid reference is not valid.

Here are two functions to convert a Grid Reference (e.g. NH196806) to Eastings & Northings values (e.g. 219600 and 880600).

Javascript Version

This returns an OpenSpace MapPoint objects.

function NGR2NE(ngr){
var e;
var n;

ngr = ngr.toUpperCase(ngr);

//remove any spaces
var bits = ngr.split(' ');
ngr = "";
for(var i=0;i<bits.length;i++)
    ngr+=bits[i];

var c = ngr.charAt(0);
if (c =='S'){ 
    e = 0;
    n = 0;
    }
else if (c == 'T'){
    e = 500000;
    n = 0;
    }
else if (c == 'N'){ 
    n = 500000;
    e = 0;
    }
else if (c == 'O'){
    n = 500000;
    e = 500000;
    }
else if(c == 'H'){
    n = 1000000;
    e = 0;
    }
else 
    return null;
    
c = ngr.charAt(1);
if(c == 'I')
    return null;
    
c = ngr.charCodeAt(1) - 65;
if(c > 8)
    c -= 1;
e += (c % 5) * 100000;
n += (4 - Math.floor(c/5)) * 100000;

c = ngr.substr(2);
if ((c.length%2) == 1) 
    return null;
if (c.length > 10) 
    return null;

try{
    var s = c.substr(0,c.length/2);
    while(s.length < 5)
        s += '0';
    e += parseInt(s,10); 
    if(isNaN(e))
        return null; 
    
    s = c.substr(c.length/2);
    while(s.length < 5)
        s += '0';
    n += parseInt(s,10); 
    if(isNaN(n))
        return null;
        
    return new OpenSpace.MapPoint(e,n);
}
catch (ex)
{
    return null;
}

}

Python version

This is a very similar algorithm to the javascript one above. This function does not return an OpenSpace.MapPoint but a tuple containting the Easting and Northing values.

def GR_to_NE( gr ):	
	gr = gr.strip().replace( ' ', '' )
	if len(gr) == 0 or len(gr) % 2 == 1 or len(gr) > 12:
	    return None, None
	 
	gr = gr.upper()  
	if gr[0] not in 'STNOH' or gr[1] == 'I' :
		return None, None
		
	e = n = 0
	c = gr[0]
	
	if c == 'T' :
		e = 500000
	elif c == 'N' :
		n = 500000
	elif c == 'O' :
		e = 500000
		n = 500000
	elif c == 'H':
		n = 10000000
	
	c = ord(gr[1]) - 66
	if c < 8: # J
	    c += 1;
	    
	e += (c % 5) * 100000;
	n += (4 - c/5) * 100000;
	
	c = gr[2:]
	try :
	    s = c[:len(c)/2]
	    while len(s) < 5 :
	    	s += '0'
	    	
	    e += int( s ) 
	    
	    s = c[-len(c)/2:]
	    while len(s) < 5 :
	    	s += '0';
		
	    n += int( s )
	    
	except Exception:
	    return None,None;
	
	return e,n

We hope you find this useful.

Back to top
© Ordnance Survey 2016
Be sure to take a look at our Terms of Use and Privacy Policy