Question

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?

Edit:

Maybe the problem resides in my position projection transformation when using second option: new OpenLayers.LonLat(newlon, newlat).transform(projections.g, projections.p);

Edit 2

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

marker.moveTo works fine for me:

 var px = map.getPixelFromLonLat(new OpenLayers.LonLat(newLon,newLat));
 marker.moveTo(px);

Hope this helps :-)

Try:

marker.lonlat = new OpenLayers.LonLat(newlon, newlat);
layer.drawMarker(marker);

(not testet)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top