Windows Phone 8 Learning Note (8) Positioning map navigation

Source: Internet
Author: User

Windows Phone 8 does not already use its own Bing maps, and the new map controls can specify cartographic modes, views, and so on. Bing Maps has a large positioning error, and it seems ideal to test the new map in the simulator. This section focuses on the location services and the use of new map controls.

Quick navigation:
First, location services
Second, map and navigation one, location services

Mobile location services can be used to develop mobile phone location applications. We can use the app to monitor the whereabouts of the phone, coordinate with the map can be used for navigation and so on. Location services can be in a timely manner to obtain mobile phone location, but also keep track of mobile phone, can also run in the background. 1. Get the current location now

We can get the current position by one operation, and the following code demonstrates the method of implementation.

[C #]

privateasync void OneShotLocation_Click(object sender, RoutedEventArgs e)

{

//地理位置访问服务

Geolocator geolocator = newGeolocator();

//定义精度,米为单位

geolocator.DesiredAccuracyInMeters = 1;

try

{

//开始获取当前位置的经纬度

Geoposition geoposition = await geolocator.GetGeopositionAsync();

LatitudeTextBlock.Text = "经度:"+ geoposition.Coordinate.Latitude.ToString("0.00");

LongitudeTextBlock.Text = "纬度:"+ geoposition.Coordinate.Longitude.ToString("0.00");

}

catch(Exception ex)

{

if((uint)ex.HResult == 0x80004004)

{

StatusTextBlock.Text = "系统设置关闭了位置服务.";

}

}

}2. Keep track of location information

If you turn on the continuous tracking phone location, when the mobile phone distance beyond the set distance, it will trigger a position change event, this time we can use the environmental information to calculate the mobile phone's action trajectory, speed direction and so on. The following shows how to keep track.

[C #]

Geolocator geolocator = null;

booltracking = false;

privatevoid TrackLocation_Click(object sender, RoutedEventArgs e)

{

if(!tracking)

{

//地理位置访问服务

geolocator = newGeolocator();

//精度级别

geolocator.DesiredAccuracy = PositionAccuracy.High;

//超过多少米引发位置改变事件

geolocator.MovementThreshold = 100;

//功能状态改变时

geolocator.StatusChanged += geolocator_StatusChanged;

//位置改变时

geolocator.PositionChanged += geolocator_PositionChanged;

tracking = true;

TrackLocationButton.Content = "停止跟踪";

}

else

{

geolocator.PositionChanged -= geolocator_PositionChanged;

geolocator.StatusChanged -= geolocator_StatusChanged;

geolocator = null;

tracking = false;

TrackLocationButton.Content = "跟踪位置";

StatusTextBlock.Text = "停止";

}

}

voidgeolocator_StatusChanged(Geolocator sender, StatusChangedEventArgs args)

{

stringstatus = "";

switch(args.Status)

{

casePositionStatus.Disabled:

status = "位置服务设置被禁用";

break;

casePositionStatus.Initializing:

status = "正在初始化";

break;

casePositionStatus.NoData:

status = "无数据";

break;

casePositionStatus.Ready:

status = "已准备";

break;

casePositionStatus.NotAvailable:

status = "无法使用";

break;

casePositionStatus.NotInitialized:

break;

}

Dispatcher.BeginInvoke(() =>

{

StatusTextBlock.Text = status;

});

}

voidgeolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)

{

Dispatcher.BeginInvoke(() =>

{

LatitudeTextBlock.Text = "经度:"+ args.Position.Coordinate.Latitude.ToString("0.00");

LongitudeTextBlock.Text = "纬度:"+ args.Position.Coordinate.Longitude.ToString("0.00");

});

}3. Continuous tracking in the background

Location tracking can be run as a service in the background, this time we do not need to update the UI, in order to enable our application to run as a service, we need to right-click Open the manifest file, choose to use the XML text editor, replace the Defaulttask node as the following information:

[XML]

      <defaulttask name= "_default" navigationpage= "MainPage.xaml" >        <BackgroundExecution>          < Executiontype  name= "locationtracking"/>        </BackgroundExecution>      </DefaultTask>

Then we need to register the Runninginbackground event, open App.xaml Add Event Application_runninginbackground, the code is as follows:

[XAML]

        <!--objects required to process lifetime events for an application--        <shell:phoneapplicationservice            launching= "Application_launching" closing= "application_closing"            activated= "application_activated" deactivated= "application_deactivated            " runninginbackground= "Application_runninginbackground"/>

Add static variables Runninginbackground and geolocator in App.xaml.cs, Runninginbackground to True when Application_runninginbackground event, Runninginbackground is false when the Application_activated event occurs. The code is as follows:

[C #]

Determines whether the app runs in the background public static bool Runninginbackground {get; set;} Provides access to the current geographic location public static Geolocator Geolocator {get; set;} Code executed when the application is activated (placed in the foreground)//This code does not execute private void application_activated (object sender, Activatedeventargs e)    when the application is first started Runninginbackground = false;} private void Application_runninginbackground (object sender, Runninginbackgroundeventargs args) {    Runninginbackground = true;}

Add the following code to the 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 = "Location:";Toast.        Navigationuri = new Uri ("/page1.xaml", urikind.relative); Toast.    Show (); }}
Ii. Maps and Navigation

To use the new map control, you need to register and register the identity in Phone:phoneapplicationpage.

[XAML]

Xmlns:maps= "Clr-namespace:microsoft.phone.maps.controls;assembly=microsoft.phone.maps"    
1. Introducing the Map control

Add the following code to the XAML to introduce the control. We see Center is the latitude and longitude of the current map central point; Zoomlevel is the zoom level; The Landmarksenabled property is set to True to display a landmark on the map control; pedestrianfeaturesenabled is set to True to show the pedestrian structure.

[XAML]

        <!--Contentpanel-place other 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= "landmarksenabled=" true " Pedestrianfeaturesenabled= "true"/>            <button foreground= "Red" content= "Specify Location" horizontalalignment= "left" Margin= "295,530,0,0" verticalalignment= "Top" click= "Button_click_1" width= "151"/> <button            Foreground= " Red "content=" Cartographic 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 Location" Horizontalalignment= "left" margin= "10,602,0,0" verticalalignment= "Top" click= "Button_click_4"/>        </Grid >
2. Setting the mapping mode

There are four options in cartographic mode, as follows:
Road: Displays the normal default two-dimensional map.
Aerial: Displays aerial survey.
Hybrid: displays an aerial view of the map overlaid with roads and labels.
Terrain: Displays a natural terrain image for the displayed highland and water structures, such as mountains and rivers.

below to see how to switch.

[C #]

Toggle Cartographic 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 both Ming and dark, we see how to achieve.

[C #]

Toggle color Mode private void Button_click_3 (object sender, RoutedEventArgs e) {    if (Mymap.colormode = = mapcolormode.light) C1/>mymap.colormode = Mapcolormode.dark;    else Mymap.colormode = mapcolormode.light;}
4. Specify a new view position

We can programmatically switch the view position to the new latitude and longitude, and can specify the transition effect when switching, here is the way to specify the parabolic line.

[C #]

private void Button_click_1 (object sender, RoutedEventArgs e) {    //by parabolic way, the angle of view to the Optical Valley Software Park in the center of the lake.    Mymap.setview (new geocoordinate (30.476724, 114.406563), mapanimationkind.parabolic);}
5. Position my position and mark

Position the map to my current location. This time need to use the location of the function, through the positioning function obtained by the latitude and longitude instance type is not the same, need to do a pre-conversion. The conversion class Coordinateconverter as follows.

[C #]

public static class coordinateconverter{    //<summary>//////To convert position to map location///</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 position the map here.

[C #]

Add other controls to the map, identify my current location private async void Button_click_4 (object sender, RoutedEventArgs e) {//Get my location Geolocator Mygeo    Locator = new Geolocator ();    Accuracy 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, mapanimationkind.parabolic);    Draw a square and then render it in my current position 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. Access to driving directions

We can also navigate through the location and map to achieve the function, the following demonstration, from my current location (Optics Valley Software Park) to the designated location (Optics Valley Venture Street) how to drive.

[XAML]

    <phone:PhoneApplicationPage.Resources> <datatemplate x:key= "Routelisttemplate" > <text    Block text= "{Binding}" fontsize= "{StaticResource phonefontsizemedium}" margin= "5,5,0,0"/> </DataTemplate> </phone:PhoneApplicationPage.Resources> <!--LayoutRoot is the root grid that contains all page content--<grid x:name= "Layoutro OT "background=" Transparent "> <Grid.RowDefinitions> <rowdefinition height=" Auto "/&gt                ; <rowdefinition height= "*"/> <rowdefinition height= "Auto"/> <rowdefinition Hei ght= "*"/> </Grid.RowDefinitions> <textblock text= "map navigation" grid.row= "0" fontsize= "{Staticre SOURCE Phonefontsizelarge} "margin=" 0,0,0,20 "/> <maps:map x:name=" MyMap "grid.row=" 1 "center=" 30.476724, 114.406563 "zoomlevel="/> <textblock text= "Driving route" grid.row= "2" fontsize= "{StaticResource Phonefontsizel Arge} "margin= "0,10,0,20"/> <phone:longlistselector x:name= "Routells" grid.row= "3" background= "Transparent" Item Template= "{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.F            Romseconds (10)); } catch (UnauthorizedAccessException) {MessageBox.Show ("System setup has closed the location service.            "); } catch (Exception ex) {} mycoordinates.add (new geocoordinate (MYGEOPOSITION.C Oordinate.        Latitude, MyGeoPosition.Coordinate.Longitude));    Mygeocodequery = new Geocodequery ();            Mygeocodequery.searchterm = "Optics Valley pioneering 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) {i F (e.error = = null) {//Get specificItinerary 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 (); }        }    }
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.