OpenLayers Map Centering and the International Date Line

I recently came across another piece of OpenLayers to be aware of when working with maps that wrap the International Date Line. I store the map extent throughout a user’s session so they can leave the map page, come back, and still see the same set of results as when they left. Unfortunately, the map was sometimes taking a stored location in the North Pacific and displaying Northern Africa instead! Obviously not what I want it to do. Before I get into why this happens, here’s a few OpenLayers object introductions to make sure we’re all on the same page.

The Layer object can understand what projection you’re working in, if you happen to give it one. If the displayed map area happens to wrap around the IDL (and your layers are set up correctly), the Layer object gracefully acknowledges the IDL and produces correct coordinates.

In contrast, the Bounds object is pure math. It’s meant to be as projection-agnostic as possible without actually messing up coordinates in objects that do know about projections and their quirks. This can be a very good thing, since doing math without worrying about projections is a lot faster and works just fine in most cases.

The problem I ran into comes from one little Layer object configuration option that is uncharacteristically poorly documented: wrapDateLine. The issue it tells you to reference (#487) talks about using modular arithmatic to fix how layers handle the IDL… I’m not a math person, but handling the IDL is exactly what I want it to do! Too bad they couldn’t have mentioned this in the documentation.  ;)   What the Map winds up doing if you don’t have this config option set is using the Bounds object’s straight-up math to get the center of the extent. Unfortunately, using straight math when the IDL is in play puts the center of the map at the longitude exactly opposite of where logic dictates it should go. If the wrapDateLine configuration item is set, then the Layer tells the Map “Whoa, there! The Bounds object doesn’t know about the IDL, but I do. Use my math first.” So the Map uses the Layer’s math to turn the extent into coordinates that the Bounds object’s math will work correctly on. Viola! The North Pacific!

So the simple fix is to have wrapDateLine: true in your layer configuration object.

To see this bit of oddness ‘in action’, go to the OpenLayers Google Map example and pan the map so that the IDL is in view. Using FireBug, enter the commands map.getCenter() and map.getExtent().getCenterLonLat(). The resulting coordinate longitudes will be on opposite sides of the planet.

Both comments and trackbacks are currently closed.