user1297988
user1297988

Reputation: 31

How to make pushpin draggable over the map in bingmap wpf

I am working on bingmap wpf. I have created pushpins on click event of mouse. Now I need to make it draggable and track the coordinate as per the pushpin location. Anybody has any idea on how to make the pushpin draggable and in which function we need to write code to update when it is released.

Thank you very much in advance

Upvotes: 3

Views: 1688

Answers (2)

Amir Gasmi
Amir Gasmi

Reputation: 29

solution by Peter Wone works but needs a small fix. Either nullify the SelectedPushpin or make _drag = false when MouseButtonState.Pressed = False. Complete solution:

Vector _mouseToMarker;
private bool _dragPin;
public Pushpin SelectedPushpin { get; set; }
private void pin_MouseDown(object sender, MouseButtonEventArgs e)
{
    e.Handled = true;
    SelectedPushpin = sender as Pushpin;
    _dragPin = true;
    _mouseToMarker = System.Windows.Point.Subtract(myMap.LocationToViewportPoint(SelectedPushpin.Location), e.GetPosition(myMap));
    
}
private void map_MouseMove(object sender, MouseEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        if (_dragPin && SelectedPushpin != null)
        {
            SelectedPushpin.Location =myMap.ViewportPointToLocation(
              System.Windows.Point.Add(e.GetPosition(myMap), _mouseToMarker));
            e.Handled = true;
            
        }
    }
    else
    { _dragPin = false; }
    
}

The solution works like this:

  1. You attach an event to MouseDown event of all pushpins so when you press on mouse while over the pushpin selectedpushpin is assigned this pushpin which is then used in the next step for moving it.
  2. use the identified pushpin in MouseMove event of the map component to move it to next location as long as the mouseleftbutton is continuously pressed then use the dragpin flag to nullify the selectedpushpin when the mouse is pressed away from pushpin does not continously drag the previously selected pushpin.

Upvotes: 1

Peter Wone
Peter Wone

Reputation: 18765

Vector _mouseToMarker;
private bool _dragPin;
public Pushpin SelectedPushpin { get; set; }

void pin_MouseDown(object sender, MouseButtonEventArgs e)
{
  e.Handled = true;
  SelectedPushpin = sender as Pushpin;
  _dragPin = true;
  _mouseToMarker = Point.Subtract(
    map.LocationToViewportPoint(SelectedPushpin.Location), 
    e.GetPosition(map));
}

private void map_MouseMove(object sender, MouseEventArgs e)
{
  if (e.LeftButton == MouseButtonState.Pressed)
  {
    if (_dragPin && SelectedPushpin != null)
    {
      SelectedPushpin.Location = map.ViewportPointToLocation(
        Point.Add(e.GetPosition(map), _mouseToMarker));
      e.Handled = true;
    }
  }
}

Upvotes: 6

Related Questions