Zenya
Zenya

Reputation: 1521

How to reproject a vector layer when you switch between base maps of different projections

I have OpenLayers map with two base layers: MetaCarta (EPSG:4326) and Google map (Mercator). sphericalMercator = false, units are degrees. There are also some markers, boxes, and vector data on the map.

When I switch between the base layers (which are of different projections), the simple geometries (such as markers or boxes) are reprojecting automatically and displayed correctly. However vector layers (polylines) are just shifted, not reprojected. I think that I need to call some kind of "rebuild" function or add some parameter so that OpenLayers do this automatically when the base layer projection changes. But I have no idea how to do this.

I read about Spherical Mercator (http://docs.openlayers.org/library/spherical_mercator.html) and look through OpenLayers examples, but didn't find a solution.

The part of my code is below (all coordinates in vector.json is in degrees):

var metaCarta = new OpenLayers.Layer.WMS("MetaCarta",
    "http://labs.metacarta.com/wms/vmap0?",
    {layers: "basic"}
);

var gmap = new OpenLayers.Layer.Google(
    "Google Streets",
    {numZoomLevels: 40}
);

map.addLayers([metaCarta, gmap]);
map.setCenter(new OpenLayers.LonLat(139.8, 35.7), 11);


// Load vector data
var jsonFormat = new OpenLayers.Format.GeoJSON();

var vectorLayer = new OpenLayers.Layer.Vector("vector", {
    style: {strokeColor: "gray",strokeWidth: 2}
});

OpenLayers.loadURL("vector.json", {}, null, function(response) {
    var features = jsonFormat.read(response.responseText);
    vectorLayer.addFeatures(features);
});

map.addLayer(vectorLayer);

Upvotes: 2

Views: 925

Answers (1)

winwaed
winwaed

Reputation: 7801

You will need to define the projections and a suitable transform in OpenLayers. In turn, you will need to include the Proj4JS library (which is used by OpenLayers to perform these projection transformations)

Upvotes: 1

Related Questions