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

Jon Burgess jburgess777 at googlemail.com
Thu Nov 15 22:39:43 GMT 2007


On Thu, 2007-11-15 at 22:50 +0100, Rune Baggetun wrote:
> > 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.
> 

Looks like you've got your lat and long muddled up. Swapping them around
gives the correct tile x/y/z and offset. The attached script also adds a
link to the tile so you can check in your browser.

$ ./tile.pl
Tile URL: http://tile.openstreetmap.org/15/16864/9452.png
232
249

Note that the offset is measured from the top left corner of the tile,
hence this puts the dot very close to the bottom right hand corner as
you show in your other example.

	Jon



-------------- next part --------------
A non-text attachment was scrubbed...
Name: tile.pl
Type: application/x-perl
Size: 399 bytes
Desc: not available
URL: <http://lists.openstreetmap.org/pipermail/dev/attachments/20071115/1c53346b/attachment.bin>


More information about the dev mailing list