I am using Openlayers.Layer
and OpenLayers.Marker
to display a marker on the map.
It is positioned correctly and I can successfuly show it and hide it doing:
marker.display(boolean);
But I try to change its position before displaying it but with no success. I already tried this:
var projections = {
g: new OpenLayers.Projection("EPSG:4326"),
p: new OpenLayers.Projection("EPSG:900913")
};
var newlonlat = new OpenLayers.LonLat(newlon, newlat).transform(projections.g, projections.p);
marker.lonlat = newlonlat
layer.redraw();
(no errors triggered but position does not change)
and also tried this:
var px = map.getPixelFromLonLat(newlonlat);
marker.moveTo(px);
layer.redraw();
(it throws an error inside getPixelFromLonLat
function. Error: c is null
)
Why can't I move markers dynamically and what is the best way to do it?
Maybe the problem resides in my position projection transformation when using second option:
new OpenLayers.LonLat(newlon, newlat).transform(projections.g, projections.p);
So, going deeper I found that marker.map
property was null
, so after its initialization I did:
var marker = new OpenLayers.Marker(lonlat, icon);
marker.map = map;
where map is an OpenLayers.Map
object and now its working fine. Don't know why but it fixed it.
To workaround the problem I did:
marker.lonlat = new OpenLayers.LonLat(newlon, newlat);
layer.removeMarker(marker);
layer.addMarker(marker);
layer.redraw();
It seems stupid removing and adding the same marker to just update its position but it works. It may be slower when doing this to a large group of markers though.