Correctly anchoring pushpins to the map

I regularly come across developers who run into issue that when they zoom the map in and out the pushpin appears to drift to and from the coordinate in which is meant to represent. The reason for this is that most of the time the information for how to offset the pushpin relative to the coordinate is the top left corner of the pushpin image or control.

Correcting this in Bing Maps V7

This is a fairly easy issue to resolve. In the Bing Maps v7 control the default anchor point for a pushpin is 12px to the left and 36px up. For example:

PushpinAnchor

If you are using a custom pushpin with the Bing Maps v7 map control you can specify the width, height and an anchor offset value as options when creating the pushpin. If you don’t set the width and height values and your image is larger than the default pushpin icon it will be clipped. The following code shows how can set the anchor property of the pushpin to offset it such that the tip of the pushpin aligns with the coordinate on the map.

 var pushpin = new Microsoft.Maps.Pushpin(map.getCenter(), {
    icon: 'url to image', 
    width: 24, 
    height: 36, 
    anchor: new Microsoft.Maps.Point(12, 36)
});

Here are a few other pushpin images and examples of the width, height and anchor offset x & y values that can be used to properly position the pushpin.

BluePin

redPin

orangePin

width: 35px height: 35px x: 12px y: 12px

 

width: 18px height: 30px x: 3px y: 30px

 

width: 30px height: 30px x: 3px y: 30px

 

 

 

Correcting this in XAML based Bing Maps controls

In the XAML Bing Maps controls the easiest way to offset a pushpin or custom UIElement that is being overlaid on the map like a pushpin is to specify a negative margin value on the pushpin or UIElement. This will pull the pushpin over so that it aligns with the point that we want to align with the coordinate on the map. The following is an example of how you might create a circle pushpin and have it centered overtop of a coordinate.

 var pushpin = new Canvas()
{
    Width = 35,
    Height = 35,
    Margin = new Thickness(-12, -12, 0, 0)
};

pushpin.Children.Add(new Ellipse()
{
    Fill = new SolidColorBrush(Colors.Blue),
    Stroke = new SolidColorBrush(Colors.White),
    StrokeThickness = 5,
    Width = 35,
    Height = 35
});

MapLayer.SetPosition(pushpin, new Location(45, -110));