我正在使用 Openlayers.Layer
和 OpenLayers.Marker
在 map 上显示标记。
它的位置正确,我可以成功地显示和隐藏它:
marker.display(boolean);
但我尝试在显示它之前改变它的位置,但没有成功。我已经试过了:
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();
(没有触发错误但位置没有改变)
也试过这个:
var px = map.getPixelFromLonLat(newlonlat);
marker.moveTo(px);
layer.redraw();
(它在 getPixelFromLonLat
函数中抛出错误。错误:c 为 null
)
为什么我不能动态移动标记,最好的方法是什么?
编辑:
也许问题出在我使用第二个选项时的位置投影转换:
new OpenLayers.LonLat(newlon, newlat).transform(projections.g, projections.p);
编辑2
所以,深入我发现 marker.map
属性是 null
,所以在它初始化之后我做了:
var marker = new OpenLayers.Marker(lonlat, icon);
marker.map = map;
其中 map 是一个 OpenLayers.Map
对象,现在可以正常工作了。不知道为什么,但它修复了它。
最佳答案
marker.moveTo 适合我:
var px = map.getPixelFromLonLat(new OpenLayers.LonLat(newLon,newLat));
marker.moveTo(px);
希望这有帮助:-)
关于javascript - 动态移动标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18537555/