XML在地图上插入Pins

时间:2012-07-10 11:35:42

标签: windows-phone-7 bing-maps

我可以将列表中的Lat和Long列为完整字符串。我现在需要能够在地图中使用它。

以下是显示地图的代码。目前它显示两个引脚和位置。 (XAML)

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; }
    }

编辑: 我试图在bing地图上得到所有的停止。我可以在列表中获取所有位置,这将填充到列表框中。这一切都有效。

现在正试图将所有这些位置都放到地图上,同时也使用名称。

所以我需要在网站上做什么 - 但是在电话上 - http://www.buses.co.uk/travel/live-bus-times.aspx

2 个答案:

答案 0 :(得分:0)

我不太确定你的问题是什么,但我认为你对图钉的绑定不起作用?

您已在ObservableCollection上实现了INotifyPropertyChanged。这不是必要的。要使其工作,您必须在PinModel上实现它,并在设置Location属性时调用RaisePropertyChanged方法。

您的PinModel类应该类似于下面的内容,以使您的绑定工作(尽管您的绑定现在可能正常工作,因为您将它绑定为一次。)

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));
        }
    } 

} 

另请注意,het .Single()方法对linq查询的调用返回单个值而不是列表。请查看Lance关于如何构建linq查询的答案。 (有关.Single()文档,请参阅此link

答案 1 :(得分: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() 
                             }); 
相关问题