I am relatively new to open layers, but pretty familiar with the google maps api.
I've done the following with google maps before. I am basically trying to replicate the same functionality with open layers/open street maps. But I've run into a puzzle.
map = new OpenLayers.Map("map");
wms = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: 'basic'} );
osm = new OpenLayers.Layer.OSM();
map.addLayer(wms);
epsg4326 = new OpenLayers.Projection("EPSG:4326"); //WGS 1984 projection
projectTo = map.getProjectionObject(); //The map projection (Spherical Mercator)
var lonLat = new OpenLayers.LonLat(-71.3699930, 43.5412410).transform(epsg4326, projectTo);
var zoom=12;
map.setCenter (lonLat, zoom);
var vectorLayer = new OpenLayers.Layer.Vector("Overlay");
var encoded = "_p~iF~ps|U_ulLnnqC_mqNvxq`@";
var format = new OpenLayers.Format.EncodedPolyline({geometryType:"linestring"});
vectorLayer.addFeatures(format.read(encoded));
map.addLayer(vectorLayer);
The way the code is written currently works. It loads the WMS maps, shows the polyline, and centers the map correctly. But that isn't what I want, I want the OSM maps loaded. So if I change this line:
map.addLayer(wms);
to this:
map.addLayer(osm);
The osm maps load fine, but the polyline is not shown. I've played with this for a very long time and can't seem to get this working. Does it have something to do with projections? Thanks!
What you need to do is change
vectorLayer.addFeatures(format.read(encoded));
to the following
vectorLayer.addFeatures(new OpenLayers.Feature.Vector(format.read(encoded).geometry.transform('EPSG:4326', 'EPSG:3857')));
I had exactly the same trouble and thats how I solved it.