如何在OSMSharp中使MapMarker可拖动

时间:2016-08-23 12:15:53

标签: c# android xamarin openstreetmap

我正在使用OSMSharp将标记添加到MapView

MapView mapView = new MapView(this, new MapViewSurface(this));

//add map layer
var map = new Map();
map.AddLayer(new LayerMBTile(OsmSharp.Android.UI.Data.SQLite.SQLiteConnection.CreateFrom(
        Assembly.GetExecutingAssembly().GetManifestResourceStream(selectedMap), "map")));
mapView.Map = map;

//add marker
MapMarker marker = new MapMarker(this, coordinate, 
         MapControlAlignmentType.CenterBottom, this.Resources, Resource.Drawable.marker);
mapView.AddMarker(marker);

如何将标记设置为可拖动,以便用户可以重新定位它们?

https://github.com/OsmSharp/ui/blob/master/OsmSharp.Android.UI/Markers/MapMarker.cs https://github.com/OsmSharp/ui/blob/master/OsmSharp.Android.UI/Controls/MapControl.cs

1 个答案:

答案 0 :(得分:0)

这是如何使地图标记可拖动。 在MapMarker.cs中添加这个......

//during initialise
this.View.LongClick += View_LongClick;
this.Oid = Guid.NewGuid();
...

void View_LongClick(object sender, View.LongClickEventArgs e)
{
    //pass in MapMarker Guid
    var data = ClipData.NewPlainText("name", Oid.ToString());

    // Start dragging and pass data
    ((sender) as View).StartDrag(data, new View.DragShadowBuilder(((sender) as View)), null, 0);
}

在MapView.cs中添加这个......

/// <summary>
/// Initialize this instance.
/// </summary>
private void Initialize()
{           
    this.AddView(_mapView as View);
    this.Drag += MapView_Drag;
}

void MapView_Drag(object sender, View.DragEventArgs e)
{
    // React on different dragging events
    var evt = e.Event;
    switch (evt.Action)
    {
        case DragAction.Ended:
        case DragAction.Started:
        case DragAction.Location:
            e.Handled = true;
            break;

        case DragAction.Drop:
            // Try to get clip data
            var data = e.Event.ClipData;
            if (data != null)
            {
                Guid thisOid = new Guid(data.GetItemAt(0).Text);
                //find MapMarker using Guid
                MapMarker marker = _markers.Find(x => x.Oid == thisOid);
                if (marker != null)
                {
                    float xCoord = evt.GetX();
                    float yCoord = evt.GetY() + (marker.Image.Height / 2); //middle of image offset

                    marker.Location = (sender as MapView).PointToCoordinate(Convert.ToSingle(xCoord), Convert.ToSingle(yCoord));
                }
            }
            e.Handled = true;
            break;
    }
}

public GeoCoordinate PointToCoordinate(double PointX, double PointY)
{
    double x, y;
    var fromMatrix = CurrentView.CreateFromViewPort(CurrentWidth, CurrentHeight);
    fromMatrix.Apply(PointX, PointY, out x, out y);

    return this.Map.Projection.ToGeoCoordinates(x, y);
}