protected virtual void HandleTimeCommand(CommandMatch cmd, IChannelMessageEventArgs msg) { string location = ((string)cmd.Arguments[0]).Trim(); if (location.Length == 0) { location = Config.DefaultLocation; } string aliasedLocation; if (Config.LocationAliases.TryGetValue(location, out aliasedLocation)) { location = aliasedLocation; } // obtain location var client = new GeoNamesClient(Config.GeoNames); GeoName loc = client.GetFirstGeoName(location).SyncWait(); if (loc == null) { ConnectionManager.SendChannelMessage(msg.Channel, $"{msg.SenderNickname}: GeoNames cannot find that location!"); return; } // obtain timezone GeoTimeZoneResult geoTimeZoneResult = client.GetTimezone(loc.Latitude, loc.Longitude).SyncWait(); // find actual date/time using our zone data DateTimeZone zone = TimeZoneProvider.GetZoneOrNull(geoTimeZoneResult.TimezoneID); if (zone == null) { ConnectionManager.SendChannelMessage(msg.Channel, $"{msg.SenderNickname}: I don't know the timezone {geoTimeZoneResult.TimezoneID}."); return; } ZonedDateTime time = SystemClock.Instance.GetCurrentInstant().InZone(zone); bool lucky = cmd.CommandName.StartsWith("l"); ConnectionManager.SendChannelMessage( msg.Channel, lucky ? $"{msg.SenderNickname}: The time there is {time:yyyy-MM-dd HH:mm:ss}." : $"{msg.SenderNickname}: The time in {loc.Name} is {time:yyyy-MM-dd HH:mm:ss}." ); }
public void DistanceTo_WrapsAroundLongitudeCorrectly() { var a = new GeoName { Latitude = 51.377020, Longitude = 179.431888, Name = "Amchitka Island" }; var b = new GeoName { Latitude = 51.272322, Longitude = -179.134396, Name = "Amatignak Island" }; var actual = 100300; // +/- a bit; checked with http://www.freemaptools.com/measure-distance.htm and (classic) google maps measure tool var result = a.DistanceTo(b); Assert.AreEqual(actual, result, actual * .0005); // All we want is to be within .05% of the "actual" (according to our own measurements) value }
private void Initialize(Stream Input, bool MajorPlacesOnly) { List<GeoName> Places = new List<GeoName>(); using (StreamReader db = new StreamReader(Input)) { string Line; while (!db.EndOfStream && (Line = db.ReadLine()) != null) { var Place = new GeoName(Line); if (!MajorPlacesOnly || Place.FeatureClass != GeoFeatureClass.City) Places.Add(Place); } } Tree = new KDTree<GeoName>(Places.ToArray()); }
private Dictionary <string, List <GeoName> > ReadCsv() { byName = new Dictionary <string, List <GeoName> >(); using (StreamReader streamReader = new StreamReader("data/canada_usa_cities.tsv")) using (CsvReader csvReader = new CsvReader(streamReader, CultureInfo.InvariantCulture)) { csvReader.Configuration.Delimiter = "\t"; csvReader.Configuration.HasHeaderRecord = true; csvReader.Configuration.BadDataFound = null; csvReader.Read(); csvReader.ReadHeader(); while (csvReader.Read()) { GeoName thisGeoName = new GeoName { City = csvReader.GetField <string>("name"), State = csvReader.GetField <string>("admin1"), Country = csvReader.GetField <string>("country"), AlternateNames = csvReader.GetField <string>("alt_name").Split(','), Latitude = csvReader.GetField <double>("lat"), Longitude = csvReader.GetField <double>("long") }; if (thisGeoName.AlternateNames[0] == "") { thisGeoName.AlternateNames = Array.Empty <string>(); } List <GeoName> thisList; if (byName.ContainsKey(thisGeoName.City)) { byName.TryGetValue(thisGeoName.City, out thisList); thisList.Add(thisGeoName); } else { thisList = new List <GeoName> { thisGeoName }; byName.Add(thisGeoName.City, thisList); } } } return(byName); }
public GeoName[] GetFirstLike(string like, double?latitude, double?longitude) { List <GeoName> result = new List <GeoName>(); foreach (string key in byName.Keys) { if (key.Contains(like)) { List <GeoName> thisGeoNameList; byName.TryGetValue(key, out thisGeoNameList); GeoName thisGeoName = thisGeoNameList.First(); CalculateScore(thisGeoName, key, like, latitude, longitude); result.Add(thisGeoName); } } return(OrderAndTruncateList(result)); }
public void DistanceTo_ReturnsCorrectResult() { //http://en.wikipedia.org/w/index.php?title=Great-circle_distance&oldid=414838052 var a = new GeoName { Latitude = 36.1172, Longitude = -86.6672 }; //Nashville International Airport (BNA) in Nashville, TN, USA: N 36°7.2', W 86°40.2' var b = new GeoName { Latitude = 33.9344, Longitude = -118.4 }; //Los Angeles International Airport (LAX) in Los Angeles, CA, USA: N 33°56.4', W 118°24.0' var x1 = a.DistanceTo(b); // DistanceTo(GeoName) overload var x2 = a.DistanceTo(b.Latitude, b.Longitude); // DistanceTo(double, double) overload var actual = 2887260; // According to wikipedia //We use a slightly different radius of the earth than the wikipedia example uses (6372.8 in wikipedia vs. 6371 which is most commonly used) Assert.AreEqual(actual, x1, actual * .0005); // All we want is to be within .05% of the "actual" (according to wikipedia) value Assert.AreEqual(actual, x2, actual * .0005); // All we want is to be within .05% of the "actual" (according to wikipedia) value //Actually, we're only 0,0135% off... }
private void Initialize(Stream Input, bool MajorPlacesOnly) { List<GeoName> Places = new List<GeoName>(); using (StreamReader db = new StreamReader(Input)) { string Line; while (!db.EndOfStream && (Line = db.ReadLine()) != null) { var Place = new GeoName(Line); if (!MajorPlacesOnly || Place.FeatureClass != GeoFeatureClass.City) Places.Add(Place); } } Names = new Dictionary<string, GeoName>(); foreach(var p in Places) { } }
private void CalculateScore(GeoName geoName, string city, string like, double?latitude, double?longitude) { double matchScore = (double)like.Length / (double)city.Length; double coordScore; if (latitude != null && longitude != null) { double latDiff = geoName.Latitude - (double)latitude; double longDiff = geoName.Longitude - (double)longitude; double distance = Math.Sqrt(Math.Pow(latDiff, 2) + Math.Pow(longDiff, 2)); distance = Math.Min(255.0, distance); coordScore = 1.0 - (distance / 255.0); } else { coordScore = matchScore; } double avgScore = (matchScore + coordScore) / 2; geoName.Score = Math.Round(avgScore, 2); }
public void DistanceTo_WorksOnAllIGeoLocationObjects() { var gn = new GeoName { Latitude = 50.0333, Longitude = 16.2833 }; var en = new ExtendedGeoName { Latitude = 55.5075, Longitude = 31.85 }; var pc = new Postalcode { Latitude = 51.5558, Longitude = 5.6903 }; var a = gn.DistanceTo(en); var b = gn.DistanceTo(pc); var c = gn.DistanceTo(gn); var d = en.DistanceTo(gn); var e = en.DistanceTo(pc); var f = en.DistanceTo(en); var g = pc.DistanceTo(gn); var h = pc.DistanceTo(en); var i = pc.DistanceTo(pc); }
protected void Page_Load(object sender, EventArgs e) { var childTabs = TabController.GetTabsByParent(TabId, PortalId); if (childTabs.Count() > 0) { DetailsTabId = childTabs[0].TabID; } if (childTabs.Count() > 1) { EditTabId = childTabs[1].TabID; } try { if (!IsPostBack) { LoadPersistentSettings(); StringBuilder sb = new StringBuilder(); sb.Append("var markersArray=[];"); sb.Append("function clearOverlays() {"); sb.Append(" for (var i = 0; i < markersArray.length; i++ ) {"); sb.Append(" markersArray[i].setMap(null);"); sb.Append(" }"); sb.Append(" markersArray = [];"); sb.Append("}"); locationGMap.Add(sb.ToString()); using (SelectedHotelsEntities db = new SelectedHotelsEntities()) { #if DEBUGDB db.Database.Log = logInfo => MyLogger.Log(logInfo, PortalSettings); #endif PanelCategories.Visible = false; PanelProducts.Width = Unit.Pixel(870); GeoName geoName = db.GeoNames.SingleOrDefault(gn => gn.Name == "London" && gn.CountryCode == "GB"); GLatLng point = new GLatLng(geoName.Location.Latitude.Value, geoName.Location.Longitude.Value); if (Session["HiddenFieldX"] == null && Session["Location"] == null) { if (Settings["location"] != null) { var location = Settings["location"].ToString(); var geoNames = db.GeoNames.Where(gn => gn.Name.ToLower() == location.ToLower()) .OrderByDescending(gn => gn.Population) .ThenByDescending(gn => gn.ModificationDate); if (geoNames.Any()) { geoName = geoNames.FirstOrDefault(); Session["HiddenFieldX"] = geoName.Location.Latitude.Value; Session["HiddenFieldY"] = geoName.Location.Longitude.Value; } } } else if (Session["Location"] != null) { var location = Session["Location"].ToString(); var geoNames = db.GeoNames.Where(gn => gn.Name.ToLower() == location.ToLower()) .OrderByDescending(gn => gn.Population) .ThenByDescending(gn => gn.ModificationDate); if (geoNames.Any()) { geoName = geoNames.FirstOrDefault(); if (geoName.Location.Latitude != null && geoName.Location.Longitude != null) { Session["HiddenFieldX"] = geoName.Location.Latitude.Value; Session["HiddenFieldY"] = geoName.Location.Longitude.Value; } } } else if (Session["HiddenFieldX"] != null) { point = new GLatLng(Convert.ToDouble(Session["HiddenFieldX"]), Convert.ToDouble(Session["HiddenFieldY"])); var location = DbGeography.FromText(String.Format("POINT({0} {1})", point.lng, point.lat)); geoName = db.GeoNames.Where(gn => gn.FeatureClass == "P").OrderBy(gn => gn.Location.Distance(location)).First(); } point = new GLatLng(Convert.ToDouble(Session["HiddenFieldX"]), Convert.ToDouble(Session["HiddenFieldY"])); LabelSelectedLocation.Text = geoName.Name; double distance = double.Parse(DropDownListDistance.SelectedValue); ResetMap(point, distance); CreateMarker(point); BindData(db, point, distance); SavePersistentSetting(); } } } catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); } }
/// <summary> /// Takes an prepopulated IDataReader and creates an array of GeoNames /// </summary> public static List<GeoName> PopulateObjectWithJoin(IDataReader dr) { ColumnFieldList list = new ColumnFieldList(dr); List<GeoName> arr = new List<GeoName>(); GeoName obj; while (dr.Read()) { obj = new GeoName(); if (list.IsColumnPresent("GeoNameID")) { obj._geoNameID = (int)dr["GeoNameID"]; } if (list.IsColumnPresent("Name")) { obj._name = (string)dr["Name"]; } if (list.IsColumnPresent("Latitude")) { obj._latitude = (decimal)dr["Latitude"]; } if (list.IsColumnPresent("Longitude")) { obj._longitude = (decimal)dr["Longitude"]; } if (list.IsColumnPresent("FeatureClassID")) { obj._featureClassID = (int)dr["FeatureClassID"]; } if (list.IsColumnPresent("FeatureCodeID")) { obj._featureCodeID = (int)dr["FeatureCodeID"]; } if (list.IsColumnPresent("CountryID")) { obj._countryID = (int)dr["CountryID"]; } if (list.IsColumnPresent("Admin1ID")) { obj._admin1ID = (int)dr["Admin1ID"]; } if (list.IsColumnPresent("Population")) { obj._population = (int)dr["Population"]; } if (list.IsColumnPresent("Elevation")) { obj._elevation = (int)dr["Elevation"]; } if (list.IsColumnPresent("gtopo3")) { obj._gtopo3 = (int)dr["gtopo3"]; } if (list.IsColumnPresent("TimeZoneID")) { obj._timeZoneID = (int)dr["TimeZoneID"]; } if (list.IsColumnPresent("ModDate")) { obj._modDate = (DateTime)dr["ModDate"]; } arr.Add(obj); } dr.Close(); return arr; }
protected virtual void GetWeatherForLocation(string location, string channel, string nick, bool lookupAlias = true, bool showLocName = true) { if (lookupAlias) { string aliasedLocation; if (Config.LocationAliases.TryGetValue(location, out aliasedLocation)) { location = aliasedLocation; } } // try specials first var providersWeathers = new List <(IWeatherProvider Provider, string WeatherString)>(); foreach (IWeatherProvider provider in WeatherProviders) { // returns null if unsuccessful string weatherDescr = provider.GetWeatherDescriptionForSpecial(location); providersWeathers.Add((provider, weatherDescr)); } if (providersWeathers.Any(pw => pw.WeatherString != null)) { // some special; skip the geocoding foreach (var(provider, weather) in providersWeathers) { if (weather == null) { continue; } OutputWeather(null, channel, nick, weather, showLocName); } return; } // geocode var geoClient = new GeoNamesClient(Config.GeoNames); Match latLonMatch = LatLonRegex.Match(location); decimal latitude, longitude; string locName = null; if (latLonMatch.Success) { latitude = ParseDecimalInv(latLonMatch.Groups["Latitude"].Value); longitude = ParseDecimalInv(latLonMatch.Groups["Longitude"].Value); if (showLocName) { locName = geoClient.GetFirstReverseGeo(latitude, longitude).Result; } } else { // find the location using GeoNames (Wunderground's geocoding is really bad) GeoName loc = geoClient.GetFirstGeoName(location).Result; if (loc == null) { ConnectionManager.SendChannelMessage(channel, $"{nick}: GeoNames cannot find that location!"); return; } latitude = loc.Latitude; longitude = loc.Longitude; locName = loc.NameAndCountryName; } foreach (var(provider, weather) in providersWeathers) { string finalWeather = weather; if (finalWeather == null) { finalWeather = provider.GetWeatherDescriptionForCoordinates(latitude, longitude); } OutputWeather(locName, channel, nick, finalWeather, showLocName); } }