Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Navigation;
- using Microsoft.Phone.Controls;
- using Microsoft.Phone.Shell;
- using Microsoft.Phone.Maps.Controls;
- using System.Device.Location;
- using Windows.Devices.Geolocation;
- using System.Windows.Threading;
- using System.Windows.Media;
- using System.Windows.Shapes;
- using System.Threading.Tasks;
- using System.IO.IsolatedStorage;
- using Microsoft.Phone.Maps.Services;
- using System.Text;
- using MyTouristApp.Resources;
- using MyTouristApp.Utility;
- using MyTouristApp.Data;
- using System.IO;
- using System.Runtime.Serialization.Json;
- using System.Globalization;
- using Microsoft.Phone.Maps.Toolkit;
- using System.Collections.ObjectModel;
- namespace MyTouristApp
- {
- public partial class Page2 : PhoneApplicationPage
- {
- GeoCoordinateWatcher myWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
- MapPolyline line;
- DispatcherTimer _timer = new DispatcherTimer();
- long _startTime;
- GeoCoordinateWatcher watcher;
- PlacesList placesListObj;
- private string currentLatitude = string.Empty;
- private string currentLongitude = string.Empty;
- private string prevLatitude = string.Empty;
- private string prevLongitude = string.Empty;
- private Boolean isPosSet = false;
- // Constructor
- public Page2()
- {
- InitializeComponent();
- if (getConsentStatus())
- fetchUserLocation();
- _timer.Interval = TimeSpan.FromSeconds(1);
- _timer.Tick += Timer_Tick;
- // create a line which illustrates the users path
- line = new MapPolyline();
- line.StrokeColor = Colors.Red;
- line.StrokeThickness = 5;
- myMap.MapElements.Add(line);
- myWatcher.PositionChanged += Watcher_PositionChanged;
- }
- 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; // The units are meters.
- App.Geolocator.PositionChanged += geolocator_PositionChanged;
- }
- }
- protected override void OnRemovedFromJournal(System.Windows.Navigation.JournalEntryRemovedEventArgs e)
- {
- App.Geolocator.PositionChanged -= geolocator_PositionChanged;
- App.Geolocator = null;
- }
- void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
- {
- if (!App.RunningInBackground)
- {
- Dispatcher.BeginInvoke(() =>
- {
- LatitudeTextBlock.Text = args.Position.Coordinate.Latitude.ToString("0.00");
- LongitudeTextBlock.Text = 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");
- toast.Title = "Location: ";
- toast.NavigationUri = new Uri("/Page2.xaml", UriKind.Relative);
- toast.Show();
- }
- }
- private void Timer_Tick(object sender, EventArgs e)
- {
- TimeSpan runTime = TimeSpan.FromMilliseconds(System.Environment.TickCount - _startTime);
- }
- private void StartButton_Click(object sender, RoutedEventArgs e)
- {
- if (_timer.IsEnabled)
- {
- myWatcher.Stop();
- _timer.Stop();
- StartButton.Content = "Start";
- }
- else
- {
- myWatcher.Start();
- _timer.Start();
- _startTime = System.Environment.TickCount;
- StartButton.Content = "Stop";
- }
- }
- private void Watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
- {
- var coord = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);
- myMap.Center = coord;
- line.Path.Add(coord);
- }
- public bool getConsentStatus()
- {
- if (IsolatedStorageSettings.ApplicationSettings.Contains("LocationConsent"))
- {
- // User has already made a decision, just retrieve that decision.
- if (Convert.ToBoolean(IsolatedStorageSettings.
- ApplicationSettings["LocationConsent"]))
- {
- return Convert.ToBoolean(IsolatedStorageSettings.
- ApplicationSettings["LocationConsent"]);
- }
- else
- {
- MessageBoxResult result =
- MessageBox.Show(AppConstants.strYouHadChoosenNoLoc, "Location", MessageBoxButton.OKCancel);
- if (result == MessageBoxResult.OK)
- {
- IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true;
- }
- else
- {
- IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false;
- }
- IsolatedStorageSettings.ApplicationSettings.Save();
- return result == MessageBoxResult.OK;
- }
- }
- else
- {
- MessageBoxResult result =
- MessageBox.Show(AppConstants.strAppRequiresYourLoc,
- "Location",
- MessageBoxButton.OKCancel);
- if (result == MessageBoxResult.OK)
- {
- IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true;
- }
- else
- {
- IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false;
- }
- IsolatedStorageSettings.ApplicationSettings.Save();
- return result == MessageBoxResult.OK;
- }
- }
- private void fetchUserLocation()
- {
- // 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.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
- }
- watcher.Start();
- }
- void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
- {
- currentLatitude = e.Position.Location.Latitude.ToString("0.000");
- currentLongitude = e.Position.Location.Longitude.ToString("0.000");
- if (!isPosSet)
- {
- isPosSet = true;
- startGeoNamesAPICall();
- }
- }
- private void startGeoNamesAPICall()
- {
- try
- {
- HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(AppConstants.baseUri + "&lat=" + currentLatitude + "&lng=" + currentLongitude + "&username=" + AppConstants.strUserName + "&radius=" + AppConstants.strDefaultRadiusForWikiAPI + "&maxRows=" + AppConstants.strDefaultResultRowsForWikiAPI));
- httpReq.BeginGetResponse(HTTPWebRequestCallBack, httpReq);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
- private void HTTPWebRequestCallBack(IAsyncResult result)
- {
- string strResponse = "";
- try
- {
- Dispatcher.BeginInvoke(() =>
- {
- try
- {
- HttpWebRequest httpRequest = (HttpWebRequest)result.AsyncState;
- WebResponse response = httpRequest.EndGetResponse(result);
- Stream stream = response.GetResponseStream();
- StreamReader reader = new StreamReader(stream);
- strResponse = reader.ReadToEnd();
- parseResponseData(strResponse);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- });
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
- private void parseResponseData(String aResponse)
- {
- placesListObj = new PlacesList();
- MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(aResponse));
- DataContractJsonSerializer ser = new DataContractJsonSerializer(placesListObj.GetType());
- placesListObj = ser.ReadObject(ms) as PlacesList;
- ms.Close();
- // updating UI
- if (placesListObj != null)
- {
- updateMap(placesListObj);
- }
- }
- private void updateMap(PlacesList aWiKIAPIResponse)
- {
- int totalRecords = aWiKIAPIResponse.PlaceList.Count();
- myMap.Visibility = System.Windows.Visibility.Visible;
- try
- {
- ObservableCollection<PlaceToMap> placeToMapObjs = new ObservableCollection<PlaceToMap>();
- for (int index = 0; index < totalRecords; index++)
- {
- placeToMapObjs.Add(new PlaceToMap()
- {
- Coordinate = new GeoCoordinate(Convert.ToDouble(aWiKIAPIResponse.PlaceList.ElementAt(index).Latitude),
- Convert.ToDouble(aWiKIAPIResponse.PlaceList.ElementAt(index).Longitude)),
- Info = aWiKIAPIResponse.PlaceList.ElementAt(index).Title + Environment.NewLine + aWiKIAPIResponse.PlaceList.ElementAt(index).Feature
- });
- }
- ObservableCollection<DependencyObject> children = MapExtensions.GetChildren(myMap);
- var obj = children.FirstOrDefault(x => x.GetType() == typeof(MapItemsControl)) as MapItemsControl;
- obj.ItemsSource = placeToMapObjs;
- myMap.SetView(new GeoCoordinate(Convert.ToDouble(currentLatitude), Convert.ToDouble(currentLongitude)), 14, 0, 55);
- }
- catch (Exception)
- {
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement