Simulating Markers with a Tile Layer
[google-map-tiles.git] / USNaviguide_Google_Tiles.pm
1 # Calculate tile characteristics given a bounding box of coordinates and a zoom...
2 # Author. John D. Coryat 01/2008...
3 # USNaviguide LLC.
4 # Published under Apache 2.0 license.
5 # Adapted from: Google Maps API Javascript...
6 ##
7 # In order to correctly locate objects of interest on a Custom Map Overlay Google Maps, 
8 # the characteristics of each tile to build are required.
9 ##
10 # Google_Tiles                                  # Calculate all tiles for a bounding box and zoom
11 # Google_Tile_Factors                           # Calculate the factors needed ( Zoom, Tilesize )
12 # Google_Tile_Calc                              # Calculate a single tile features from a tile name and zoom
13 # Google_Tile_to_Pix                            # Calculate tile name to pixel
14 # Google_Coord_to_Pix                           # Calculate coordinate to Pixel
15 # Google_Pix_to_Coord                           # Calculate Pixels to coordinates
16 # Google_Pix_to_Tile                            # Calculate a tile name from a pixel location and zoom
17
18 require 5.003 ;
19 package USNaviguide_Google_Tiles ;
20 use strict ;
21 use Math::Trig ;
22
23 BEGIN {
24  use Exporter ;
25  use vars qw ( $VERSION @ISA @EXPORT) ;
26  $VERSION       = 1.0 ;
27  @ISA           = qw ( Exporter ) ;
28  @EXPORT        = qw ( 
29  Google_Tiles
30  Google_Tile_Factors
31  Google_Tile_Calc
32  Google_Tile_to_Pix
33  Google_Coord_to_Pix
34  Google_Pix_to_Coord
35  Google_Pix_to_Tile
36  ) ;
37 }
38
39 #
40 # Call as: <array of Hashes> = &Google_Tiles(<LatitudeS>, <LongitudeW>, <LatitudeN>, <LongitudeE>, <Zoom>, [<option: tileSize>], [<option: Partial/Whole>]) ;
41 # Partial/Whole option: (Default: Partial)
42 #       Partial: Include the edge to create partial tiles
43 #       Whole: Include only tiles that are contained by the bounds
44 #
45 #          Returned Array Specifications:
46 #            Each element is a reference to a Hash:
47 #              NAMEY - Tile Name y
48 #              NAMEX - Tile Name x
49 #              PYS - Pixel South
50 #              PXW - Pixel West
51 #              PYN - Pixel North
52 #              PXE - Pixel East
53 #              LATS - South Latitude
54 #              LNGW - West Longitude
55 #              LATN - North Latitude
56 #              LNGE - East Longitude
57 #
58 #          Note: X is width, Y is height...
59 #
60
61 sub Google_Tiles
62 {
63  my $latS       = shift ;
64  my $lngW       = shift ;
65  my $latN       = shift ;
66  my $lngE       = shift ;
67  my $zoom       = shift ;
68  my $tileSize   = shift ;
69  my $parwho     = shift ;
70  my $ty         = 0 ;
71  my $tx         = 0 ;
72  my @ret        = ( ) ;
73  my %first      = ( ) ;                         # First Results Hash
74  my %last       = ( ) ;                         # Last Results Hash
75
76  my $value      = &Google_Tile_Factors($zoom, $tileSize) ; # Calculate Tile Factors
77
78  if (!defined($parwho) or !$parwho)
79  {
80   $parwho = 'Partial' ;
81  }
82
83  # NW: Convert Coordinates to Pixels...
84
85  ($first{'NORTH'},$first{'WEST'}) = &Google_Coord_to_Pix( $value, $latN, $lngW ) ;
86
87  # Convert Pixels to Tile Name...
88
89  ($first{'NAMEY'},$first{'NAMEX'}) = &PixtoTileName( $value, $first{'NORTH'}, $first{'WEST'}, 'N', 'W', $parwho ) ;
90
91  # SE: Convert Coordinates to Pixels...
92
93  ($last{'SOUTH'},$last{'EAST'}) = &Google_Coord_to_Pix( $value, $latS, $lngE ) ;
94
95  # Convert Pixels to Tile Name...
96
97  ($last{'NAMEY'},$last{'NAMEX'}) = &PixtoTileName( $value, $last{'SOUTH'}, $last{'EAST'}, 'S', 'E', $parwho ) ;
98
99  # Calculate tile values for all tiles...
100
101  if ( $first{'NAMEX'} > $last{'NAMEX'} )                        # Across the date line
102  {
103   for ( $ty = $first{'NAMEY'} ; $ty <= $last{'NAMEY'} ; $ty++ )
104   {
105    for ( $tx = $first{'NAMEX'} ; $tx <= $$value{'max'} ; $tx++ )
106    {
107     push( @ret, {&Google_Tile_Calc( $value, $ty, $tx)} ) ;
108    }
109    for ( $tx = 0 ; $tx <= $last{'NAMEX'} ; $tx++ )
110    {
111     push( @ret, {&Google_Tile_Calc( $value, $ty, $tx)} ) ;
112    }
113   }
114  } else
115  {
116   for ( $ty = $first{'NAMEY'} ; $ty <= $last{'NAMEY'} ; $ty++ )
117   {
118    for ( $tx = $first{'NAMEX'} ; $tx <= $last{'NAMEX'} ; $tx++ )
119    {
120     push( @ret, {&Google_Tile_Calc( $value, $ty, $tx)} ) ;
121    }
122   }
123  }
124
125  $ret[0]{'NORTH'} = $first{'NORTH'} ;
126  $ret[0]{'WEST'} = $first{'WEST'} ;
127
128  $ret[$#ret]{'SOUTH'} = $last{'SOUTH'} ;
129  $ret[$#ret]{'EAST'} = $last{'EAST'} ;
130  
131  return ( @ret ) ;
132 }
133
134 # Calculate Tile Factors...
135
136 sub Google_Tile_Factors
137 {
138  my $zoom       = shift ;
139  my $tileSize   = shift ;
140  my %value      = ( ) ;
141
142  # Validate and correct input parameters...
143
144  if ( !defined($zoom) or $zoom < 0 )
145  {
146   $zoom = 0 ;
147  }
148
149  if ( !defined($tileSize) or !$tileSize )
150  {
151   $tileSize     = 256 ;
152  }
153
154  # Calculate Values...
155
156  $value{'zoom'} = $zoom ;
157  $value{'PI'}   = 3.1415926536 ;
158  $value{'bc'}   = 2 * $value{'PI'} ;
159  $value{'Wa'}   = $value{'PI'} / 180 ;
160  $value{'cp'}   = 2 ** ($value{'zoom'} + 8) ;
161  $value{'max'}  = (2 ** $value{'zoom'}) - 1 ;           # Maximum Tile Number
162  $value{'pixLngDeg'}= $value{'cp'} / 360;
163  $value{'pixLngRad'}= $value{'cp'} / $value{'bc'} ;
164  $value{'bmO'}  = $value{'cp'} / 2 ;
165  $value{'tileSize'} = $tileSize ;
166
167  return \%value ;
168 }
169
170 # Calculate tile values from Name...
171
172 sub Google_Tile_Calc
173 {
174  my %result     = ( ) ;
175  my $value      = shift ;
176  $result{'NAMEY'} = shift ;
177  $result{'NAMEX'} = shift ;
178
179  # Convert Tile Name to Pixels...
180
181  ($result{'PYN'},$result{'PXW'}) = &Google_Tile_to_Pix( $value, $result{'NAMEY'}, $result{'NAMEX'} ) ;
182
183  # Convert Pixels to Coordinates (Upper Left Corner)...
184
185  ($result{'LATN'},$result{'LNGW'}) = &Google_Pix_to_Coord( $value, $result{'PYN'}, $result{'PXW'} ) ;
186
187  $result{'PYS'} = $result{'PYN'} + 255 ;
188  $result{'PXE'} = $result{'PXW'} + 255 ;
189
190  # Convert Pixels to Coordinates (Lower Right Corner)...
191
192  ($result{'LATS'},$result{'LNGE'}) = &Google_Pix_to_Coord( $value, $result{'PYS'}, $result{'PXE'} ) ;
193
194  return %result ;
195 }
196
197 # Translate a coordinate to a pixel location...
198
199 sub Google_Coord_to_Pix
200 {
201  my $value      = shift ;
202  my $lat        = shift ;
203  my $lng        = shift ;
204  my @d          = ( ) ; 
205  my $e          = 0 ;
206
207  if ( $lat > 85.05 )
208  {
209   $lat = 85.05 ;
210  }
211  if ( $lat < -85.05 )
212  {
213   $lat = -85.05 ;
214  }
215
216  if ( $lng > 180 )
217  {
218   $lng = 180 ;
219  }
220  if ( $lng < -180 )
221  {
222   $lng = -180 ;
223  }
224
225  $d[1] = sprintf("%0.0f", $$value{'bmO'} + $lng * $$value{'pixLngDeg'} ) ;
226
227  $e = sin($lat * $$value{'Wa'}) ;
228
229  if( $e > 0.99999 )
230  {
231   $e = 0.99999 ;
232  }
233
234  if( $e < -0.99999 )
235  {
236   $e = -0.99999 ;
237  }
238
239  $d[0] = sprintf("%0.0f", $$value{'bmO'} + 0.5 * log((1 + $e) / (1 - $e)) * (-1) * $$value{'pixLngRad'} ) ;
240
241  return (@d) ;
242 }
243
244 # Calculate a tile name from a pixel location and zoom: Externally called version...
245
246 sub Google_Pix_to_Tile
247 {
248  my $value      = shift ;
249  my $ty         = shift ;
250  my $tx         = shift ;
251
252  # Convert Pixels to Tile Name...
253
254  ($ty,$tx) = &PixtoTileName( $value, $ty, $tx, 'N', 'W', 'Partial' ) ;
255
256  return ( $ty,$tx ) ;
257 }
258
259 # Translate a pixel location to a tile name: Internally called version...
260
261 sub PixtoTileName
262 {
263  my $value      = shift ;
264  my $y          = shift ;
265  my $x          = shift ;
266  my $yd         = shift ;                               # Y Direction: N or S
267  my $xd         = shift ;                               # X Direction: W or E
268  my $parwho     = shift ;                               # Partial / Whole
269  my $yn         = 0 ;                                   # Y Name
270  my $xn         = 0 ;                                   # X Name
271
272  $yn = int( $y / $$value{'tileSize'} ) ;                # Round Down
273  $xn = int( $x / $$value{'tileSize'} ) ;                # Round Down
274
275  if ( $parwho ne 'Partial' )
276  {
277   if ( $yd eq 'N' )
278   {
279    $yn++ ;
280   } else
281   {
282    $yn-- ;
283   }
284   if ( $xd eq 'W' )
285   {
286    $xn++ ;
287   } else
288   {
289    $xn-- ;
290   }
291  }
292
293  # Make sure tile numbers are sane...
294
295  if ( $yn > $$value{'max'} )
296  {
297   $yn = $$value{'max'} ;
298  } elsif ( $yn < 0 )
299  {
300   $yn = 0 ;
301  }
302
303  if ( $xn > $$value{'max'} )
304  {
305   $xn = $$value{'max'} ;
306  } elsif ( $xn < 0 )
307  {
308   $xn = 0 ;
309  }
310
311  return( $yn, $xn ) ; 
312 }
313
314 # Translate a tile name to a pixel location...
315
316 sub Google_Tile_to_Pix
317 {
318  my $value      = shift ;
319  my $y          = shift ;
320  my $x          = shift ;
321  return( (sprintf("%0.0f", $y * $$value{'tileSize'} ), sprintf("%0.0f", $x * $$value{'tileSize'} )) ) ; 
322 }
323
324 # Translate a pixel location to a coordinate...
325
326 sub Google_Pix_to_Coord
327 {
328  my $value      = shift ;
329  my $y          = shift ;
330  my $x          = shift ;
331  my @d          = ( ) ;
332  my $e          = (($y - $$value{'bmO'}) / $$value{'pixLngRad'}) * (-1) ;
333
334  $d[1]  = sprintf("%0.6f",($x - $$value{'bmO'}) / $$value{'pixLngDeg'}) ;
335
336  $d[0]  = sprintf("%0.6f", (2 * atan(exp($e)) - $$value{'PI'} / 2) / $$value{'Wa'}) ;
337  return (@d);
338 }
339
340 1;
341
342 __END__
343
344 =head1 SYNOPSIS
345
346 #!/usr/bin/perl -w
347 # Test Program:
348
349 # Google Tile Calculator Test Program...
350 # Author. John D. Coryat 01/2008 USNaviguide LLC
351
352 use strict;
353 use USNaviguide_Google_Tiles ;
354
355 my $latS        = 34.177442 ;
356 my $lngW        = -91.318359 ;
357 my $latN        = 35.797300 ;
358 my $lngE        = -88.681641 ;
359 my $zoom        = 8 ;
360 my $x           = '' ;
361 my %tile        = ( ) ;
362 my $i           = 0 ;
363
364 my @d = &Google_Tiles($latS, $lngW, $latN, $lngE, $zoom,0,'Whole');
365
366 print "Total: " . scalar(@d) . "\n" ;
367
368 for ( $i = 0; $i <= $#d; $i++ )
369 {
370  print "Tile # $i Y: $d[$i]{'NAMEY'} X: $d[$i]{'NAMEX'}\n" ;
371
372  %tile = %{$d[$i]} ;
373
374  foreach $x (sort keys %tile)
375  {
376   print "\t$x: $tile{$x}\n" ;
377  }
378 }
379
380 =cut