public async Task <GeoResult> ResolveIpAsync(string ip, CancellationToken cancellationToken = new CancellationToken()) { if (String.IsNullOrEmpty(ip) || (!ip.Contains(".") && !ip.Contains(":"))) { return(null); } ip = ip.Trim(); if (ip.IsPrivateNetwork()) { return(null); } var cacheValue = await _localCache.GetAsync <GeoResult>(ip).AnyContext(); if (cacheValue.HasValue) { return(cacheValue.Value); } GeoResult result = null; var database = await GetDatabaseAsync(cancellationToken).AnyContext(); if (database == null) { return(null); } try { if (database.TryCity(ip, out var city) && city?.Location != null) { result = new GeoResult { Latitude = city.Location.Latitude, Longitude = city.Location.Longitude, Country = city.Country.IsoCode, Level1 = city.MostSpecificSubdivision.IsoCode, Locality = city.City.Name }; } await _localCache.SetAsync(ip, result).AnyContext(); return(result); } catch (Exception ex) { if (ex is GeoIP2Exception) { if (_logger.IsEnabled(LogLevel.Trace)) { _logger.LogTrace(ex, ex.Message); } await _localCache.SetAsync <GeoResult>(ip, null).AnyContext(); } else if (_logger.IsEnabled(LogLevel.Error)) { _logger.LogError(ex, "Unable to resolve geo location for ip: {IP}", ip); } return(null); } }
private void fetch() { Response.Clear(); SpotInfo sinfo = new SpotInfo(); String key = Request["key"]; sinfo.Address = key; Geocoder geo = new Geocoder(); GeoResult result = geo.GetGeoResult(sinfo); JsonObject jobj = new JsonObject(); if (GeoResultStatus.OK.Equals(result.Status))//@since 0.1.1 { jobj.NameValuePair.Add(new JsonObject.nvpair() { Name = "lat", Value = result.Results[0].Geometry.Location.Lat }); jobj.NameValuePair.Add(new JsonObject.nvpair() { Name = "lng", Value = result.Results[0].Geometry.Location.Lng }); } AjaxResponse jresponse = new AjaxResponse(); jresponse.Status = "OK"; jresponse.RawData = jobj; jresponse.Msg = "lat, lng of " + key; Response.Write(jresponse.ToString()); Response.ContentType = "application/json"; }
public static bool TryParse(string input, out GeoResult result) { result = null; if (String.IsNullOrEmpty(input)) { return(false); } string[] parts = input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { return(false); } if (!Double.TryParse(parts[0].Trim(), out double latitude) || Double.IsNaN(latitude) || Double.IsInfinity(latitude)) { return(false); } if (!Double.TryParse(parts[1].Trim(), out double longitude) || Double.IsNaN(longitude) || Double.IsInfinity(longitude)) { return(false); } result = new GeoResult { Latitude = latitude, Longitude = longitude }; return(true); }
public void PostAndDeleteTests() { if (!_redisConnectionString.IsNotNullOrEmpty()) { return; } var rest = new Rest(_redisConnectionString); var testPath1 = "home:test1"; var testPath2 = "home:test2"; var testData = new GeoResult() { City = "London", Country_Code = "GB", Country_Name = "United Kingdom" }; var testDataInStream = StringUtils.GenerateStreamFromString(testData.JsonSerialize()); var result1 = rest.Post <GeoResult>(testPath1, testData); Assert.True(result1?.City == "London"); Assert.True(rest.Delete <bool>(testPath1)); var result2 = rest.Post <Stream>(testPath2, testDataInStream); Assert.True(result2?.Length > 0); Assert.True(rest.Delete <bool>(testPath2)); }
public async System.Threading.Tasks.Task <ActionResult> CustomerLocationAsync(int id) { Customer customer = db.Customers.Find(id); GeoCoderToFindCustomerLocation geoCoderToFindCustomerLocation = new GeoCoderToFindCustomerLocation(); var splitAddress = customer.StreetAddress.Split(new[] { ' ' }, 4); var finalAddress = string.Join("+", splitAddress); finalAddress += ",+" + customer.City + ",+" + customer.State; geoCoderToFindCustomerLocation.address = finalAddress; string url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + geoCoderToFindCustomerLocation.address + "&key=" + PrivateKeys.key1; HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(url); string jsonResult = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { GeoResult postManJSON = JsonConvert.DeserializeObject <GeoResult>(jsonResult); geoCoderToFindCustomerLocation.longit = postManJSON.results[0].geometry.location.lng; geoCoderToFindCustomerLocation.latit = postManJSON.results[0].geometry.location.lat; geoCoderToFindCustomerLocation.fullNameAndAddressToPutOnMarker = customer.FirstName + " " + customer.LastName; geoCoderToFindCustomerLocation.fullNameAndAddressToPutOnMarker += ", " + customer.StreetAddress + ", " + customer.City + ", " + customer.State + ", " + customer.ZipCode; return(View(geoCoderToFindCustomerLocation)); } return(View()); }
// PUT api/GeoResult/5 public IHttpActionResult PutGeoResult(int id, GeoResult georesult) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != georesult.Id) { return(BadRequest()); } db.Entry(georesult).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!GeoResultExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task <IActionResult> All() { var items = await UnitOfWork.Repository <GeoData>() .GetListAsync(); return(Ok(items.Select(obj => GeoResult.Create(obj)))); }
public override async Task EventBatchProcessingAsync(ICollection <EventContext> contexts) { var geoGroups = contexts.GroupBy(c => c.Event.Geo); foreach (var group in geoGroups) { GeoResult result; if (GeoResult.TryParse(group.Key, out result) && result.IsValid()) { group.ForEach(c => UpdateGeoAndlocation(c.Event, result, false)); continue; } // The geo coordinates are all the same, set the location from the result of any of the ip addresses. if (!String.IsNullOrEmpty(group.Key)) { var ips = group.SelectMany(c => c.Event.GetIpAddresses()).Union(new[] { group.First().EventPostInfo?.IpAddress }).Distinct(); result = await GetGeoFromIpAddressesAsync(ips).AnyContext(); group.ForEach(c => UpdateGeoAndlocation(c.Event, result)); continue; } // Each event could be a different user; foreach (var context in group) { var ips = context.Event.GetIpAddresses().Union(new[] { context.EventPostInfo?.IpAddress }); result = await GetGeoFromIpAddressesAsync(ips).AnyContext(); UpdateGeoAndlocation(context.Event, result); } } }
private void UpdateGeoAndLocation(PersistentEvent ev, GeoResult result, bool isValidLocation = true) { ev.Geo = result?.ToString(); if (result != null && isValidLocation) { ev.SetLocation(result.ToLocation()); } else { ev.Data.Remove(Event.KnownDataKeys.Location); } }
async Task <bool> GeoLocation(string location) { locationList.Clear(); GeoResult result = await rest.GetGeoResult(location); if (result != null) { if (result.results.Count > 0) { foreach (var item in result.results) { var cell = new TextCell() { Text = item.formatted_address, }; cell.Tapped += (sender, e) => { double lat = item.geometry.location.lat; double lng = item.geometry.location.lng; if (isHomeSelected) { parent.originPos = new Position(lat, lng); parent.origin = item.formatted_address; parent.isHomeSet = 2; } else { parent.destinationPos = new Position(lat, lng); parent.destination = item.formatted_address; parent.isDestinationSet = 2; } Navigation.PopModalAsync(); }; locationList.Add(cell); } return(true); } else { Debug.WriteLine("Could not get info of home address"); return(false); } } else { Debug.WriteLine("Geocoder returns no results"); return(false); } }
public IHttpActionResult DeleteGeoResult(int id) { GeoResult georesult = db.GeoResults.Find(id); if (georesult == null) { return(NotFound()); } db.GeoResults.Remove(georesult); db.SaveChanges(); return(Ok(georesult)); }
public IHttpActionResult PostGeoResult(GeoResult georesult) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //Get user ID //------------------------------------ var currentUserId = User.Identity.GetUserId(); var currentTeamName = manager.FindById(currentUserId).TeamName; //Set user information so we dont have to send it from javascript. Seems like a hacker could hack the guid being sent through ajax. //------------------------------------ georesult.TeamName = currentTeamName; georesult.UserId = currentUserId; georesult.Location = DbGeography.FromText("POINT(" + georesult.Longitude + " " + georesult.Latitude + ")"); //Get Current Week //------------------------------------ var weekId = db.Week.First().Week_Id; //Get GeoMaster by week //---------------------- var geoMasters = db.GeoMasters.Where(x => x.Week == weekId).FirstOrDefault(); //Get distance between the posted users bullshit guess, and then the real answer //---------------------- var distance = georesult.Location.Distance(geoMasters.Location); distance = distance * 0.000621371; decimal distaanceAway = (decimal)(distance); distaanceAway = Math.Round(distaanceAway, 3); //Add the distance to the geoResult model //---------------------- georesult.DistanceAway = distaanceAway; db.GeoResults.Add(georesult); db.SaveChanges(); return(CreatedAtRoute("DefaultApi", new { id = georesult.Id }, georesult)); }
public async Task <IActionResult> Get(string id) { if (ObjectId.TryParse(id, out ObjectId oid)) { var item = await UnitOfWork.Repository <GeoData>() .GetByIdAsync(oid); if (item == null) { return(NotFound(id)); } return(Ok(GeoResult.Create(item))); } return(BadRequest()); }
public async Task ReverseGeocodeLookup() { var service = GetService <IGeocodeService>(); if (service is NullGeocodeService) { return; } Assert.True(GeoResult.TryParse(GREEN_BAY_COORDINATES, out var coordinates)); var location = await service.ReverseGeocodeAsync(coordinates.Latitude.GetValueOrDefault(), coordinates.Longitude.GetValueOrDefault()); Assert.Equal("US", location?.Country); Assert.Equal("WI", location?.Level1); Assert.Equal("Brown County", location?.Level2); Assert.Equal("Green Bay", location?.Locality); }
public static Location ToLocation(this GeoResult result) { if (result == null) { return(null); } if (String.IsNullOrEmpty(result.Country) && String.IsNullOrEmpty(result.Level1) && String.IsNullOrEmpty(result.Level2) && String.IsNullOrEmpty(result.Locality)) { return(null); } return(new Location { Country = result.Country?.Trim(), Level1 = result.Level1?.Trim(), Level2 = result.Level2?.Trim(), Locality = result.Locality?.Trim() }); }
public override async Task HandleItemAsync(WorkItemContext context) { var workItem = context.GetData <SetLocationFromGeoWorkItem>(); GeoResult result; if (!GeoResult.TryParse(workItem.Geo, out result)) { return; } var location = await _cacheClient.GetAsync <Location>(workItem.Geo, null).AnyContext(); if (location == null) { try { result = await _geocodeService.ReverseGeocodeAsync(result.Latitude.GetValueOrDefault(), result.Longitude.GetValueOrDefault()).AnyContext(); location = result.ToLocation(); await _metricsClient.CounterAsync(MetricNames.UsageGeocodingApi).AnyContext(); } catch (Exception ex) { Logger.Error().Exception(ex).Message($"Error occurred looking up reverse geocode: {workItem.Geo}").Write(); } } if (location == null) { return; } await _cacheClient.SetAsync(workItem.Geo, location, TimeSpan.FromDays(3)).AnyContext(); var ev = await _eventRepository.GetByIdAsync(workItem.EventId).AnyContext(); if (ev == null) { return; } ev.SetLocation(location); await _eventRepository.SaveAsync(ev).AnyContext(); }
// GET: Weather public ActionResult Index(string location, string dateTime) { ViewBag.Controller = "Weather"; if (!User.Identity.IsAuthenticated) { return(this.RedirectToAction("Index", "Home", new { location = location, dateTime = dateTime })); } if (location != null) // empty string is acceptable { TempDataDictionary data = TempData; TempData["geoReport"] = APIHelper.GetGeoLocation(ref data, location, dateTime); TempData["weatherReport"] = APIHelper.GetWeatherForecast(ref data, TempData["geoReport"] as GeoReport); TempData = data; Query query = new Query() { location = TempData["location"] as String, dateTime = TempData["dateTime"] as String }; GeoResult geoResult = new GeoResult() { query = query, geoJson = TempData["geoJson"] as String }; WeatherResult weatherResult = new WeatherResult() { query = query, weatherJson = TempData["weatherJson"] as String }; Session["query"] = query; Session["geoResult"] = geoResult; Session["weatherResult"] = weatherResult; } List <Query> pastQueries = db.queries.ToList(); TempData["pastQueries"] = pastQueries; return(View(pastQueries)); }
// GET: Weather/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Query query = db.queries.Find(id); GeoResult geoResult = db.geoResults.First(g => g.query.Id == query.Id); WeatherResult weatherResult = db.weatherResults.First(w => w.query.Id == query.Id); string geoJson = geoResult.geoJson; string weatherJson = weatherResult.weatherJson; TempData["geoReport"] = JsonConvert.DeserializeObject <GeoReport>(geoJson); TempData["weatherReport"] = JsonConvert.DeserializeObject <WeatherReport>(weatherJson); Session["query"] = query; return(this.RedirectToAction("Index")); }
public static GeoAddress[] ConvertGeoResultToAddresses(this GeoResult result) { if (result.Status == ResultStatus.OK) { return(result.Results .Where(r => r.Formatted_address.HasValue() && r.Geometry != null && r.Geometry.Location != null && r.Geometry.Location.Lng != 0 && r.Geometry.Location.Lat != 0 && (r.AddressComponentTypes.Any(type => type == AddressComponentType.Street_address) || (r.Types.Any(t => _otherTypesAllowed.Any(o => o.ToLower() == t.ToLower()))))) .Select(ConvertGeoObjectToAddress) .ToArray()); } else { return(new GeoAddress[0]); } }
public async Task <IActionResult> List() { var oid = GetUserId(); if (oid.HasValue) { var items = await UnitOfWork.Repository <GeoData>() .GetListAsync(o => o.UserId == oid.Value); if (items.Count() == 0) { return(NotFound()); } var result = items.Select(obj => GeoResult.Create(obj)); return(Ok(result)); } return(BadRequest()); }
public async Task <IActionResult> FilterPartnersByRating(MapView mapView, GeoResult geoResult) { ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id"); var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); var viewerInDb = _context.Partners.Where(m => m.IdentityUserId == userId).FirstOrDefault(); var applicationDbContext = _context.Partners.Include(p => p.IdentityUser); mapView.partner = viewerInDb; var rating = _context.RateServices.Where(r => r.Rating > 1).First(); var ds = _context.DonateServices.Where(s => s.DonateServiceId == rating.DonateServiceId).First(); //mapView.donateService = ds; var part = _context.Partners.Where(p => p.PartnerId == ds.PartnerId); //var coords = part.PartnerLat + "," + part.PartnerLong; //var coor = part.PartnerLat.First(); //var coorLang = part.PartnerLong; //var part = _context.Partners.Where(p => p.PartnerId == ds.PartnerId); return(View(await part.ToListAsync())); }
public async Task <IActionResult> GetByLocation(double lon, double lat, double distance, string[] tag = null) { var oid = GetUserId(); if (!oid.HasValue) { return(BadRequest()); } var repository = UnitOfWork.GeoRepository <GeoData>(); var items = await repository.GetByLocationAsync(oid.Value, lon, lat, distance, tag); if (items.Count() == 0) { return(NotFound()); } var result = items.Select(obj => GeoResult.Create(obj)); return(Ok(result)); }
public override Task EventBatchProcessingAsync(ICollection <EventContext> contexts) { var geoGroups = contexts.GroupBy(c => c.Event.Geo); var tasks = new List <Task>(); foreach (var group in geoGroups) { if (GeoResult.TryParse(group.Key, out var result) && result.IsValid()) { group.ForEach(c => UpdateGeoAndLocation(c.Event, result, false)); continue; } // The geo coordinates are all the same, set the location from the result of any of the ip addresses. if (!String.IsNullOrEmpty(group.Key)) { var ips = group.SelectMany(c => c.Event.GetIpAddresses()).Union(new[] { group.First().EventPostInfo?.IpAddress }).Distinct().ToList(); if (ips.Count > 0) { tasks.Add(UpdateGeoInformationAsync(group, ips)); } continue; } // Each event in the group could be a different user; foreach (var context in group) { var ips = context.Event.GetIpAddresses().Union(new[] { context.EventPostInfo?.IpAddress }).ToList(); if (ips.Count > 0) { tasks.Add(UpdateGeoInformationAsync(context, ips)); } } } return(Task.WhenAll(tasks)); }
public async System.Threading.Tasks.Task <ActionResult> CustomerLocationAsync(int id) { Customer customer = context.Customer.Find(id); GeoCoderAddress geoCoderInfo = new GeoCoderAddress(); var splitAddress = customer.StreetAddress.Split(new[] { ' ' }, 4); geoCoderInfo.address += splitAddress[0] + "+" + splitAddress[1] + "+" + splitAddress[2] + "+" + splitAddress[3] + ",+" + customer.City + ",+" + customer.State; string url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + geoCoderInfo.address + "&key=" + PrivateKeys.key1; HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(url); string jsonResult = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { GeoResult postManJSON = JsonConvert.DeserializeObject <GeoResult>(jsonResult); geoCoderInfo.latitudeValue = postManJSON.results[0].geometry.location.lat; geoCoderInfo.longitudeValue = postManJSON.results[0].geometry.location.lng; return(View(geoCoderInfo)); } return(View()); }
public ActionResult Create() //[Bind(Include = "Id,location")] Query query { Query query = Session["query"] as Query; GeoResult geoResult = Session["geoResult"] as GeoResult; WeatherResult weatherResult = Session["weatherResult"] as WeatherResult; if (query != null && geoResult != null && weatherResult != null && ModelState.IsValid) { db.queries.Add(query); db.geoResults.Add(geoResult); db.weatherResults.Add(weatherResult); db.SaveChanges(); Session.Remove("query"); Session.Remove("geoResult"); Session.Remove("weatherResult"); TempData["errorMessage"] = "Data saved successfully."; return(this.RedirectToAction("Index", "Weather")); } TempData["errorMessage"] = "Could not save data."; return(this.RedirectToAction("Index", "Weather")); }
public async Task <IHttpActionResult> GetSubmitEvent(string projectId = null, int version = 2, string type = null, [UserAgent] string userAgent = null, [QueryStringParameters] IDictionary <string, string[]> parameters = null) { if (parameters == null || parameters.Count == 0) { return(StatusCode(HttpStatusCode.OK)); } if (projectId == null) { projectId = Request.GetDefaultProjectId(); } // must have a project id if (String.IsNullOrEmpty(projectId)) { return(BadRequest("No project id specified and no default project was found.")); } var project = await GetProjectAsync(projectId); if (project == null) { return(NotFound()); } // TODO: We could save some overhead if we set the project in the overage handler... // Set the project for the configuration response filter. Request.SetProject(project); string contentEncoding = Request.Content.Headers.ContentEncoding.ToString(); var ev = new Event { Type = !String.IsNullOrEmpty(type) ? type : Event.KnownTypes.Log }; string identity = null; string identityName = null; var exclusions = project.Configuration.Settings.GetStringCollection(SettingsDictionary.KnownKeys.DataExclusions).ToList(); foreach (var kvp in parameters.Where(p => !String.IsNullOrEmpty(p.Key) && !p.Value.All(String.IsNullOrEmpty))) { switch (kvp.Key.ToLower()) { case "type": ev.Type = kvp.Value.FirstOrDefault(); break; case "source": ev.Source = kvp.Value.FirstOrDefault(); break; case "message": ev.Message = kvp.Value.FirstOrDefault(); break; case "reference": ev.ReferenceId = kvp.Value.FirstOrDefault(); break; case "date": DateTimeOffset dtValue; if (DateTimeOffset.TryParse(kvp.Value.FirstOrDefault(), out dtValue)) { ev.Date = dtValue; } break; case "value": decimal decValue; if (Decimal.TryParse(kvp.Value.FirstOrDefault(), out decValue)) { ev.Value = decValue; } break; case "geo": GeoResult geo; if (GeoResult.TryParse(kvp.Value.FirstOrDefault(), out geo)) { ev.Geo = geo.ToString(); } break; case "tags": ev.Tags.AddRange(kvp.Value.SelectMany(t => t.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)).Distinct()); break; case "identity": identity = kvp.Value.FirstOrDefault(); break; case "identity.name": identityName = kvp.Value.FirstOrDefault(); break; default: if (kvp.Key.AnyWildcardMatches(exclusions, true)) { continue; } if (kvp.Value.Length > 1) { ev.Data[kvp.Key] = kvp.Value; } else { ev.Data[kvp.Key] = kvp.Value.FirstOrDefault(); } break; } } ev.SetUserIdentity(identity, identityName); try { await _eventPostQueue.EnqueueAsync(new EventPostInfo { MediaType = Request.Content.Headers.ContentType?.MediaType, CharSet = Request.Content.Headers.ContentType?.CharSet, ProjectId = projectId, UserAgent = userAgent, ApiVersion = version, Data = Encoding.UTF8.GetBytes(ev.ToJson(Formatting.None, _jsonSerializerSettings)), ContentEncoding = contentEncoding, IpAddress = Request.GetClientIpAddress() }, _storage); } catch (Exception ex) { _logger.Error().Exception(ex) .Message("Error enqueuing event post.") .Project(projectId) .Identity(ExceptionlessUser?.EmailAddress) .Property("User", ExceptionlessUser) .SetActionContext(ActionContext) .WriteIf(projectId != Settings.Current.InternalProjectId); return(StatusCode(HttpStatusCode.InternalServerError)); } return(StatusCode(HttpStatusCode.OK)); }
public BreatheKlerePage() { InitializeComponent(); // MapTypes var mapTypeValues = new List <MapType>(); rest = new RESTService(); foreach (var mapType in Enum.GetValues(typeof(MapType))) { mapTypeValues.Add((MapType)mapType); } if (App.Current.Properties.ContainsKey("DID")) { DID = App.Current.Properties["DID"].ToString(); } isFirstLaunch = true; map.MapType = mapTypeValues[0]; map.MyLocationEnabled = true; map.IsTrafficEnabled = true; map.IsIndoorEnabled = false; map.UiSettings.CompassEnabled = true; map.UiSettings.RotateGesturesEnabled = true; map.UiSettings.MyLocationButtonEnabled = true; map.UiSettings.IndoorLevelPickerEnabled = false; map.UiSettings.ScrollGesturesEnabled = true; map.UiSettings.TiltGesturesEnabled = false; map.UiSettings.ZoomControlsEnabled = true; map.UiSettings.ZoomGesturesEnabled = true; var entryGesture = new TapGestureRecognizer(); entryGesture.Tapped += Home_Focused; entryAddress.GestureRecognizers.Add(entryGesture); var destinationGesture = new TapGestureRecognizer(); destinationGesture.Tapped += Destination_Focused; destinationAddress.GestureRecognizers.Add(destinationGesture); startPin = new Pin { Type = PinType.SavedPin, Label = "Start Point", }; endPin = new Pin { Type = PinType.Generic, Label = "End Point", }; // Map Clicked map.MapClicked += async(sender, e) => { if (mapMode == 2) { destinationPos = e.Point; endPin.Position = e.Point; GeoResult result = await rest.GetGeoResult(e.Point.Latitude.ToString() + ',' + e.Point.Longitude.ToString()); if (result != null) { destinationAddress.Text = result.results[0].formatted_address; destination = result.results[0].formatted_address; endPin.Address = result.results[0].formatted_address; } if (map.Pins.Contains(endPin)) { map.Pins.Remove(endPin); } map.Pins.Add(endPin); isDestinationSet = 2; await CalculateRoute(); } else if (mapMode == 1) { originPos = e.Point; startPin.Position = e.Point; GeoResult result = await rest.GetGeoResult(e.Point.Latitude.ToString() + ',' + e.Point.Longitude.ToString()); if (result != null) { origin = result.results[0].formatted_address; entryAddress.Text = result.results[0].formatted_address; startPin.Address = result.results[0].formatted_address; } if (map.Pins.Contains(startPin)) { map.Pins.Remove(startPin); } map.Pins.Add(startPin); isHomeSet = 2; } mapMode = 0; }; }
async protected override void OnAppearing() { base.OnAppearing(); NavigationPage.SetHasNavigationBar(this, false); try { var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location); if (status != PermissionStatus.Granted) { if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location)) { await DisplayAlert("Need location", "Gunna need that location", "OK"); } var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location); //Best practice to always check that the key exists if (results.ContainsKey(Permission.Location)) { status = results[Permission.Location]; } } if (status == PermissionStatus.Granted) { if (Utils.IsLocationAvailable() && isFirstLaunch) { originPos = await Utils.GetPosition(); currentPos = originPos.Latitude + "," + originPos.Longitude; map.MoveToRegion(MapSpan.FromCenterAndRadius(originPos, Distance.FromMeters(5000))); GeoResult result = await rest.GetGeoResult(currentPos); if (result != null) { origin = result.results[0].formatted_address; } else { origin = currentPos; } isHomeSet = 2; } } else { await DisplayAlert("Location Denied", "Can not continue, try again.", "OK"); } if (isFirstLaunch) { isFirstLaunch = false; } } catch (Exception ex) { await DisplayAlert("Error", ex.Message, "OK"); } //Setting up the locations if (isHomeSet > 0) { if (isHomeSet == 1) { var result = await rest.GetGeoResult(origin); if (result != null) { originPos = new Position(result.results[0].geometry.location.lat, result.results[0].geometry.location.lng); } } entryAddress.Text = origin; startPin.Address = origin; if (map.Pins.Contains(startPin)) { map.Pins.Remove(startPin); } startPin.Position = originPos; map.Pins.Add(startPin); } if (isDestinationSet > 0) { if (isDestinationSet == 1) { var result = await rest.GetGeoResult(destination); if (result != null) { destinationPos = new Position(result.results[0].geometry.location.lat, result.results[0].geometry.location.lng); } } destinationAddress.Text = destination; endPin.Address = destination; if (map.Pins.Contains(endPin)) { map.Pins.Remove(endPin); } endPin.Position = destinationPos; map.Pins.Add(endPin); } if (isHomeSet > 0 && isDestinationSet > 0) { await CalculateRoute(); } }
/// <summary> /// Search addresses for the specified name, latitude and longitude. /// </summary> /// <param name='name'> /// Search criteria, address fragment. Cannot be null or empty /// </param> /// <param name='latitude'> /// Latitude /// </param> /// <param name='longitude'> /// Longitude /// </param> /// <param name="geoResult"> /// /// </param> public Address[] Search(string name, double?latitude, double?longitude, string currentLanguage, GeoResult geoResult = null) { if (name.IsNullOrEmpty()) { return(new Address[0]); } var geoCodingService = new Geocoding(_geocoder, _appSettings, _popularAddressProvider, _logger); var allResults = geoCodingService.Search(name, latitude, longitude, currentLanguage, geoResult); return(ProcessAddresses(name, allResults, latitude, longitude, currentLanguage, geoResult)); }
private Address[] ProcessAddresses(string name, IEnumerable <Address> allResults, double?latitude, double?longitude, string currentLanguage, GeoResult geoResult = null) { IEnumerable <Address> addressesGeocode; IEnumerable <Address> addressesPlaces = new Address[0]; // ReSharper disable CompareOfFloatsByEqualityOperator if (latitude.HasValue && longitude.HasValue && (latitude.Value != 0 || longitude.Value != 0)) // ReSharper restore CompareOfFloatsByEqualityOperator { addressesGeocode = allResults .OrderBy(adrs => Position.CalculateDistance(adrs.Latitude, adrs.Longitude, latitude.Value, longitude.Value)); } else { addressesGeocode = allResults; } var term = name.FirstOrDefault(); int n; if (!int.TryParse(term + "", out n)) { var nearbyService = new Places(_placeProvider, _appSettings, _popularAddressProvider); addressesPlaces = nearbyService.SearchPlaces(name, latitude, longitude, currentLanguage); } return(addressesGeocode .Take(20) .Concat(addressesPlaces.Take(20)) .OrderBy(p => AddressSortingHelper.GetRelevance(p, name, latitude, longitude)) .ToArray()); }