static GeoResponse Geocode(string name) { GeoResponse output = null; string baseUrl = "https://geocode.localfocus.nl/geocode.php?q={0}&boundary=ITA"; using (var client = new HttpClient()) { var response = client.GetAsync(string.Format(baseUrl, name)).Result; if (response.IsSuccessStatusCode) { var responseContent = response.Content; string responseString = responseContent.ReadAsStringAsync().Result; if (responseString != null) { List <GeoResponse> items = JsonConvert.DeserializeObject <List <GeoResponse> >(responseString); foreach (GeoResponse item in items) { if (output == null || (output != null && output.Confidence < item.Confidence)) { output = item; } } } } } return(output); }
private static GeoResponse GetGeoResponse(string url) { GeoResponse res = null; try { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeoResponse)); WebProxy proxy = request.Proxy as WebProxy; if (proxy != null) { string proxyuri = proxy.GetProxy(request.RequestUri).ToString(); request.UseDefaultCredentials = true; request.Proxy = new WebProxy(proxyuri, false) { Credentials = CredentialCache.DefaultCredentials }; } Stream stream = request.GetResponse().GetResponseStream(); res = (GeoResponse)serializer.ReadObject(stream); } catch (Exception ex) { MessageBox.Show("Unable to contact https://maps.googleapis.com error was : " + ex.Message, "FTAnalyzer"); } return(res); }
static void ProcessData() { country = new Country(); country.Name = "Italia"; country.Code = "it"; GeoResponse geo = Geocode(country.Name); if (geo != null) { country.Latitude = geo.Latitude; country.Longitude = geo.Longitude; } int counter = 0; string line; StreamReader sr = new StreamReader("Data/istat_20190630.csv"); while ((line = sr.ReadLine()) != null) { string[] values = line.Split(CSV_SEPARATOR); for (int i = 0; i < values.Length; i++) { values[i] = values[i].Trim(); } Region region = ParseRegion(values); District district = ParseDistrict(values, region); City city = ParseCity(values, district); counter++; } sr.Close(); }
// Call geocoding routine but account for throttling by Google geocoding engine public static GeoResponse GoogleReverseGeocode(double latitude, double longitude, int badtries) { double seconds = sleepinterval / 1000; if (sleepinterval > 500) { OnWaitingForGoogle("Over Google limit. Waiting " + seconds + " seconds."); } if (sleepinterval >= 20000) { OnWaitingForGoogle("Max Google GeoLocations exceeded for today."); GeoResponse response = new GeoResponse { Status = "Maxed" }; return(response); } for (int interval = 0; interval < sleepinterval; interval += 1000) { Thread.Sleep(1000); if (ThreadCancelled) { return(null); } } GeoResponse res; try { res = CallGoogleReverseGeocode(latitude, longitude); } catch (Exception e) { OnWaitingForGoogle("Caught exception: " + e); res = null; } if (res == null || res.Status == "OVER_QUERY_LIMIT") { // we're hitting Google too fast, increase interval sleepinterval = Math.Min(sleepinterval + ++badtries * 750, 20000); return(GoogleReverseGeocode(latitude, longitude, badtries)); } else { OnWaitingForGoogle(string.Empty); // going well clear any previous message // no throttling, go a little bit faster if (sleepinterval > 10000) { sleepinterval = 200; } else { sleepinterval = Math.Max(sleepinterval / 2, 75); } return(res); } }
static void Main(string[] args) { string url = "http://maps.googleapis.com/maps/api/geocode/" + "json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false"; WebResponse response = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; response = request.GetResponse(); if (response != null) { string str = null; using (Stream stream = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(stream)) { str = streamReader.ReadToEnd(); } } GeoResponse geoResponse = JsonConvert.DeserializeObject <GeoResponse>(str); if (geoResponse.Status == "OK") { int count = geoResponse.Results.Length; for (int i = 0; i < count; i++) { Console.WriteLine("Lat: {0}", geoResponse.Results [i].Geometry.Location.Lat); Console.WriteLine("Lng: {0}", geoResponse.Results [i].Geometry.Location.Lng); } } else { Console.WriteLine("JSON response failed, status is '{0}'", geoResponse.Status); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Console.WriteLine("Clean up"); if (response != null) { response.Close(); response = null; } } Console.WriteLine("Done."); Console.ReadLine(); }
public List <string> getLatLong(string street, string town, string city) { List <string> diclatlong = new List <string>(); string geoString = "https://maps.googleapis.com/maps/api/geocode/json?address=" + street + "," + town + "," + city + "&key=" + API_KEY; WebResponse response = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(geoString); request.Method = "GET"; response = request.GetResponse(); if (response != null) { string str = null; using (Stream stream = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(stream)) { str = streamReader.ReadToEnd(); } } GeoResponse geoResponse = JsonConvert.DeserializeObject <GeoResponse>(str); if (geoResponse.Status == "OK") { int count = geoResponse.Results.Length; for (int i = 0; i < count; i++) { diclatlong.Add(geoResponse.Results[i].Geometry.Location.Lat.ToString()); diclatlong.Add(geoResponse.Results[i].Geometry.Location.Lng.ToString()); } } else { diclatlong = null; } } } catch { throw new Exception("JSON response failed."); } finally { if (response != null) { response.Close(); response = null; } } return(diclatlong); }
public bool SetLocation(FactLocation loc, int level) { while (!loaded) { Application.DoEvents(); } GeoResponse.CResult.CGeometry.CViewPort viewport = null; GeoResponse res = null; Object[] args = new Object[] { 0, 0 }; if (loc.IsGeoCoded(false) && loc.ViewPort != null) { labMapLevel.Text = "Previously Geocoded: " + loc.ToString(); viewport = MapTransforms.ReverseTransformViewport(loc.ViewPort); args = new Object[] { loc.Latitude, loc.Longitude }; } else { location = loc.ToString(); res = CallGoogleGeocode(location); if (res.Status == "OK") { labMapLevel.Text = GoogleMap.LocationText(res, loc, level); viewport = res.Results[0].Geometry.ViewPort; double lat = res.Results[0].Geometry.Location.Lat; double lng = res.Results[0].Geometry.Location.Long; args = new Object[] { lat, lng }; } else if (res.Status == "OVER_QUERY_LIMIT" && loc.IsGeoCoded(false)) { labMapLevel.Text = "Previously Geocoded: " + loc.ToString(); viewport = new GeoResponse.CResult.CGeometry.CViewPort(); viewport.NorthEast.Lat = loc.Latitude + 2; viewport.NorthEast.Long = loc.Longitude + 2; viewport.SouthWest.Lat = loc.Latitude - 2; viewport.SouthWest.Long = loc.Longitude - 2; args = new Object[] { loc.Latitude, loc.Longitude }; } else { return(false); } } Object marker = webBrowser.Document.InvokeScript("frontAndCenter", args); args = new Object[] { viewport.NorthEast.Lat, viewport.NorthEast.Long, viewport.SouthWest.Lat, viewport.SouthWest.Long }; webBrowser.Document.InvokeScript("setViewport", args); webBrowser.Show(); return(true); }
static GeoResponse MaxedOut() { string message = string.IsNullOrEmpty(Properties.MappingSettings.Default.GoogleAPI) ? "Max Google GeoLocations exceeded for today.\nConsider getting your own FREE Google API Key for 40,000 lookups a day. See Help Menu.\n" : "Max Google GeoLocations exceeded for today.\n"; OnWaitingForGoogle(message); GeoResponse response = new GeoResponse { Status = "Maxed" }; return(response); }
static City ParseCity(string[] values, District district) { City temp = new City(); bool isNew = true; foreach (City city in district.Cities) { if (city.Code.Equals(values[4])) { temp = city; isNew = false; break; } } if (isNew) { temp.Code = values[4]; temp.Name = values[5]; temp.OriginalName = values[6]; temp.AlternativeName = values[7]; temp.Progressive = values[3]; temp.IsDistrict = values[12] == "1" ? true : false; temp.NumericCode = int.Parse(values[14]); temp.Code110 = values[15]; temp.Code107 = values[16]; temp.Code103 = values[17]; temp.CadastralCode = values[18]; temp.Population = int.Parse(values[19].Replace(".", "").Replace(",", "")); temp.NUTS1 = values[20]; temp.NUTS2 = values[21]; temp.NUTS3 = values[22]; Console.WriteLine("City: " + temp.Name); GeoResponse geo = Geocode(temp.Name); if (geo != null) { temp.Latitude = geo.Latitude; temp.Longitude = geo.Longitude; } district.Cities.Add(temp); } return(temp); }
private async void Addroute(GeoResponse sResponse, GeoResponse dResponse, string source, string destination) { AddMapIcon(Convert.ToDouble(sResponse.Position.Latitude), Convert.ToDouble(sResponse.Position.Longitude), source); AddMapIcon(Convert.ToDouble(dResponse.Position.Latitude), Convert.ToDouble(dResponse.Position.Longitude), destination); MapPolyline polyline = new MapPolyline(); var coordinates = new List <BasicGeoposition>(); var routeClient = new RouteClient(); coordinates = await routeClient.route(source, destination); //polyline.StrokeColor = Windows.UI.Color.FromArgb(128, 255, 0, 0); //polyline.StrokeThickness = 5; //polyline.Path = new Geopath(coordinates); //MyMap.MapElements.Add(polyline); }
private static GeoResponse GetLocation(GeoResponse geoResponse) { if (!(geoResponse.Success && geoResponse.StatusText.Equals("OK", StringComparison.InvariantCulture))) { return(geoResponse); } var latNode = geoResponse.XmlDocument.SelectSingleNode("/GeocodeResponse/result/geometry/location/lat"); var lngNode = geoResponse.XmlDocument.SelectSingleNode("/GeocodeResponse/result/geometry/location/lng"); var locTypeNode = geoResponse.XmlDocument.SelectSingleNode("/GeocodeResponse/result/geometry/location_type"); if (latNode == null || lngNode == null || locTypeNode == null) { throw new Exception("XML child nodes in /GeocodeResponse/result/geometry not found"); } switch (locTypeNode.InnerText) { case "ROOFTOP": geoResponse.GeoLocation.LocationType = LocationType.RoofTop; break; case "RANGE_INTERPOLATED": geoResponse.GeoLocation.LocationType = LocationType.RangeInterpolated; break; case "GEOMETRIC_CENTER": geoResponse.GeoLocation.LocationType = LocationType.GeometricCenter; break; case "APPROXIMATE": geoResponse.GeoLocation.LocationType = LocationType.Approximate; break; default: geoResponse.Success = false; return(geoResponse); } geoResponse.GeoLocation.Latitude = new Latitude(Angle.FromDegrees(double.Parse(latNode.InnerText, CultureInfo.InvariantCulture.NumberFormat))); geoResponse.GeoLocation.Longitude = new Longitude(Angle.FromDegrees(double.Parse(lngNode.InnerText, CultureInfo.InvariantCulture.NumberFormat))); return(geoResponse); }
public bool SetLocation(FactLocation loc, int level) { if (loc is null) { return(false); } while (!loaded) { Application.DoEvents(); } GeoResponse.CResult.CGeometry.CViewPort viewport; if (loc.IsGeoCoded(false) && loc.ViewPort != null) { labMapLevel.Text = "Previously Geocoded: " + loc.ToString(); viewport = MapTransforms.ReverseTransformViewport(loc.ViewPort); } else { GeoResponse res = GoogleMap.CallGoogleGeocode(loc, loc.ToString()); if (res.Status == "OK") { labMapLevel.Text = GoogleMap.LocationText(res, loc, level); viewport = res.Results[0].Geometry.ViewPort; } else if (res.Status == "OVER_QUERY_LIMIT" && loc.IsGeoCoded(false)) { labMapLevel.Text = "Previously Geocoded: " + loc.ToString(); viewport = new GeoResponse.CResult.CGeometry.CViewPort(); viewport.NorthEast.Lat = loc.Latitude + 2; viewport.NorthEast.Long = loc.Longitude + 2; viewport.SouthWest.Lat = loc.Latitude + 2; viewport.SouthWest.Long = loc.Longitude + 2; } else { return(false); } } object[] args = new object[] { viewport.NorthEast.Lat, viewport.NorthEast.Long, viewport.SouthWest.Lat, viewport.SouthWest.Long }; webBrowser.Document.InvokeScript("setBounds", args); webBrowser.Show(); return(true); }
private static async Task <GeoResponse> EvaluateResponse(HttpResponseMessage httpResponse) { const string statusNode = "/GeocodeResponse/status"; var geoResponse = new GeoResponse { Success = httpResponse.IsSuccessStatusCode }; if (!geoResponse.Success) { return(geoResponse); } geoResponse.XmlDocument = new XmlDocument(); geoResponse.XmlDocument.LoadXml(await httpResponse.Content.ReadAsStringAsync()); geoResponse.StatusText = geoResponse.XmlDocument.SelectSingleNode(statusNode)?.InnerText; switch (geoResponse.StatusText) { case null: throw new Exception($"XML node {statusNode} not found"); case "OK": geoResponse.Found = true; geoResponse.Success = true; return(geoResponse); case "ZERO_RESULTS": geoResponse.Found = false; geoResponse.Success = true; return(geoResponse); case "INVALID_REQUEST": case "REQUEST_DENIED": case "OVER_DAILY_LIMIT": case "OVER_QUERY_LIMIT": case "UNKNOWN_ERROR": default: geoResponse.Success = false; geoResponse.Found = false; return(geoResponse); } }
public static string LocationText(GeoResponse res, FactLocation loc, int level) { string output; int returnlevel = GetFactLocationType(res.Results[0].Types, loc); if (returnlevel != FactLocation.UNKNOWN) { output = $"Google found {loc.GetLocation(returnlevel)}"; // if we have different input and output levels, assuming it isn't just a more accurate place in the address field // then also show what Google found if (level != returnlevel && !(level == FactLocation.ADDRESS && returnlevel >= FactLocation.ADDRESS)) { output += $" as {res.Results[0].ReturnAddress}"; } } else { output = $"Best guess for {loc.GetLocation(level)} is {res.Results[0].ReturnAddress}"; } return(output); }
private async void mDestinationTextBoxClicked(object sender, AdapterView.ItemClickEventArgs e) { dest = destinationSuggestionsAdapter.GetObjectAt(e.Position); System.Diagnostics.Debug.Write(dest); autoDestinationBox.Text = destinationSuggestionsAdapter.GetObjectAt(e.Position); if (msourceRecieved != null && dest != null) { GeoResponse mResponseGetDestlatlng = await api.GeoCodingResult(token, dest); dlat = mResponseGetDestlatlng.Position.Latitude; dlng = mResponseGetDestlatlng.Position.Longitude; setDestinationMarker(dest); mLoadingDialog.Show(); PriceEstimateResponse mRes = await api.GetEstimate(token, slat, slng, dlat, dlng); mCabsEst = mRes.Estimates; CabRecyclerAdapterWithDestination mAdapter = new CabRecyclerAdapterWithDestination(Application.Context, mCabsEst, mActivity); mAdapter.ItemClick1 += Item_Click_New; mRecyclerView.SetAdapter(mAdapter); mLoadingDialog.Dismiss(); } }
void GoogleLocationSearch() { if (txtSearch.Text.Length > 0) { FactLocation loc = FactLocation.LookupLocation(txtSearch.Text); if (!loc.IsGeoCoded(false)) // if not geocoded then try database { DatabaseHelper.GetLocationDetails(loc); } if (loc.IsGeoCoded(false)) { FactLocation.CopyLocationDetails(loc, location); SetLocation(); pointUpdated = true; } else { GeoResponse res = GoogleMap.GoogleGeocode(txtSearch.Text, 8); if (res.Status == "OK" && !(res.Results[0].Geometry.Location.Lat == 0 && res.Results[0].Geometry.Location.Long == 0)) { loc.Latitude = res.Results[0].Geometry.Location.Lat; loc.Longitude = res.Results[0].Geometry.Location.Long; Coordinate mpoint = MapTransforms.TransformCoordinate(new Coordinate(loc.Longitude, loc.Latitude)); loc.LongitudeM = mpoint.X; loc.LatitudeM = mpoint.Y; loc.ViewPort = MapTransforms.TransformViewport(res.Results[0].Geometry.ViewPort); loc.GeocodeStatus = res.Results[0].PartialMatch ? FactLocation.Geocode.PARTIAL_MATCH : FactLocation.Geocode.MATCHED; FactLocation.CopyLocationDetails(loc, location); SetLocation(); pointUpdated = true; } else { MessageBox.Show("Google didn't find " + txtSearch.Text, "Failed Google Lookup"); } } } }
static Region ParseRegion(string[] values) { Region temp = new Region(); bool isNew = true; foreach (Region region in country.Regions) { if (region.Code.Equals(values[0])) { temp = region; isNew = false; break; } } if (isNew) { temp.Code = values[0]; temp.ZoneCode = int.Parse(values[8]); temp.ZoneName = values[9]; temp.Name = values[10]; Console.WriteLine("Region: " + temp.Name); GeoResponse geo = Geocode(temp.Name); if (geo != null) { temp.Latitude = geo.Latitude; temp.Longitude = geo.Longitude; } country.Regions.Add(temp); } return(temp); }
static District ParseDistrict(string[] values, Region region) { District temp = new District(); bool isNew = true; foreach (District district in region.Districts) { if (district.Code.Equals(values[2])) { temp = district; isNew = false; break; } } if (isNew) { temp.Code = values[2]; temp.Name = values[11]; temp.TerritorialUnitCode = values[8]; temp.TerritorialUnit = values[9]; temp.Abbreviation = values[13]; Console.WriteLine("District: " + temp.Name); GeoResponse geo = Geocode(temp.Name); if (geo != null) { temp.Latitude = geo.Latitude; temp.Longitude = geo.Longitude; } region.Districts.Add(temp); } return(temp); }
//Get Coordinates public Coordinate getCoordinate(string searchPlace) { using (var client = new WebClient()) { string uri = "https://maps.googleapis.com/maps/api/geocode/json?address=" + searchPlace.ToString() + "&key=" + TravisKey; string results = client.DownloadString(uri); JavaScriptSerializer js = new JavaScriptSerializer(); GeoResponse georesults = js.Deserialize <GeoResponse>(results); if (georesults.Status == "OK") { return(new Coordinate(Convert.ToDouble(georesults.Results[0].Geometry.Location.Lat), Convert.ToDouble(georesults.Results[0].Geometry.Location.Lng))); } else { return(new Coordinate(42.3347, -83.0497)); } } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (!IsInternet()) { await new MessageDialog("Seems you are not connected to the Internet").ShowAsync(); return; } else { progress.IsActive = true; MyMap.MapServiceToken = "YP9WTSzOHUo0dbahsH8J~J-K6u01dT98SF4uCCKpiwA~AnGaYM6yJxoLF1tGHEIXHFskGfwSRJTr1S5aO1dB-TCXjQ1ZX0xEWgeYslbC3Fov"; Geolocator locator = new Geolocator(); locator.DesiredAccuracyInMeters = 50; var position = await locator.GetGeopositionAsync(); await MyMap.TrySetViewAsync(position.Coordinate.Point, 17D); progress.IsActive = false; mySlider.Value = 13; Arguments args = e.Parameter as Arguments; Dictionary <string, object> Parameters = args.Values; if (args.GetType(VoiceCommandType.NO_VOICE)) { mSource = Parameters["source"].ToString(); mDestination = Parameters["destination"].ToString(); CabsAPI api = new CabsAPI(); GeoResponse sResponse = await api.GeoCodingResult(Token, mSource); GeoResponse dResponse = await api.GeoCodingResult(Token, mDestination); if (sResponse.Code == ResponseCode.SUCCESS && dResponse.Code == ResponseCode.SUCCESS) { AddMapIcon(Convert.ToDouble(sResponse.Position.Latitude), Convert.ToDouble(sResponse.Position.Longitude), mSource); AddMapIcon(Convert.ToDouble(dResponse.Position.Latitude), Convert.ToDouble(dResponse.Position.Longitude), mDestination); } else { await new MessageDialog("Error retrieving Geopositions!").ShowAsync(); return; } MapPolyline polyline = new MapPolyline(); var coordinates = new List <BasicGeoposition>(); var routeClient = new RouteClient(); coordinates = await routeClient.route(mSource, mDestination); polyline.StrokeColor = Windows.UI.Color.FromArgb(128, 255, 0, 0); polyline.StrokeThickness = 5; polyline.Path = new Geopath(coordinates); MyMap.MapElements.Add(polyline); SrcBox.Text = mSource; DestBox.Text = mDestination; PriceEstimateResponse pResponse = await api.GetEstimate(Token, Parameters["slat"].ToString(), Parameters["slng"].ToString(), Parameters["dlat"].ToString(), Parameters["dlng"].ToString()); if (pResponse.Code == ResponseCode.SUCCESS) { CabsListView.ItemsSource = pResponse.Estimates; // ReadSpeech(new MediaElement(), "Showing Estimated cab fare from" + mSource + "to" + mDestination); } } } }
public async void init(View rootView) { if (!isOnline()) { mErrorDialog.Show(); return; } api = new CabsAPI(); mLoadingDialog = new LoadingDialog(mActivity, Resource.Drawable.main); mLoadingDialog.SetCancelable(false); Window window = mLoadingDialog.Window; window.SetLayout(WindowManagerLayoutParams.MatchParent, WindowManagerLayoutParams.MatchParent); window.SetBackgroundDrawable(new ColorDrawable(Resources.GetColor(Resource.Color.trans))); SpannableString s = new SpannableString("Home"); typeface = Typeface.CreateFromAsset(mActivity.Assets, "JosefinSans-SemiBold.ttf"); s.SetSpan(new TypefaceSpan("Amaranth-Regular.ttf"), 0, s.Length(), SpanTypes.ExclusiveExclusive); s.SetSpan(new ForegroundColorSpan(this.Resources.GetColor(Resource.Color.title)), 0, s.Length(), SpanTypes.ExclusiveExclusive); mActivity.TitleFormatted = s; mSharedPreference = mActivity.GetSharedPreferences(Constants.MY_PREF, 0); token = mSharedPreference.GetString("token", " "); if (mActivity.Intent.GetStringExtra("source") != null) { msourceRecieved = mActivity.Intent.GetStringExtra("source"); } else { msourceRecieved = mSharedPreference.GetString("source", "1,ISB Rd,Gachibowli"); } autoSourceBox = rootView.FindViewById <AppCompatAutoCompleteTextView>(Resource.Id.sourceauto); autoSourceBox.Text = msourceRecieved; sourceSuggestionsAdapter = new SearchSuggestionsAdapter(mActivity); autoSourceBox.Adapter = sourceSuggestionsAdapter; destinationSuggestionsAdapter = new SearchSuggestionsAdapter(mActivity); autoSourceBox.ItemClick += mSourceTextBoxClicked; autoDestinationBox = rootView.FindViewById <AppCompatAutoCompleteTextView>(Resource.Id.destinationauto); autoDestinationBox.Adapter = destinationSuggestionsAdapter; autoDestinationBox.ItemClick += mDestinationTextBoxClicked; mLoadingDialog.Show(); mRecyclerView = rootView.FindViewById <RecyclerView>(Resource.Id.cabrecycler); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(Application.Context); mRecyclerView.SetLayoutManager(linearLayoutManager); mRecyclerView.AddItemDecoration(new VerticalSpaceItemDecoration(VERTICAL_ITEM_SPACE)); LayoutInflater inflater = (LayoutInflater)Activity.GetSystemService(Context.LayoutInflaterService); View Childlayout = inflater.Inflate(Resource.Layout.fragment_google_maps, null); if (msourceRecieved != null) { GeoResponse mResponseGetSourcelatlng = await api.GeoCodingResult(token, msourceRecieved); slat = mResponseGetSourcelatlng.Position.Latitude; slng = mResponseGetSourcelatlng.Position.Longitude; hasSourceSet = false; setSourceMarker(msourceRecieved); } CabsResponse response = await api.GetNearbyCabs(slat, slng, Constants.AUTH_TOKEN); if (response.Code == ResponseCode.SUCCESS) { mCabs = response.Cabs; mAdapter = new CabRecyclerAdapter(Application.Context, mCabs, mActivity); mAdapter.ItemClick += OnItemClick; mRecyclerView.SetAdapter(mAdapter); mLoadingDialog.Dismiss(); } }
protected override async void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); if (!isOnline()) { mErrorDialog.Show(); } else { SetContentView(Resource.Layout.activity_confirm_details); Drawable upArrow = Resources.GetDrawable(Resource.Drawable.abc_ic_ab_back_mtrl_am_alpha); upArrow.SetColorFilter(Resources.GetColor(Resource.Color.white), PorterDuff.Mode.SrcAtop); eta = Intent.GetStringExtra("eta"); high = Intent.GetStringExtra("high"); low = Intent.GetStringExtra("low"); time = Intent.GetStringExtra("time"); sourcestring = Intent.GetStringExtra("source"); type = Intent.GetStringExtra("type"); deststring = Intent.GetStringExtra("destination"); provider = Intent.GetStringExtra("provider"); capacity = Intent.GetStringExtra("capacity"); distance = Intent.GetStringExtra("distance"); fare = Intent.GetStringExtra("fare"); mSharedPreferences = GetSharedPreferences(Constants.MY_PREF, 0); SupportActionBar.SetHomeAsUpIndicator(upArrow); SupportActionBar.SetDisplayHomeAsUpEnabled(true); token = mSharedPreferences.GetString("token", " "); mLoadingDialog = new LoadingDialog(this, Resource.Drawable.main); mLoadingDialog.SetCancelable(false); Window window = mLoadingDialog.Window; window.SetLayout(WindowManagerLayoutParams.MatchParent, WindowManagerLayoutParams.MatchParent); window.SetBackgroundDrawable(new ColorDrawable(Resources.GetColor(Resource.Color.trans))); SpannableString s = new SpannableString("Confirm Booking"); typeface = Typeface.CreateFromAsset(this.Assets, "JosefinSans-SemiBold.ttf"); s.SetSpan(new TypefaceSpan("Amaranth-Regular.ttf"), 0, s.Length(), SpanTypes.ExclusiveExclusive); s.SetSpan(new ForegroundColorSpan(this.Resources.GetColor(Resource.Color.title)), 0, s.Length(), SpanTypes.ExclusiveExclusive); this.TitleFormatted = s; mCardView = FindViewById <CardView>(Resource.Id.mapsviewcard); mConfirmButton = FindViewById <Button>(Resource.Id.btn_request); if (provider.Equals("ola", StringComparison.InvariantCultureIgnoreCase)) { mConfirmButton.SetBackgroundColor(Resources.GetColor(Resource.Color.greenola)); mConfirmButton.SetTextColor(Resources.GetColor(Resource.Color.black)); } else { mConfirmButton.SetBackgroundColor(Resources.GetColor(Resource.Color.black)); } mSource = FindViewById <TextView>(Resource.Id.sourcetext); mDest = FindViewById <TextView>(Resource.Id.destinationtext); etaText = FindViewById <TextView>(Resource.Id.etatext); etaValue = FindViewById <TextView>(Resource.Id.etavalue); distText = FindViewById <TextView>(Resource.Id.disttext); distValue = FindViewById <TextView>(Resource.Id.distvalue); priceText = FindViewById <TextView>(Resource.Id.pricetext); priceVlaue = FindViewById <TextView>(Resource.Id.pricevalue); timeText = FindViewById <TextView>(Resource.Id.timetext); timeValue = FindViewById <TextView>(Resource.Id.timevalue); mConfirmButton.SetTypeface(typeface, TypefaceStyle.Normal); mSource.SetTypeface(typeface, TypefaceStyle.Normal); mDest.SetTypeface(typeface, TypefaceStyle.Normal); etaText.SetTypeface(typeface, TypefaceStyle.Normal); etaValue.SetTypeface(typeface, TypefaceStyle.Normal); distText.SetTypeface(typeface, TypefaceStyle.Normal); distValue.SetTypeface(typeface, TypefaceStyle.Normal); priceText.SetTypeface(typeface, TypefaceStyle.Normal); priceVlaue.SetTypeface(typeface, TypefaceStyle.Normal); timeText.SetTypeface(typeface, TypefaceStyle.Normal); timeValue.SetTypeface(typeface, TypefaceStyle.Normal); mSource.Text = sourcestring; mDest.Text = deststring; etaValue.Text = eta; distValue.Text = distance; priceVlaue.Text = low + "-" + high; timeValue.Text = time; mConfirmButton.Text = "REQUEST " + type; sourcestring = mSource.Text; deststring = mDest.Text; CabsAPI api = new CabsAPI(); mLoadingDialog.Show(); GeoResponse mResponse1 = await api.GeoCodingResult(token, sourcestring); GeoResponse mResponse2 = await api.GeoCodingResult(token, deststring); if (mResponse1.Code == ResponseCode.SUCCESS && mResponse2.Code == ResponseCode.SUCCESS) { mLoadingDialog.Dismiss(); slat = mResponse1.Position.Latitude.ToString(); slng = mResponse1.Position.Longitude.ToString(); dlat = mResponse2.Position.Latitude.ToString(); dlng = mResponse2.Position.Longitude.ToString(); } sourcepos = new LatLng(Convert.ToDouble(slat), Convert.ToDouble(slng)); destpos = new LatLng(Convert.ToDouble(dlat), Convert.ToDouble(dlng)); mConfirmButton.SetOnClickListener(this); setupGoogleMap(); } }
protected override async void OnCreate(Bundle savedInstanceState) { if (!isOnline()) { mErrorDialog.Show(); } else { for (int i = 0; i < 2; i++) { mOptions[i] = new MarkerOptions(); } base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_confirmed_booking); Drawable upArrow = Resources.GetDrawable(Resource.Drawable.abc_ic_ab_back_mtrl_am_alpha); upArrow.SetColorFilter(Resources.GetColor(Resource.Color.white), PorterDuff.Mode.SrcAtop); etaval = Intent.GetStringExtra("eta"); high = Intent.GetStringExtra("high"); low = Intent.GetStringExtra("low"); time = Intent.GetStringExtra("time"); sourcestring = Intent.GetStringExtra("source"); type = Intent.GetStringExtra("type"); deststring = Intent.GetStringExtra("destination"); provider = Intent.GetStringExtra("provider"); capacity = Intent.GetStringExtra("capacity"); distance = Intent.GetStringExtra("distance"); fare = Intent.GetStringExtra("fare"); mSharedPreferences = GetSharedPreferences(Constants.MY_PREF, 0); SupportActionBar.SetHomeAsUpIndicator(upArrow); SupportActionBar.SetDisplayHomeAsUpEnabled(true); token = mSharedPreferences.GetString("token", " "); mLoadingDialog = new LoadingDialog(this, Resource.Drawable.main); mLoadingDialog.SetCancelable(false); Window window = mLoadingDialog.Window; window.SetLayout(WindowManagerLayoutParams.MatchParent, WindowManagerLayoutParams.MatchParent); window.SetBackgroundDrawable(new ColorDrawable(Resources.GetColor(Resource.Color.trans))); SpannableString s = new SpannableString("Successfully Booked"); typeface = Typeface.CreateFromAsset(this.Assets, "JosefinSans-SemiBold.ttf"); s.SetSpan(new TypefaceSpan("Amaranth-Regular.ttf"), 0, s.Length(), SpanTypes.ExclusiveExclusive); s.SetSpan(new ForegroundColorSpan(this.Resources.GetColor(Resource.Color.title)), 0, s.Length(), SpanTypes.ExclusiveExclusive); this.TitleFormatted = s; mSource = FindViewById <TextView>(Resource.Id.sourcetext); mDest = FindViewById <TextView>(Resource.Id.destinationtext); eta = FindViewById <TextView>(Resource.Id.eta); dist = FindViewById <TextView>(Resource.Id.dist); price = FindViewById <TextView>(Resource.Id.price); etatext = FindViewById <TextView>(Resource.Id.etavalue); disttext = FindViewById <TextView>(Resource.Id.distvalue); pricetext = FindViewById <TextView>(Resource.Id.pricevalue); drivertext = FindViewById <TextView>(Resource.Id.drivername); cartype = FindViewById <TextView>(Resource.Id.cartype); carnumber = FindViewById <TextView>(Resource.Id.carnumber); mProvider = FindViewById <ImageView>(Resource.Id.cabprovider); mDriver = FindViewById <ImageView>(Resource.Id.driverimage); mPhone = FindViewById <ImageView>(Resource.Id.phoneimage); mPhone.SetOnClickListener(this); mSource.SetTypeface(typeface, TypefaceStyle.Normal); mDest.SetTypeface(typeface, TypefaceStyle.Normal); eta.SetTypeface(typeface, TypefaceStyle.Normal); etatext.SetTypeface(typeface, TypefaceStyle.Normal); price.SetTypeface(typeface, TypefaceStyle.Normal); pricetext.SetTypeface(typeface, TypefaceStyle.Normal); dist.SetTypeface(typeface, TypefaceStyle.Normal); disttext.SetTypeface(typeface, TypefaceStyle.Normal); drivertext.SetTypeface(typeface, TypefaceStyle.Normal); cartype.SetTypeface(typeface, TypefaceStyle.Normal); carnumber.SetTypeface(typeface, TypefaceStyle.Normal); mSource.Text = sourcestring.ToUpperInvariant(); mDest.Text = deststring.ToUpperInvariant(); etatext.Text = etaval; disttext.Text = distance; pricetext.Text = low + "-" + high; if (provider.Equals("Uber", StringComparison.InvariantCultureIgnoreCase)) { mProvider.SetImageResource(Resource.Drawable.uber); } else { mProvider.SetImageResource(Resource.Drawable.ola); } mcab = new CabsAPI(); mLoadingDialog.Show(); GeoResponse mResponse1 = await mcab.GeoCodingResult(token, sourcestring); GeoResponse mResponse2 = await mcab.GeoCodingResult(token, deststring); if (mResponse1.Code == ResponseCode.SUCCESS && mResponse2.Code == ResponseCode.SUCCESS) { slat = mResponse1.Position.Latitude.ToString(); slng = mResponse1.Position.Longitude.ToString(); dlat = mResponse2.Position.Latitude.ToString(); dlng = mResponse2.Position.Longitude.ToString(); BookingDetailsResponse mResBooking = await mcab.BookCab(token, slat, slng); if (mResBooking.Code == ResponseCode.SUCCESS) { mLoadingDialog.Dismiss(); if (provider.Equals("Uber", StringComparison.InvariantCultureIgnoreCase)) { drivertext.Text = mResBooking.BookingData.DriverDetails.Name; cartype.Text = mResBooking.BookingData.VehicleDetails.Make + " " + mResBooking.BookingData.VehicleDetails.Model; carnumber.Text = mResBooking.BookingData.VehicleDetails.License_Plate; ImageLoader.Instance.DisplayImage(mResBooking.BookingData.DriverDetails.Picture_Url, mDriver); phonenumner = mResBooking.BookingData.DriverDetails.Phone_Number; } else { phonenumner = "8110020055"; } } else { } } sourcepos = new LatLng(Convert.ToDouble(slat), Convert.ToDouble(slng)); destpos = new LatLng(Convert.ToDouble(dlat), Convert.ToDouble(dlng)); setupGoogleMap(); } }
public WeatherResponse(GeoResponse geo, IForecastResponse weather) { this._geo = geo; this._weather = weather; }
private async Task SendCompletionMessageForCostEstimate(string source, string destination) { string slat, slng, dlat, dlng, token, mDisplay; slat = slng = dlng = dlat = null; var mUserMessage = new VoiceCommandUserMessage(); var mUserPrompt = new VoiceCommandUserMessage(); VoiceCommandResponse mResponseError; VoiceCommandContentTile mCabTile = new VoiceCommandContentTile(); CabsAPI mCabsApi = new CabsAPI(); GeoResponse mGeoResp; List <VoiceCommandContentTile> mCabTiles = new List <VoiceCommandContentTile>(); token = Windows.Storage.ApplicationData.Current.LocalSettings.Values["Token"].ToString(); if (destination.Equals("")) { await ShowProgressScreen("Insufficient Info"); mDisplay = "Sorry no destination provided Please enter a valid destination"; mUserMessage.DisplayMessage = mUserMessage.SpokenMessage = mDisplay; mResponseError = VoiceCommandResponse.CreateResponse(mUserMessage); } else { mGeoResp = await mCabsApi.GeoCodingResult(token, destination); if (mGeoResp.Code == ResponseCode.SUCCESS) { dlat = mGeoResp.Position.Latitude; dlng = mGeoResp.Position.Longitude; } else { mDisplay = "Destination not found"; mUserMessage.DisplayMessage = mUserMessage.SpokenMessage = mDisplay; mResponseError = VoiceCommandResponse.CreateResponse(mUserMessage); await voiceServiceConnection.ReportFailureAsync(mResponseError); } } mGeoResp = await mCabsApi.GeoCodingResult(token, source); if (mGeoResp.Code == ResponseCode.SUCCESS) { slat = mGeoResp.Position.Latitude; slng = mGeoResp.Position.Longitude; } else { mDisplay = "Source not found"; mUserMessage.DisplayMessage = mUserMessage.SpokenMessage = mDisplay; mResponseError = VoiceCommandResponse.CreateResponse(mUserMessage); await voiceServiceConnection.ReportFailureAsync(mResponseError); } string EstimatingCabsFromXtoY = "Getting cost Details from " + source + " to " + destination; await ShowProgressScreen(EstimatingCabsFromXtoY); CabsAPI api = new CabsAPI(); string loadingCabsFromXtoY = "Loading Details of cabs from " + source + " to " + destination; await ShowProgressScreen(loadingCabsFromXtoY); GeoResponse sResponse = await api.GeoCodingResult(token, source); GeoResponse dResponse = await api.GeoCodingResult(token, destination); PriceEstimateResponse pResponse = await api.GetEstimate(token, slat, slng, dlat, dlng); var userMessage = new VoiceCommandUserMessage(); var cabTiles = new List <VoiceCommandContentTile>(); List <CabEstimate> cabsAvaialble = pResponse.Estimates; CabEstimate cabSelected; if (cabsAvaialble == null) { string foundNoCabs = "Sorry No Cabs Found"; userMessage.DisplayMessage = foundNoCabs; userMessage.SpokenMessage = foundNoCabs; } else { string message = "Ok! I have found the following Cabs for you"; userMessage.DisplayMessage = message; userMessage.SpokenMessage = message; cabSelected = await AvailableList(cabsAvaialble, "Which cab do you want to book?", "Book the selected cab?"); var userPrompt = new VoiceCommandUserMessage(); VoiceCommandResponse response; string BookCabToDestination = "Booking " + cabSelected.Provider + " with " + cabSelected.Type + " from " + source + " to " + destination + " arriving in " + cabSelected.Eta + " with " + cabSelected.CurrentEstimate.LowRange + " to " + cabSelected.CurrentEstimate.HighRange + " cost estimation"; userPrompt.DisplayMessage = userPrompt.SpokenMessage = BookCabToDestination; var userReprompt = new VoiceCommandUserMessage(); string confirmBookCabToDestination = "Confirm booking"; userReprompt.DisplayMessage = userReprompt.SpokenMessage = confirmBookCabToDestination; response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, userReprompt, cabTiles); var voiceCommandConfirmation = await voiceServiceConnection.RequestConfirmationAsync(response); if (voiceCommandConfirmation != null) { if (voiceCommandConfirmation.Confirmed == true) { BookingDetailsResponse booking = await api.BookCab(token, sResponse.Position.Latitude, sResponse.Position.Longitude); string BookingCabToDestination = "Booking cab"; await ShowProgressScreen(BookingCabToDestination); var cabShow = new VoiceCommandContentTile(); cabShow.ContentTileType = VoiceCommandContentTileType.TitleWith68x68IconAndText; if (cabSelected.Provider.Equals("UBER")) { cabShow.Image = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///ContosoCabs.VoiceCommandService/img/uber.png")); } else { cabShow.Image = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///ContosoCabs.VoiceCommandService/img/ola.png")); } cabShow.Title = cabSelected.Type; cabShow.TextLine1 = "ETA : " + cabSelected.Eta; cabShow.TextLine2 = "Estimated Fare: " + cabSelected.CurrentEstimate.LowRange + "-" + cabSelected.CurrentEstimate.HighRange; cabShow.TextLine3 = "Call driver at " + booking.BookingData.DriverDetails.Phone_Number; cabTiles.Add(cabShow); var userMessage1 = new VoiceCommandUserMessage(); string BookCabInformation = "Cab booked. your cab driver " + booking.BookingData.DriverDetails.Name + "will be arriving shortly."; //Vehicle number :"+ booking.BookingData.VehicleDetails.License_Plate userMessage.DisplayMessage = userMessage.SpokenMessage = BookCabInformation; userMessage1.DisplayMessage = userMessage1.SpokenMessage = BookCabInformation; response = VoiceCommandResponse.CreateResponse(userMessage1, cabTiles); await voiceServiceConnection.ReportSuccessAsync(response); } else { userMessage = new VoiceCommandUserMessage(); string BookingCabToDestination = "Cancelling cab request..."; await ShowProgressScreen(BookingCabToDestination); string keepingTripToDestination = "Cancelled."; userMessage.DisplayMessage = userMessage.SpokenMessage = keepingTripToDestination; response = VoiceCommandResponse.CreateResponse(userMessage); await voiceServiceConnection.ReportSuccessAsync(response); } } } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); ShowLoader(true); { if (!IsInternet()) { await new MessageDialog("Seems you are not connected to the Internet").ShowAsync(); return; } else { MyMap.MapServiceToken = "YP9WTSzOHUo0dbahsH8J~J-K6u01dT98SF4uCCKpiwA~AnGaYM6yJxoLF1tGHEIXHFskGfwSRJTr1S5aO1dB-TCXjQ1ZX0xEWgeYslbC3Fov"; Geolocator locator = new Geolocator(); locator.DesiredAccuracyInMeters = 50; var position = await locator.GetGeopositionAsync(); await MyMap.TrySetViewAsync(position.Coordinate.Point, 10D); //mySlider.Value = 13; Arguments args = e.Parameter as Arguments; if (args.GetType(VoiceCommandType.BOOK_CHEAPEST_TO_DEST)) { string source = args.Values["source"].ToString(); string destination = args.Values["destination"].ToString(); CabsAPI api = new CabsAPI(); string token = Windows.Storage.ApplicationData.Current.LocalSettings.Values["Token"].ToString(); GeoResponse sResponse = await api.GeoCodingResult(token, source.ToLower()); GeoResponse dResponse = await api.GeoCodingResult(token, destination.ToLower()); if (dResponse.Code == ResponseCode.SUCCESS) { if (sResponse.Code == ResponseCode.SUCCESS) { Addroute(sResponse, dResponse, source, destination); Dictionary <string, object> Parameters = args.Values; List <CabEstimate> mCabs = new List <CabEstimate>(); mCabs = Parameters["list"] as List <CabEstimate>; ETAData.Text = mCabs[0].Eta; PriceData.Text = mCabs[0].CurrentEstimate.LowRange + "-" + mCabs[0].CurrentEstimate.HighRange; DistanceData.Text = mCabs[0].CurrentEstimate.Distance; TimeData.Text = mCabs[0].CurrentEstimate.Time; if (Parameters["source"] != null) { if (Parameters["source"].ToString() == null) { SrcBox.Text = "Microsoft Building 1 ".ToUpperInvariant(); } else { SrcBox.Text = Parameters["source"].ToString().ToUpperInvariant(); } } if (Parameters["destination"] != null) { DestBox.Text = Parameters["destination"].ToString().ToUpperInvariant(); } } else { await new MessageDialog("Error retrieving Geoposition").ShowAsync(); return; } } else { await new MessageDialog("Destiantion not found.").ShowAsync(); return; } } else if (args.GetType(VoiceCommandType.NO_VOICE)) { Dictionary <string, object> Parameters = args.Values; string source = Parameters["source"].ToString(); string destination = Parameters["destination"].ToString(); CabsAPI apiCus = new CabsAPI(); string tokenCus = Windows.Storage.ApplicationData.Current.LocalSettings.Values["Token"].ToString(); GeoResponse sResponse = await apiCus.GeoCodingResult(tokenCus, source.ToLower()); GeoResponse dResponse = await apiCus.GeoCodingResult(tokenCus, destination.ToLower()); Addroute(sResponse, dResponse, source, destination); ETAData.Text = Parameters["eta"].ToString(); PriceData.Text = Parameters["price"].ToString(); DistanceData.Text = Parameters["distance"].ToString(); TimeData.Text = Parameters["time"].ToString(); SrcBox.Text = Parameters["source"].ToString().ToUpperInvariant(); DestBox.Text = Parameters["destination"].ToString().ToUpperInvariant(); } else if (args.GetType(VoiceCommandType.BOOK_TO_CUSTOM_LOCATION)) { string source = args.Values["source"].ToString(); string destination = args.Values["location"].ToString(); CabsAPI apiCus = new CabsAPI(); string tokenCus = Windows.Storage.ApplicationData.Current.LocalSettings.Values["Token"].ToString(); GeoResponse sResponse = await apiCus.GeoCodingResult(tokenCus, source.ToLower()); GeoResponse dResponse = await apiCus.GeoCodingResult(tokenCus, destination.ToLower()); if (sResponse.Code == ResponseCode.SUCCESS) { if (dResponse.Code == ResponseCode.SUCCESS) { Addroute(sResponse, dResponse, source, destination); Dictionary <string, object> Parameters = args.Values; List <CabEstimate> DesiredCabs = new List <CabEstimate>(); DesiredCabs = Parameters["list"] as List <CabEstimate>; ETAData.Text = DesiredCabs[0].Eta; PriceData.Text = DesiredCabs[0].CurrentEstimate.LowRange + "-" + DesiredCabs[0].CurrentEstimate.HighRange; DistanceData.Text = DesiredCabs[0].CurrentEstimate.Distance; TimeData.Text = DesiredCabs[0].CurrentEstimate.Time; SrcBox.Text = "Microsoft Building 1 Gachibowli Hyderabad".ToUpperInvariant(); if (Parameters["location"] != null) { DestBox.Text = Parameters["location"].ToString().ToUpperInvariant(); } } else { await new MessageDialog("Destination not found.").ShowAsync(); return; } } else { await new MessageDialog("Error retrieving Geoposition").ShowAsync(); return; } } else if (args.GetType(VoiceCommandType.BOOK_ME_A_CAB_FROM_X_TO_Y)) { string source = args.Values["source"].ToString(); string destination = args.Values["destination"].ToString(); CabsAPI api = new CabsAPI(); string token = Windows.Storage.ApplicationData.Current.LocalSettings.Values["Token"].ToString(); PlacesResponse sResponse = await api.GetPlaceLocation(source.ToLower(), token); PlacesResponse dResponse = await api.GetPlaceLocation(destination.ToLower(), token); if (sResponse.Code == ResponseCode.SUCCESS) { if (dResponse.Code == ResponseCode.SUCCESS) { Addroute(sResponse, dResponse, source, destination); //AddMapIcon(Convert.ToDouble(sResponse.Location.Latitude), Convert.ToDouble(sResponse.Location.Longitude), source); //AddMapIcon(Convert.ToDouble(dResponse.Location.Latitude), Convert.ToDouble(dResponse.Location.Longitude), destination); //MapPolyline polyline = new MapPolyline(); //var coordinates = new List<BasicGeoposition>(); //var routeClient = new RouteClient(); //string sourceLoc = sResponse.Location.Latitude + "," + sResponse.Location.Longitude; //string destinationLoc = dResponse.Location.Latitude + "," + dResponse.Location.Longitude; //coordinates = await routeClient.route(sourceLoc, destinationLoc); //polyline.StrokeColor = Windows.UI.Color.FromArgb(128, 255, 0, 0); //polyline.StrokeThickness = 5; //polyline.Path = new Geopath(coordinates); //MyMap.MapElements.Add(polyline); //ReadSpeech(new MediaElement(), sResponse.Location.Latitude + " ok " + dResponse.Location.Longitude); PriceEstimateResponse pRespone = await api.GetEstimate(token, sResponse.Location.Latitude, sResponse.Location.Longitude, dResponse.Location.Latitude, dResponse.Location.Longitude); //ReadSpeech(new MediaElement(), pRespone.Estimates.First().Provider); SrcBox.Text = source; DestBox.Text = destination; //AddMapIcon(sResponse.Location.Latitude,) if (pRespone.Code == ResponseCode.SUCCESS) { ETAData.Text = pRespone.Estimates[1].Eta; PriceData.Text = pRespone.Estimates[1].CurrentEstimate.LowRange + "-" + pRespone.Estimates[1].CurrentEstimate.HighRange; DistanceData.Text = pRespone.Estimates[1].CurrentEstimate.Distance; TimeData.Text = pRespone.Estimates[1].CurrentEstimate.Time; } else { await new MessageDialog("Error in estimating prices").ShowAsync(); return; } } else { await new MessageDialog("Destination not found").ShowAsync(); return; } } else { await new MessageDialog("Error retrieving Geoposition").ShowAsync(); return; } } else if (args.GetType(VoiceCommandType.ESTIMATE_FROM)) { string source = args.Values["source"].ToString(); string destination = args.Values["destination"].ToString(); CabsAPI apiCus = new CabsAPI(); string token = Windows.Storage.ApplicationData.Current.LocalSettings.Values["Token"].ToString(); GeoResponse sResponse = await apiCus.GeoCodingResult(token, source.ToLower()); GeoResponse dResponse = await apiCus.GeoCodingResult(token, destination.ToLower()); Addroute(sResponse, dResponse, source, destination); Arguments eArgs = args as Arguments; SrcBox.Text = source; DestBox.Text = destination; ETAData.Text = eArgs.Values["eta"].ToString(); PriceData.Text = eArgs.Values["low"].ToString() + "-" + eArgs.Values["high"].ToString(); DistanceData.Text = eArgs.Values["distance"].ToString(); TimeData.Text = eArgs.Values["time"].ToString(); } } } ShowLoader(false); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (!IsInternet()) { await new MessageDialog("Seems you are not connected to the Internet").ShowAsync(); return; } else { progress.IsActive = true; speechRecognition = e.Parameter as SpeechRecognitionResult; mSource = this.SemanticInterpretation("source", speechRecognition); mDestination = this.SemanticInterpretation("destination", speechRecognition); MyMap.MapServiceToken = "YP9WTSzOHUo0dbahsH8J~J-K6u01dT98SF4uCCKpiwA~AnGaYM6yJxoLF1tGHEIXHFskGfwSRJTr1S5aO1dB-TCXjQ1ZX0xEWgeYslbC3Fov"; Geolocator locator = new Geolocator(); locator.DesiredAccuracyInMeters = 50; var position = await locator.GetGeopositionAsync(); await MyMap.TrySetViewAsync(position.Coordinate.Point, 10D); progress.IsActive = false; // mySlider.Value = 13; CabsAPI api = new CabsAPI(); GeoResponse sResponse = await api.GeoCodingResult(Token, mSource); GeoResponse dResponse = await api.GeoCodingResult(Token, mDestination); if (sResponse.Code == ResponseCode.SUCCESS) { if (dResponse.Code == ResponseCode.SUCCESS) { AddMapIcon(Convert.ToDouble(sResponse.Position.Latitude), Convert.ToDouble(sResponse.Position.Longitude), mSource); AddMapIcon(Convert.ToDouble(dResponse.Position.Latitude), Convert.ToDouble(dResponse.Position.Longitude), mDestination); MapPolyline polyline = new MapPolyline(); var coordinates = new List <BasicGeoposition>(); var routeClient = new RouteClient(); coordinates = await routeClient.route(mSource, mDestination); polyline.StrokeColor = Windows.UI.Color.FromArgb(128, 255, 0, 0); polyline.StrokeThickness = 5; polyline.Path = new Geopath(coordinates); MyMap.MapElements.Add(polyline); SrcBox.Text = mSource; DestBox.Text = mDestination; PriceEstimateResponse pResponse = await api.GetEstimate(Token, sResponse.Position.Latitude, sResponse.Position.Longitude, dResponse.Position.Latitude, dResponse.Position.Longitude); if (pResponse.Code == ResponseCode.SUCCESS) { CabsListView.ItemsSource = pResponse.Estimates; ReadSpeech(new MediaElement(), "Showing Estimated cab fare from" + mSource + "to" + mDestination); } else { await new MessageDialog("Error in estimating cabs").ShowAsync(); return; } } else { await new MessageDialog("Destination not found").ShowAsync(); return; } } else { await new MessageDialog("Source not found").ShowAsync(); return; } } }