Friday, 29 December 2017

javascript - How to overlay lat/lon points on a Google layer in OpenLayers 2?


I'm stuck adding a vector point in lat/lon on top of a Google layer in OpenLayers. The point is moving when I pan the map. This doesn't happen if I replace the Google layer with a layer in WGS84. How can I fix this?


map = new OpenLayers.Map('map');
map.addControl(new OpenLayers.Control.LayerSwitcher());

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

var pointLayer = new OpenLayers.Layer.Vector("Point Layer");

map.addLayers([gmap,pointLayer]);
map.setCenter(new OpenLayers.LonLat(16.373056, 48.208333), 5);

var point = new OpenLayers.Geometry.Point(16.373056, 48.208333);
var pointFeature = new OpenLayers.Feature.Vector(point,null,null);
pointLayer.addFeatures([pointFeature]);

I've tried to follow http://docs.openlayers.org/library/spherical_mercator.html but without success.




Answer



You need to add a few changes to get the required results:



  1. Add the sphericalMercator: true property to your Google layer so vector layers are shown correctly on top of your Google base layer (this is the reason for the shifting geometry).

  2. Add in the maxExtent property of your Google layer, otherwise the centre of the map will not be set correctly. The extent shown below is the extent of the world in Mercator coordinates.

  3. As user1795 stated your point geometry has to be reprojected from 4326 to Web Mercator to appear correctly on the map.

  4. This also applies to the setCenter LonLat so you need to transform this too.


Working code below:


            map = new OpenLayers.Map('map');

map.addControl(new OpenLayers.Control.LayerSwitcher());

var proj = new OpenLayers.Projection("EPSG:4326");

var gmap = new OpenLayers.Layer.Google("Google Streets", {
sphericalMercator: true,
'maxExtent': new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34)
});
var pointLayer = new OpenLayers.Layer.Vector("Point Layer");


map.addLayers([gmap, pointLayer]);
var lonlat = new OpenLayers.LonLat(16.373056, 48.208333);
lonlat.transform(proj, map.getProjectionObject());
map.setCenter(lonlat, 5);

var point = new OpenLayers.Geometry.Point(16.373056, 48.208333);
point = point.transform(proj, map.getProjectionObject());
//console.log(point);
var pointFeature = new OpenLayers.Feature.Vector(point, null, null);
pointLayer.addFeatures([pointFeature]);

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...