Thursday, January 25, 2007
In my Asteroid Occultation site I generate dynamic Google Maps that draw the occultation paths with 5 Polyline elements. One of the things I wanted to do is center the polylines in the displayed map. Easy enough, I parse an XML response with coordinates (the AJAX part of the project) and store those in arrays. Simply take the middle coordinate from the middle polyline and center on that when the map is fully rendered. I wrote something like this:

var pts[];

// store coordinates in pts array

var middle = pts[pts.length / 2];


Easy as pi. Not. For some reason my maps wouldn't always center properly. Adding some debug messages I found that 'middle' was sometimes set to undefined. Unlike other languages I've used in the past (c/c++, VB6, VB.NET, Perl, PHP) if you divide an integer by another integer and use the result as another integer, you get, well, an integer. Not so in Javascript apparently. pts[5.5] is nothing. I assumed, incorrectly, that this would be pts[5] or pts[6]. For my application I don't care if the left or right middle element is chosen.

A little Googling found this article http://rextang.net/blogs/work/archive/2006/01/09/3325.aspx which suggests an easy way to turn a number into an integer. Simply do a bitwise or with 0:

var middle = pts[(pts.length / 2) | 0];

This works great! Someone then posted a comment saying that 'parseInt' is a more readable solution and I agree. I still liked the |0 solution though :)

1/25/2007 1:50:06 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
Related Posts:
Firebug 1.0: a terrific debugger for Firefox

Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):