2011-03-31 60 views

回答

1

如果您只需要多边形的近似中心,则可以找到其边界框的中心并以编程方式在多边形上添加一个TextBlock。

所以这样的事情可能工作:

(XAML)

<MapControl:Map x:Name="MyMap"> 
     <MapControl:Map.Children> 
      <MapControl:MapPolygon Fill="Red" Stroke="Yellow" StrokeThickness="5" Opacity="0.7"> 
       <MapControl:MapPolygon.Locations> 
        <m:LocationCollection> 
         <m:Location>20, -20</m:Location> 
         <m:Location>20, 20</m:Location> 
         <m:Location>-20, 20</m:Location> 
         <m:Location>-20, -20</m:Location> 
        </m:LocationCollection> 
       </MapControl:MapPolygon.Locations> 
      </MapControl:MapPolygon> 
     </MapControl:Map.Children> 
    </MapControl:Map> 

(代码隐藏)

 public partial class MainPage : UserControl 
{ 
    private MapLayer tbLayer; 

    public MainPage() 
    { 
     InitializeComponent(); 

     tbLayer = new MapLayer(); 

     List<TextBlock> newTbs = new List<TextBlock>(); 

     // loop through the maps children and find the polygons 
     foreach (var child in MyMap.Children) 
     { 
      if (child is MapPolygon) 
      { 
       var poly = child as MapPolygon; 

       // get the average lat and long to calculate the "center"-ish of the polygon 
       var avgLat = poly.Locations.Select(l => l.Latitude).Average(); 
       var avgLon = poly.Locations.Select(l => l.Longitude).Average(); 

       TextBlock tb = new TextBlock 
            { 
              Text = "Hey there. I'm a polygon." 
            }; 

       // set the position of the textblock and add it to a new map layer 
       MapLayer.SetPositionOrigin(tb, PositionOrigin.Center); 
       MapLayer.SetPosition(tb, new Location(avgLat, avgLon)); 
       tbLayer.Children.Add(tb); 
      } 
     } 

     // add the new maplayer to the parent map 
     MyMap.Children.Add(tbLayer); 

    } 
} 

如果你的多边形形状奇特,而不是漂亮的像我一般的例子小广场,那么你可能需要变得更肮脏。在这种情况下,您可能需要一个可以计算多边形质心的Web服务(WCF)。我不认为在Silverlight中这是一种简单的方法。

这将是类似如下的过程:

  1. 发送指向一个WCF服务方法。
  2. 加载了一个SqlGeometry对象与你的观点,可能是由形成WKT这些点,并使用SqlGeometry.Parse
  3. 呼叫STCentroid您SqlGeometry对象。
  4. 返回SqlGeometry.STAsText以通过调用STCentroid返回刚获得的点的WKT。

这是一个混乱,但在Silverlight中做空间的东西总是凌乱的我的经验。

希望有所帮助,不要太长时间啰嗦:)