2012-07-10 3 views
0

목록의 위도와 경도를 전체 문자열로 얻을 수 있습니다. 나는 이제 이것을지도에서 사용할 수 있어야합니다.지도상의 XML을

다음은지도를 표시하는 코드입니다. 현재 두 개의 핀과 위치를 표시하고 있습니다. (XAML)을 Heres 코드

phone:PhoneApplicationPage 
x:Class="BrightonHoveBuses.location" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
FontFamily="{StaticResource PhoneFontFamilyNormal}" 
FontSize="{StaticResource PhoneFontSizeNormal}" 
Foreground="{StaticResource PhoneForegroundBrush}" 
SupportedOrientations="Portrait" Orientation="Portrait" 
mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480" 
shell:SystemTray.IsVisible="True" xmlns:my="clr- 
namespace:Microsoft.Phone.Controls.Maps;assembly=Microsoft.Phone.Controls.Maps"> 
     <phone:PhoneApplicationPage.Resources> 

    <DataTemplate x:Key="PinItemTemplate"> 
     <my:Pushpin Location="{Binding Location}" 
        MouseLeftButtonUp="Pushpin_MouseLeftButtonUp_1" 
        Content="{Binding Id}"> 
     </my:Pushpin> 
    </DataTemplate> 

    <ControlTemplate x:Key="pinMyLoc" 
        TargetType="my:Pushpin"> 
     <Grid Height="26" 
        Width="26" 
        Margin="-13,-13,0,0" 
        RenderTransformOrigin="0.5,0.5"> 
      <Grid.RenderTransform> 
       <CompositeTransform Rotation="-45" /> 
      </Grid.RenderTransform> 
      <Rectangle Fill="Black" 
         HorizontalAlignment="Center"      Margin="0"      Stroke="White"      VerticalAlignment="Center"      Height="26"      Width="26" /> 
      <Ellipse HorizontalAlignment="Center" 
        Height="16" Margin="0" VerticalAlignment="Center" 
        Fill="Teal" 
        Width="16" /> 
     </Grid> 
    </ControlTemplate> 
      <DataTemplate x:Key="BusItemTemplate"> 
      <my:Pushpin Location="{Binding Location}" 
       Name="{Binding Id}" 
       MouseLeftButtonUp="Pushpin_MouseLeftButtonUp_1"> 
    <Grid> 
     <StackPanel Orientation="Horizontal"> 
      <Image Source="/Images/1.png" Stretch="None" Width="20" Height="25"/> 
     </StackPanel> 
    </Grid> 
</my:Pushpin> 
</DataTemplate> 
    <ControlTemplate x:Key="stops" 
        TargetType="my:Pushpin"> 
     <Grid Height="26" 
        Width="26" 
        Margin="-13,-13,0,0" 
        RenderTransformOrigin="0.5,0.5"> 
      <Grid.RenderTransform> 
       <CompositeTransform Rotation="-45" /> 
      </Grid.RenderTransform> 
      <Rectangle Fill="Black" 
         HorizontalAlignment="Center"      Margin="0"      Stroke="White"      VerticalAlignment="Center"      Height="26"      Width="26" /> 
      <Ellipse HorizontalAlignment="Center" 
        Height="16" Margin="0" VerticalAlignment="Center" 
        Fill="Yellow" 
        Width="16" /> 
     </Grid> 
    </ControlTemplate> 
    </phone:PhoneApplicationPage.Resources> 

<!--LayoutRoot is the root grid where all page content is placed--> 
<Grid x:Name="LayoutRoot" Background="Transparent"> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="Auto"/> 
     <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 


    <!--TitlePanel contains the name of the application and page title--> 
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> 
     <TextBlock x:Name="ApplicationTitle" Text="BRIGHTON &amp; HOVE BUSES" Style="{StaticResource PhoneTextNormalStyle}"/> 
     <TextBlock x:Name="PageTitle" Text="Stop Map" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> 
    </StackPanel> 

    <!--ContentPanel - place additional content here--> 
    <!-- This is the coding for the pushpins on the map--> 
    <Grid Grid.RowSpan="2"> 
     <my:Map Name="map1" CredentialsProvider="Apg4fepCyTYEAQ0UxPKpbIljr_THidmUi7BNRth0JGtGSE0blId5FJSJqYy80kQC" Center="47.620574,-122.34942" Margin="0,139,6,99" Height="458" ZoomLevel="17" LogoVisibility="Visible" CopyrightVisibility="Visible" Loaded="startLocationButton_Click"> 
      <my:Pushpin Location="{Binding CurrentLocation}" Template="{StaticResource pinMyLoc}" Name="myPushPin"/> 
      <my:MapItemsControl x:Name="MapPins" 
      ItemsSource="{Binding Pins}" 
      ItemTemplate="{StaticResource PinItemTemplate}" 
      /> 
     </my:Map> 
     <ListBox Height="87" HorizontalAlignment="Left" Margin="12,603,0,0" Name="listBox1" VerticalAlignment="Top" Width="460" > 
         <ListBox.ItemTemplate> 
        <DataTemplate> 
         <StackPanel> 
          <TextBlock Text="{Binding latitude}"/> 
          <TextBlock Text="{Binding NaptanCode}"/> 
          <TextBlock Text=" "/> 
         </StackPanel> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 


     </ListBox> 
    </Grid> 
</Grid> 
<phone:PhoneApplicationPage.ApplicationBar> 
    <shell:ApplicationBar Opacity="1.0" IsMenuEnabled="True" IsVisible="True">   

     <shell:ApplicationBarIconButton Text="Zoom In" IconUri="/Images/add.png" Click="Buttonplus_Click" /> 
     <shell:ApplicationBarIconButton Text="Zoom Out" IconUri="/Images/minus.png" Click="Buttonminus_Click" /> 
     <shell:ApplicationBarIconButton Text="Me" IconUri="/Images/location.png" Click="ButtonLocation_Click" /> 


     <shell:ApplicationBar.MenuItems> 

     <shell:ApplicationBarMenuItem Text="Road View" Click="ApplicationBarRoad_Click" /> 
     <shell:ApplicationBarMenuItem Text="Aerial View" Click="ApplicationBarAerial_Click" /> 

     </shell:ApplicationBar.MenuItems>   


    </shell:ApplicationBar> 

</phone:PhoneApplicationPage.ApplicationBar> 
</phone:PhoneApplicationPage> 

....

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 
using System.Device.Location; 
using Microsoft.Phone.Shell; 
using System.Xml.Serialization; 
using System.Xml; 
using System.IO.IsolatedStorage; 
using Microsoft.Phone.Controls; 
using System.Runtime.Serialization.Json; 
using System.Collections.ObjectModel; 
using System.Runtime.Serialization; 
using System.Text; 
using System.Xml.Linq; 
using System.Data.Linq.Mapping; 
using System.ComponentModel; 
using Microsoft.Phone.Controls.Maps; 
using Microsoft.Phone.Controls.Maps.Platform; 
namespace BrightonHoveBuses 
{ 
public partial class location : PhoneApplicationPage 
{ 


    public location() 
    { 
     InitializeComponent(); 
     DataContext = App.ViewMapModel; 
     MapViewModel view = new MapViewModel(); 
     view.Load(); 
     this.DataContext = view; 

     WebClient client = new WebClient(); 
     client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); 
     Uri url = new Uri("http://www.henry-edwards.co.uk/feed.txt", UriKind.Absolute); 
     client.DownloadStringAsync(url); 

    } 
    GeoCoordinateWatcher watcher; 


    // Click the event handler for the “Start Location” button. 
    private void startLocationButton_Click(object sender, RoutedEventArgs e) 
    { 
     // The watcher variable was previously declared as type GeoCoordinateWatcher. 
     if (watcher == null) 
     { 
      watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // using high accuracy 
      watcher.MovementThreshold = 20; // use MovementThreshold to ignore noise in the signal 

      watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged); 
      watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged); 
     } 


     watcher.Start(); 
    } // End of the Start button Click handler. 





    public class RootContainer 
    { 
     [DataMember] 
     public string StopName { get; set; } 

     [DataMember] 
     public string StopId { get; set; } 

     [DataMember] 
     public string Stop { get; set; } 

     [DataMember] 
     public string RouteId { get; set; } 

     [DataMember] 
     public string RouteName { get; set; } 

     [DataMember] 
     public string latitude { get; set; } 

     [DataMember] 
     public string longitude { get; set; } 

     [DataMember] 
     public List<Location> Location { get; set; } 


    } 





    void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e) 
    { 
     if ((App.Current as App).locsettings == false) 
     { 
      MessageBoxResult m = MessageBox.Show("Do you want to allow this application to use information about your location?", "Use Location", MessageBoxButton.OKCancel); 

      if (m == MessageBoxResult.OK) 
      { 
       watcher.Start(); 
       (App.Current as App).locsettings = true; 
      } 
      else if (m == MessageBoxResult.Cancel) 
      { 
       watcher.Stop(); 
       (App.Current as App).locsettings = false; 
      } 
     } 
     switch (e.Status) 
     { 
      case GeoPositionStatus.Disabled: 
       // The Location Service is disabled or unsupported. 
       // Check to see whether the user has disabled the Location Service. 
       if (watcher.Permission == GeoPositionPermission.Denied) 
       { 
        // The user has disabled the Location Service on their device. 
        MessageBox.Show("Location services must be enabled in your phone settings"); 
       } 
       else 
       { 
        MessageBox.Show("Location services must be enabled"); 
       } 
       break; 

     } 
    } 

    // Click the event handler for the “Start Location” button. 
    private void stopLocationButton_Click(object sender, RoutedEventArgs e) 
    { 
     watcher.Stop(); 
    } 


    private GeoCoordinateWatcher loc = null; 


    public string stopslist; 

    private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e) 
    { 
     myPushPin.Location = e.Position.Location; 
     map1.SetView(myPushPin.Location, 17.0); 
     watcher.MovementThreshold = 100; 
    } 

    void loc_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e) 
    { 
     if (e.Status == GeoPositionStatus.Ready) 
     { 
      map1.SetView(loc.Position.Location, 17.0); 
      loc.Stop(); 

     } 
    } 

    void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
    { 
     if (e.Error == null) 
     { 
      if (e.Result != null) 
      { 
       XDocument doc = XDocument.Parse(e.Result); 
       XNamespace ns = "http://schemas.datacontract.org/2004/07/BusExpress.ClassLibrary"; 
       var locations = (from n in doc.Descendants(ns + "ArrayOfStop") 
           select new RootContainer 
           { 

            Location = (from s in n.Elements(ns + "Stop") 
               select new Location 
               { 
                latitude = s.Element(ns + "Lat").Value + " ," + s.Element(ns + "Long").Value, 
                // longitude = s.Element(ns + "Long").Value, 


               }).ToList() 
           }).Single(); 

       // Do something with the list of Route Names in routeNames 
       listBox1.ItemsSource = locations.Location; 
      } 
     } 
    } 

public class MapViewModel : INotifyPropertyChanged 
{ 
    public void Load() 
    { 

     //Do something here to populate your view collection with pins 

     Pins.Add(new PinModel() { Id = 2, Name = string.Format("Pin # 2"), Location = new GeoCoordinate(39.932825, -75.168396) }); 

    } 

    private ObservableCollection<PinModel> _pins = new ObservableCollection<PinModel>(); 
    public ObservableCollection<PinModel> Pins 
    { 
     get { return _pins; } 
     set { _pins = value; RaisePropertyChanged("Pins"); } 
    } 

    //Event code to ensure the page updates to model changes. 
    public event PropertyChangedEventHandler PropertyChanged; 
    private void RaisePropertyChanged(string propertyName) 
    { 
     if (this.PropertyChanged != null) 
     { 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 

    private void Pushpin_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs e) 
    { 
     Pushpin pin = (Pushpin)sender; 
     MessageBox.Show(pin.Content.ToString()); 
    } 
    public class PinModel 
    { 
     public string Name { get; set; } 
     public int Id { get; set; } 
     public GeoCoordinate Location { get; set; } 
    } 

    } 

    private void ButtonLocation_Click(object sender, EventArgs e) 
    { 
     loc = new GeoCoordinateWatcher(GeoPositionAccuracy.Default); 
     //EventHandler for location service status changes 
     loc.StatusChanged += loc_StatusChanged; 
     //If the location service is disabled or not supported 
     if (loc.Status == GeoPositionStatus.Disabled) 
     { 
      //Display a message 
      MessageBox.Show("Location services must be enabled"); 
      return; 
     } 
     loc.Start(); 
    } 

    private void Pushpin_MouseLeftButtonUp_1(object sender, System.Windows.Input.MouseButtonEventArgs e) 
    { 
     Pushpin pin = (Pushpin)sender; 
    } 

    private void Buttonminus_Click(object sender, EventArgs e) 
    { 
     double zoom; 
     zoom = map1.ZoomLevel; 
     map1.ZoomLevel = --zoom; 

    } 

    private void Buttonplus_Click(object sender, EventArgs e) 
    { 
     double zoom; 
     zoom = map1.ZoomLevel; 
     map1.ZoomLevel = ++zoom; 

    } 

    private void ApplicationBarRoad_Click(object sender, EventArgs e) 
    { 
     map1.Mode = new RoadMode(); 

    } 

    private void ApplicationBarAerial_Click(object sender, EventArgs e) 
    { 
     map1.Mode = new AerialMode(); 

    } 


    } 


    } 

편집 :

public class PinModel : INotifyPropertyChanged 
    { 
     public string Name { get; set; } 
     public int Id { get; set; } 
     public GeoCoordinate Location { get; set; } 
    } 

편집 : 나는 빙지도에있는 모든 정거장을 얻기 위해 노력하고 . 목록의 모든 위치를 가져올 수 있으며 목록 상자에 채워집니다. 이것은 모두 작동합니다.

이제 모든 위치를지도와 이름으로 가져 오려고합니다.

그래서 내가 무슨 웹 사이트에 할 필요 -하지만 전화 - http://www.buses.co.uk/travel/live-bus-times.aspx

+0

무엇이 질문입니까? – ken2k

+0

내 편집 –

+0

을 참조하십시오. 도움이됩니다. http://babaandthepigman.wordpress.com/2010/10/06/databinding-bingmaps-control-wp7-mvvm/ – ken2k

답변

0

나는 당신의 질문이 무엇인지 꽤 잘 모르겠지만, 나는 당신이 푸시 핀이 결합 작동하지 않는 생각?

ObservableCollection에 INotifyPropertyChanged를 구현했습니다. 그럴 필요는 없습니다. 이 기능을 사용하려면 PinModel에 구현해야하며 RaisePropertyChanged 메서드를 호출하는 것보다 Location 속성을 설정할 때 필요합니다.

public class PinModel : INotifyPropertyChanged 
{ 
    public string Name { get; set; } 
    public int Id { get; set; } 
    private GeoCoordinate _location; 
    public GeoCoordinate Location 
    { 
     get 
     { 
      return _location; 
     } 
     set 
     { 
      _location = value; 
      RaisePropertyChanged("Location"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    private void RaisePropertyChanged(string propertyName) 
    { 
     if (this.PropertyChanged != null) 
     { 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 

} 

또한 그 노한주의 (그것은 당신의 당신이 전체적으로 한 번에 결합하기 때문에, 지금 당장 노력하고 바인딩. 가능성이 있습니다 Allthough) 귀하의 바인딩 작업을 아래처럼 보일 것이다 귀하의 PinModel 클래스 .Single() 메서드를 호출하여 linq 쿼리를 호출하면 목록 대신 단일 값이 반환됩니다. Lance에서 linq 쿼리를 작성하는 방법에 대한 답변을 살펴보십시오. (.Single() 설명서는 link을 참조하십시오.)

+0

안녕하세요, 저는 정지 목록을 얻으려고합니다. 위도와 경도는 하나의 목록으로 만들어지며 위도가됩니다. 그런 다음 모든 정거장을지도에 표시하고 싶습니다. pinModel을 변경 했으므로 편집 ... can;을 참조하십시오. RaisePropertyChanged를 넣지 않고 어디에서 볼 수 있습니까? –

+0

오케이, 업데이트했습니다. 그러나 정지 점은 여전히지도에 표시되지 않습니다. –

0

LINQ 메서드의 출력을 확인 했습니까? 목록에 하나의 인스턴스 만 만들고있는 것 같습니다. 현재 구문 분석 방법 대신이 방법을 사용해보십시오.

var locations = (from n in doc.Descendants(ns + "ArrayOfStop") 
          select new RootContainer 
          { 

           Location = (from s in n.Elements(ns + "Stop") 
              select new Location 
              { 
               latitude = s.Element(ns + "Lat").Value + " ," + s.Element(ns + "Long").Value, 
               // longitude = s.Element(ns + "Long").Value, 


              }).ToList() 
          }); 
+0

이 모든 것이 작동하며 위치를 출력합니다. 푸시 핀으로 표시됩니다. –

+0

일어나는 현상은 모든 위치가 ObservableCollection의 단일 항목에 들어간다는 것입니다. 출력 목록 상자에서도 모든 값이 표시되지만 여전히 단일 항목입니다. –

+0

좋아, 어떻게 하나의 항목이 아닌가? –