How to move a marker in an OpenLayers.Layer.Marker

2019-02-25 11:49发布

问题:

How can I programmatically move an existing marker on an OpenLayers.Layer.Markers layer? I can't seem to find a proper way.

Is this supported at all? Or do I have to use the Vector layer?

The marker.moveTo() function doesn't work for me, I have the coordinate in lat/lon.

回答1:

marker.moveTo() is not "official" APIMethod. It's used internally by other methods in OpenLayers and you are actually discouraged to use methods that are not marked as "APIMethod".

Wouldn't removing and adding marker on new position fulfill your requirement? There are removeMarker() and addMarker() APIMethods for that.

If not, I would consider using Vector layer as it's much more flexible in terms om rendering and manipulation features.



回答2:

if you have lon/lat for the new point then marker could be moved as:

var newLonLat = new OpenLayers.LonLat(lon, lat);
var newPx = map.getLayerPxFromLonLat(newLonLat);
myMarker.moveTo(newPx);


回答3:

This is not a fully working example demonstrating moving marker on click event

coffeescript:

projection_4326 = new OpenLayers.Projection("EPSG:4326") #Transform from WGS 1984
projection_900913 = new OpenLayers.Projection("EPSG:900913") # Spherical Mercator Projection
markers = new OpenLayers.Layer.Markers( "Markers")
marker = new OpenLayers.Marker(new OpenLayers.LonLat(0,0).transform(projection_4326, projection_900913), icon)
markers.addMarker(marker)
map = new OpenLayers.Map(...init...stuff)
map.addLayers([markers])
map.events.register "click", map, (e) ->
            opx = map.getLayerPxFromViewPortPx(e.xy)
            lonLat = map.getLonLatFromPixel(e.xy)
            # now, if your coordinates are in EPSG:4326 you would have to convert the lonLat here
            #new_position = marker.lonlat.transform(projection_4326, projection_900913)
            marker.map = map
            marker.moveTo(opx) #or new_position


标签: openlayers