[OSM-dev] How to translate coordinate to pixel for a tile ?

Rune Baggetun baggetun at gmail.com
Thu Nov 15 21:50:07 GMT 2007


> where it does "* 2**z" (or "1<<zoom") just multiply by an extra 256
> (the pixel size of a tile).
> then:
> tile number = floor(n/256)
> pixel = n mod 256
>
> so:
> my $x = ($lon+180)/360 *2**$z * 256;
> my $y = (1 - log(tan($lat*pi/180) + sec($lat*pi/180))/pi)/2 *2**$z * 256;
> my $xtile = int($x/256);
> my $ytile = int($y/256);
> my $xpixel = $x % 256;
> my $ypixel = $y % 256;

I can't get it to work. What am I doing wrong ?

Example:
Using the tile code at the wiki I made a 'proxy' service to serve my
j2me application.

Service for my j2me application:
http://bybris.intermedia.uib.no/locatext/returnOSMTile.py?coords=60.3434,005.2834

As you can see I get the tile for the coordinates: 60.3434,005.2834

The tile is the right one. This is verified :-)

If I paint a dot on that tile at that location (60.3434,005.2834)
manually the dot will appear here:
http://bybris.intermedia.uib.no/locatext/tileMarked.png

If I paint it where the perl code above tells me to paint the dot it
will be here:
http://bybris.intermedia.uib.no/locatext/tileMarkedComputedDot.png

This is how I tested the perl code:

#!/usr/bin/perl
use Math::Trig;
my $lon = 60.3434;
my $lat = 5.2834;

my $z = 15;
my $x = ($lon+180)/360 *2**$z * 256;
my $y = (1 - log(tan($lat*pi/180) + sec($lat*pi/180))/pi)/2 *2**$z * 256;
my $xtile = int($x/256);
my $ytile = int($y/256);
my $xpixel = $x % 256;
print "$xpixel\n";
my $ypixel = $y % 256;
print "$ypixel\n";


This is the output:

151
105

This is actually the first piece of perl code I've written (or copied)
so I am not surprised if I did something wrong. I do most my
'amateurish' coding in java and python.


Regards

-- 
Rune Baggetun




More information about the dev mailing list