Windows phone 8 study notes (8) location map navigation

Source: Internet
Author: User
Document directory
  • 1. Get the current location immediately
  • 2. Continuous tracking location information
  • 3. Continuous tracking in the background
  • 1. Introduce map controls
  • 2. Set the drawing mode
  • 3. Set the color mode
  • 4. specify the location of the new view
  • 5. Locate my location and Mark
  • 6. Get the route

Windows phone 8 does not use its own bing map. The new map control can specify the drawing mode and view. The positioning error of bing Maps is relatively large, and it seems ideal to test the new map in the simulator. This section describes how to use the location service and new map controls.

Quick Navigation:
I. Positioning Service
2. Map and navigation

I. Positioning Service

The mobile phone location service can be used to develop applications that utilize the geographical location of mobile phones. We can use apps to monitor mobile phone movements and use maps for navigation. The location service can promptly obtain the geographical location of the mobile phone, continuously track mobile phone movements, and run in the background.

1. Get the current location immediately

We can get the current location through an operation. The following Code demonstrates the implementation method.

[C #]

private async void OneShotLocation_Click (object sender, RoutedEventArgs e)
  {
      // Geographic access service
      Geolocator geolocator = new Geolocator ();
      // definition accuracy in meters
      geolocator.DesiredAccuracyInMeters = 1;

      try
      {
          // Start getting the latitude and longitude of the current position
          Geoposition geoposition = await geolocator.GetGeopositionAsync ();
          LatitudeTextBlock.Text = "Longitude:" + geoposition.Coordinate.Latitude.ToString ("0.00");
          LongitudeTextBlock.Text = "Latitude:" + geoposition.Coordinate.Longitude.ToString ("0.00");
      }
      catch (Exception ex)
      {
          if ((uint) ex.HResult == 0x80004004)
          {
              StatusTextBlock.Text = "Location settings have turned off location services.";
          }

      }
  }

 

2. Continuous tracking location information

If you enable continuous tracking of the mobile phone location, when the mobile phone distance exceeds the set distance, the location change event will be triggered. At this time, we can use the environment information to calculate the mobile phone's action track, speed direction. The following shows how to keep track.

[C #]

Geolocator geolocator = null;
bool tracking = false;

private void TrackLocation_Click (object sender, RoutedEventArgs e)
{

    if (! tracking)
    {
        // Geographic access service
        geolocator = new Geolocator ();
        // precision level
        geolocator.DesiredAccuracy = PositionAccuracy.High;
        // How many meters exceeds to trigger a position change event
        geolocator.MovementThreshold = 100;

        // When the function status changes
        geolocator.StatusChanged + = geolocator_StatusChanged;
        // When the position changes
        geolocator.PositionChanged + = geolocator_PositionChanged;

        tracking = true;
        TrackLocationButton.Content = "Stop tracking";
    }
    else
    {
        geolocator.PositionChanged-= geolocator_PositionChanged;
        geolocator.StatusChanged-= geolocator_StatusChanged;
        geolocator = null;

        tracking = false;
        TrackLocationButton.Content = "Tracking Location";
        StatusTextBlock.Text = "Stop";
    }
}

void geolocator_StatusChanged (Geolocator sender, StatusChangedEventArgs args)
{
    string status = "";

    switch (args.Status)
    {
        case PositionStatus.Disabled:
            status = "Location service settings are disabled";
            break;
        case PositionStatus.Initializing:
            status = "Initializing";
            break;
        case PositionStatus.NoData:
            status = "no data";
            break;
        case PositionStatus.Ready:
            status = "ready";
            break;
        case PositionStatus.NotAvailable:
            status = "unavailable";
            break;
        case PositionStatus.NotInitialized:
            break;
    }
    Dispatcher.BeginInvoke (() =>
    {
        StatusTextBlock.Text = status;
    });
}

void geolocator_PositionChanged (Geolocator sender, PositionChangedEventArgs args)
{
    Dispatcher.BeginInvoke (() =>
    {
        LatitudeTextBlock.Text = "Longitude:" + args.Position.Coordinate.Latitude.ToString ("0.00");
        LongitudeTextBlock.Text = "Latitude:" + args.Position.Coordinate.Longitude.ToString ("0.00");
    });
}

 

3. Continuous tracking in the background

Location tracking can be used as a service in the background. At this time, we do not need to update the UI. To make our application run as a service, we need to right-click to open the configuration file, select the XML text editor to replace the DefaultTask node with the following information:

[XML]

  <DefaultTask Name="_default" NavigationPage="MainPage.xaml">
        <BackgroundExecution>
          <ExecutionType  Name="LocationTracking" />
        </BackgroundExecution>
      </DefaultTask>

Then we need to register the RunningInBackground event and open App. xaml to add the event Application_RunningInBackground. The Code is as follows:

[XAML]

<!-Objects needed to handle application lifetime events->
         <shell: PhoneApplicationService
             Launching = "Application_Launching" Closing = "Application_Closing"
             Activated = "Application_Activated" Deactivated = "Application_Deactivated"
             RunningInBackground = "Application_RunningInBackground" />

In App. xaml. cs, add static variables RunningInBackground and Geolocator. When Application_RunningInBackground event, RunningInBackground is true, and when Application_Activated event, RunningInBackground is false. The Code is as follows:

[C #]

// Determine if the application is running in the background
public static bool RunningInBackground {get; set;}
// Provide access to the current geographic location
public static Geolocator Geolocator {get; set;}

// Code executed when the application is activated (in the foreground)
// This code is not executed when the application is first launched
private void Application_Activated (object sender, ActivatedEventArgs e)
{
     RunningInBackground = false;
}

private void Application_RunningInBackground (object sender, RunningInBackgroundEventArgs args)
{
     RunningInBackground = true;
} 

Add the following code to mainpage:

[C #]

protected override void OnNavigatedTo (System.Windows.Navigation.NavigationEventArgs e)
{
    if (App.Geolocator == null)
    {
        App.Geolocator = new Geolocator ();
        App.Geolocator.DesiredAccuracy = PositionAccuracy.High;
        App.Geolocator.MovementThreshold = 100;
        App.Geolocator.PositionChanged + = geolocator_PositionChanged;
    }
}

void geolocator_PositionChanged (Geolocator sender, PositionChangedEventArgs args)
{
    if (! App.RunningInBackground)
    {
        Dispatcher.BeginInvoke (() =>
        {
            LatitudeTextBlock.Text = "Longitude:" + args.Position.Coordinate.Latitude.ToString ("0.00");
            LongitudeTextBlock.Text = "Latitude:" + args.Position.Coordinate.Longitude.ToString ("0.00");
        });
    }
    else
    {
        Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast ();
        toast.Content = args.Position.Coordinate.Latitude.ToString ("0.00") + "," + args.Position.Coordinate.Longitude.ToString ("0.00");
        toast.Title = "Position:";
        toast.NavigationUri = new Uri ("/ Page1.xaml", UriKind.Relative);
        toast.Show ();

    }
}

 

2. Map and navigation

To use the new map control, you must first register and register the ID on phone: PhoneApplicationPage.

[XAML]

xmlns:maps="clr-namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps"    
1. Introduce map controls

Add the following code to XAML to introduce the control. We can see that the Center refers to the longitude and latitude of the current Map Center. ZoomLevel refers to the zoom level. The LandmarksEnabled attribute is set to true to display the landmark on the Map control. PedestrianFeaturesEnabled is set to true to display the Pedestrian Street structure.

[XAML]

<!-ContentPanel-place additional content here->
         <Grid x: Name = "ContentPanel" Grid.Row = "1" Margin = "12,0,12,0">
             <!-Map controls->
             <maps: Map x: Name = "MyMap" Center = "30.5473, 114.2922" ZoomLevel = "10" LandmarksEnabled = "true" PedestrianFeaturesEnabled = "true" />
             <Button Foreground = "Red" Content = "specified position" HorizontalAlignment = "Left" Margin = "295,530,0,0" VerticalAlignment = "Top" Click = "Button_Click_1" Width = "151" />
             <Button Foreground = "Red" Content = "drawing mode" HorizontalAlignment = "Left" Margin = "10,530,0,0" VerticalAlignment = "Top" Click = "Button_Click_2" />
             <Button Foreground = "Red" Content = "color mode" HorizontalAlignment = "Left" Margin = "134,530,0,0" VerticalAlignment = "Top" Click = "Button_Click_3" />
             <Button Foreground = "Red" Content = "My Position" HorizontalAlignment = "Left" Margin = "10,602,0,0" VerticalAlignment = "Top" Click = "Button_Click_4" />
         </ Grid>

 

2. Set the drawing mode

There are four options in the drawing mode:
Road:The default two-dimensional map is displayed normally.
Aerial:The aerial test chart is displayed.

Hybrid:Displays the aerial test view of the map that overlaps roads and labels.

Terrain:Displays natural terrain images for the displayed highlands and Waters (such as mountains and rivers.

Next let's take a look at how to switch.

[C #]

// Toggle drawing mode
private void Button_Click_2 (object sender, RoutedEventArgs e)
{
     switch (MyMap.CartographicMode)
     {
         case MapCartographicMode.Aerial:
             MyMap.CartographicMode = MapCartographicMode.Hybrid;
             break;
         case MapCartographicMode.Hybrid:
             MyMap.CartographicMode = MapCartographicMode.Road;
             break;
         case MapCartographicMode.Road:
             MyMap.CartographicMode = MapCartographicMode.Terrain;
             break;
         case MapCartographicMode.Terrain:
             MyMap.CartographicMode = MapCartographicMode.Aerial;
             break;
     }
}

 

3. Set the color mode

Color is divided into two types: bright and dark. Let's see how to implement it.

[C #]

// Switch color mode
private void Button_Click_3 (object sender, RoutedEventArgs e)
{
     if (MyMap.ColorMode == MapColorMode.Light)
         MyMap.ColorMode = MapColorMode.Dark;
     else MyMap.ColorMode = MapColorMode.Light;
}

 

4. specify the location of the new view

We can switch the Angle of View to the new latitude and longitude through programming, and specify the transition effect during the switchover. Here we specify the parabolic method.

[C #]

private void Button_Click_1 (object sender, RoutedEventArgs e)
{
     // In a parabolic way, position the perspective over the central lake of the Optics Valley Software Park.
     MyMap.SetView (new GeoCoordinate (30.476724, 114.406563), 16, MapAnimationKind.Parabolic);
}

 

5. Locate my location and Mark

Locate the map to my current location. In this case, you need to use the positioning function to find instances of different longitude and latitude types. You need to make a conversion in advance. The conversion class CoordinateConverter is as follows.

[C #]

public static class CoordinateConverter
{
     /// <summary>
     /// Convert the positioning position to the map position
     /// </ summary>
     /// <param name = "geocoordinate"> </ param>
     /// <returns> </ returns>
     public static GeoCoordinate ConvertGeocoordinate (Geocoordinate geocoordinate)
     {
         return new GeoCoordinate
             (
             geocoordinate.Latitude,
             geocoordinate.Longitude,
             geocoordinate.Altitude ?? Double.NaN,
             geocoordinate.Accuracy,
             geocoordinate.AltitudeAccuracy ?? Double.NaN,
             geocoordinate.Speed ?? Double.NaN,
             geocoordinate.Heading ?? Double.NaN
             );
     }
}

Then, we need to draw a small square on the map to mark my current position and locate the map here.

[C #]

// Add other controls to the map to identify my current location
private async void Button_Click_4 (object sender, RoutedEventArgs e)
{
    // Get my geographic location
    Geolocator myGeolocator = new Geolocator ();
    // precision
    myGeolocator.DesiredAccuracyInMeters = 1;
    Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync ();
    Geocoordinate myGeocoordinate = myGeoposition.Coordinate;
    // Convert latitude and longitude GeoCoordinate
    GeoCoordinate myGeoCoordinate = CoordinateConverter.ConvertGeocoordinate (myGeocoordinate);

    //MessageBox.Show (myGeoCoordinate.ToString ());

    // Locate the map to my location
    MyMap.SetView (myGeoCoordinate, 16, MapAnimationKind.Parabolic);

    // Draw a square and render it on my current location on the map
    Rectangle MyRectangle = new Rectangle ();
    MyRectangle.Fill = new SolidColorBrush (Colors.Black);
    MyRectangle.Height = 20;
    MyRectangle.Width = 20;

    MapOverlay MyOverlay = new MapOverlay ();
    MyOverlay.Content = MyRectangle;
    MyOverlay.GeoCoordinate = myGeoCoordinate;
    MyOverlay.PositionOrigin = new Point (0, 0.5);

    MapLayer MyLayer = new MapLayer ();
    MyLayer.Add (MyOverlay);
    MyMap.Layers.Add (MyLayer);

}

 

6. Get the route

We can also implement navigation through positioning and map. The following shows how to drive from my current location (Optics Valley software park) to the specified location (Optics Valley venture Street.

[XAML]

<phone: PhoneApplicationPage.Resources>
        <DataTemplate x: Key = "RouteListTemplate">
            <TextBlock Text = "{Binding}" FontSize = "{StaticResource PhoneFontSizeMedium}" Margin = "5,5,0,0" />
        </ DataTemplate>
    </phone:PhoneApplicationPage.Resources>
    <!-LayoutRoot is the root grid containing all page content->
        <Grid x: Name = "LayoutRoot" Background = "Transparent">
            <Grid.RowDefinitions>
                <RowDefinition Height = "auto" />
                <RowDefinition Height = "*" />
                <RowDefinition Height = "auto" />
                <RowDefinition Height = "*" />
            </Grid.RowDefinitions>
            <TextBlock Text = "Map Navigation" Grid.Row = "0" FontSize = "{StaticResource PhoneFontSizeLarge}" Margin = "0,0,0,20" />
            <maps: Map x: Name = "MyMap" Grid.Row = "1" Center = "30.476724, 114.406563" ZoomLevel = "13" />
            <TextBlock Text = "Driving directions" Grid.Row = "2" FontSize = "{StaticResource PhoneFontSizeLarge}" Margin = "0,10,0,20" />
            <phone: LongListSelector x: Name = "RouteLLS" Grid.Row = "3" Background = "Transparent" ItemTemplate = "{StaticResource RouteListTemplate}" LayoutMode = "List"
      IsGroupingEnabled = "False" />
    </ Grid>

 

[C #]

public partial class Page1: PhoneApplicationPage
    {
        public Page1 ()
        {
            InitializeComponent ();
            this.GetCoordinates ();
        }

        RouteQuery MyQuery = null;
        GeocodeQuery Mygeocodequery = null;

        List <GeoCoordinate> MyCoordinates = new List <GeoCoordinate> ();

        private async void GetCoordinates ()
        {
            Geolocator MyGeolocator = new Geolocator ();
            MyGeolocator.DesiredAccuracyInMeters = 5;
            Geoposition MyGeoPosition = null;
            try
            {
                MyGeoPosition = await MyGeolocator.GetGeopositionAsync (TimeSpan.FromMinutes (1), TimeSpan.FromSeconds (10));
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show ("Location settings are turned off for system settings.");
            }
            catch (Exception ex)
            {
            }
            MyCoordinates.Add (new GeoCoordinate (MyGeoPosition.Coordinate.Latitude, MyGeoPosition.Coordinate.Longitude));



            Mygeocodequery = new GeocodeQuery ();
            Mygeocodequery.SearchTerm = "Optical Valley Venture Street";
            Mygeocodequery.GeoCoordinate = new GeoCoordinate (MyGeoPosition.Coordinate.Latitude, MyGeoPosition.Coordinate.Longitude);

            Mygeocodequery.QueryCompleted + = Mygeocodequery_QueryCompleted;
            Mygeocodequery.QueryAsync ();


        }
        void Mygeocodequery_QueryCompleted (object sender, QueryCompletedEventArgs <IList <MapLocation >> e)
        {
            if (e.Error == null)
            {
                MyQuery = new RouteQuery ();
                MyCoordinates.Add (e.Result [0] .GeoCoordinate);
                MyQuery.Waypoints = MyCoordinates;
                MyQuery.QueryCompleted + = MyQuery_QueryCompleted;
                MyQuery.QueryAsync ();
                Mygeocodequery.Dispose ();
            }
        }

        void MyQuery_QueryCompleted (object sender, QueryCompletedEventArgs <Route> e)
        {
            if (e.Error == null)
            {
                // Get specific itinerary
                Route MyRoute = e.Result;
                MapRoute MyMapRoute = new MapRoute (MyRoute);
                MyMap.AddRoute (MyMapRoute);
                List <string> RouteList = new List <string> ();
                foreach (RouteLeg leg in MyRoute.Legs)
                {
                    foreach (RouteManeuver maneuver in leg.Maneuvers)
                    {
                        RouteList.Add (maneuver.InstructionText);
                    }
                }

                RouteLLS.ItemsSource = RouteList;
                MyQuery.Dispose ();
            }
        }

    } 

 

Author: [Lipan]
Source: [http://www.cnblogs.com/lipan/]
Copyright: The copyright of this article is shared by the author and the blog. The source and author of the original text must be indicated during reprinting, and the original text point-to-type link must be retained. The original content cannot be changed. Otherwise, the author will be held legally liable. Previous Article: Windows phone 8 Study Notes
Series directory
Next article: Windows phone 8 learning notes Integration
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.