Tuesday, November 11, 2008

Spherical Mercator - Because the World Really is Flat

So, recently I have been working with OpenLayers and KML, just learning each of the technologies, and I discovered something odd. When I added a KML path as a Layer on my OpenLayers, my path liked to move around. No matter where the map was centered, the path was in the same place in the window. That is when I started investigating spherical mercator. Its not too tough to add, and it will quickly fix this problem. Basically, what is happening is that your map is round, but your KML is flat. You will need to fix this by making both of them flat.

Here are the basics that you need:

var map = new OpenLayers.Map(('map'),
{projection: new OpenLayers.Projection("EPSG:900913"), displayProjection: new OpenLayers.Projection("EPSG:4326"), units: "m",
maxExtent: new OpenLayers.Bounds(-20037508, -2003750, 20037508, 20037508.34)});

var mapService = new OpenLayers.Layer.Google( "Google", { sphericalMercator: true, type: G_PHYSICAL_MAP } );

map.addLayer(mapService);

map.addLayer(new OpenLayers.Layer.GML("KML",
"http://youraddress/kmlFile.kml",
{projection: map.displayProjection,
format: OpenLayers.Format.KML,
formatOptions: {extractStyles: true,
extractAttributes: true}}));

Once you've added this, now your path (or whatever KML you want to use) should stay in place, and you're done.