2011-03-31 59 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中做空間的東西總是凌亂的我的經驗。

希望有所幫助,不要太長時間囉嗦:)