public async Task <GeoCoordsResult> GetCoordsAsync(string name) { var result = new GeoCoordsResult { Success = false, Message = "Failed to get coordinates" }; var apiKey = _config["Keys:GMapsKey"]; var encodedName = WebUtility.UrlEncode(name); var url = $"https://maps.googleapis.com/maps/api/geocode/json?address={encodedName}&key={apiKey}"; var client = new HttpClient(); var json = await client.GetStringAsync(url); var results = JObject.Parse(json); var resources = results["results"][0]; if (!results["results"][0].HasValues) { result.Message = $"Could not find '{name}' as a location"; } else { var coords = resources["geometry"]["location"]; result.Latitude = (double)coords["lat"]; result.Longitude = (double)coords["lng"]; result.Success = true; result.Message = "Success"; } return(result); }
public async Task <IActionResult> Post(string tripName, [FromBody] StopViewModel vm) { try { if (ModelState.IsValid) { // map Stop newStop = Mapper.Map <Stop>(vm); // lookup the geocodes GeoCoordsResult coordsResult = await _coordsService.GetCoordsAsync(newStop.Name); if (coordsResult.Success == false) { _logger.LogError(coordsResult.Message); } else { newStop.Latitude = coordsResult.Latitude; newStop.Longitude = coordsResult.Longitude; // save to db _repository.AddStop(tripName, newStop, User.Identity.Name); if (await _repository.SaveChangesAsync()) { return(Created($"/api/trips/{tripName}/stops/{newStop.Name}", Mapper.Map <StopViewModel>(newStop))); } } } else { return(BadRequest(ModelState)); } } catch (Exception ex) { _logger.LogError("Failed to save Stop: {0}", ex); } return(BadRequest("Failed to save Stop")); }
public async Task <GeoCoordsResult> GetCoordsAsync(string name) { var result = new GeoCoordsResult { Success = false, Message = "Failed to get coordinates" }; var apiKey = _config["Keys:BingKey"]; var encodedName = WebUtility.UrlEncode(name); var url = $"http://dev.virtualearth.net/REST/v1/Locations?q={encodedName}&key={apiKey}"; var client = new HttpClient(); var json = await client.GetStringAsync(url); var results = JObject.Parse(json); var resources = results["resourceSets"][0]["resources"]; if (!results["resourceSets"][0]["resources"].HasValues) { result.Message = $"Could not find '{name}' as a location"; } else { var confidence = (string)resources[0]["confidence"]; if (confidence != "High") { result.Message = $"Could not find a confident match for '{name}' as a location"; } else { var coords = resources[0]["geocodePoints"][0]["coordinates"]; result.Latitude = (double)coords[0]; result.Longitude = (double)coords[1]; result.Success = true; result.Message = "Success"; } } return(result); }