public ActionResult ClosestLocation(int?countryId, float latitude, float longitude) { try { // If the country is not specified then use the current context. var country = countryId == null ? ActivityContext.Location.Country : _locationQuery.GetCountry(countryId.Value); // Get the closest locality. var locality = _locationQuery.GetClosestLocality(country, new GeoCoordinates(latitude, longitude)); if (locality == null) { return(ResolveLocation(countryId, null)); } // Return the first postal suburb in the first postal code. LocationReference locationReference; var postalCodes = _locationQuery.GetPostalCodes(locality).OrderBy(pc => pc.Postcode).ToList(); if (postalCodes.Count == 0) { locationReference = new LocationReference(locality); return(ResolveLocation(locationReference.ToString(), locationReference.ToString())); } var postalSuburbs = _locationQuery.GetPostalSuburbs(postalCodes[0]).OrderBy(ps => ps.Name).ToList(); if (postalSuburbs.Count == 0) { locationReference = new LocationReference(postalCodes[0]); return(ResolveLocation(locationReference.ToString(), locationReference.ToString())); } locationReference = new LocationReference(postalSuburbs[0]); return(ResolveLocation(locationReference.ToString(), locationReference.ToString())); } catch (Exception) { return(ResolveLocation(countryId, null)); } }