Thursday 14 September 2017

How to automatically transform between base layer and vector layer in OpenLayers


I have a simple example on http://jsfiddle.net/29bsw/


I have a map with an OSM layer as base layer and an additional vector layer. The projection of the map is defined as EPSG:900913 and the projection of the vector layer is defined as EPSG:4326:


//Map
var map = new OpenLayers.Map("map", {
projection: new OpenLayers.Projection("EPSG:900913")
});

//Base Layer

var osm = new OpenLayers.Layer.OSM();
map.addLayer(osm);

//Vector Layer
var vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry", {
projection: new OpenLayers.Projection("EPSG:4326")
});
map.addLayer(vectorLayer);

Now I would like to add some features to the vector layer without transforming any geometry point from EPSG:4326 to EPSG:900913. The point should be lie in Hamburg, Germany, but without transforming (see commented on line 21 in the example) the point lies near by Africa.



Because I specified the projection of the map and of the vector layer, is there any way that OpenLayers transform the point from EPSG:4326 to EPSG:900913 automatically?



Answer



Updated JSFiddle


The trick is to use preFeatureInsert inside your Vector Layer constructor:


preFeatureInsert: function(feature) {
feature.geometry.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"))
}

My earlier comment was incorrect in that I had mistyped what projection the OSM was built in. When I was retyping the edit, I realized a possible answer would be to simply use this parameter.


Essentially, this will take the input data as 4326 and transform it to 900913 for the entire vector layer before adding the data to the map.



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...