Beispiel #1
0
        ///////////////////////////////////////////////////////////////////////
        public static GeoData GetGeoData(String geonameId)
        {
            StringBuilder url = new StringBuilder("http://api.geonames.org/get?");
            url.Append("geonameId=").Append(geonameId);
            url.Append("&username="******"GetGeoData => {0}", url);

            XElement elem = XDocument.Load(url.ToString()).Root;
            String tz = elem.Element("timezone").Value;

            var data = new GeoData {
                LocationID = elem.Element("geonameId").Value,

                Name = elem.Element("name").Value,
                Country = elem.Element("country").Value,
                Region = elem.Element("adminName1").Value,

                Latitude = decimal.Parse(elem.Element("lat").Value),
                Longitude = decimal.Parse(elem.Element("lng").Value),

                TimeZone = TimeZoneInfo.FindSystemTimeZoneById(tz),

                LastUpdated = DateTime.Now
            };

            return data;
        }
Beispiel #2
0
        ///////////////////////////////////////////////////////////////////////
        public static AstronomicalData GetAstroData(GeoData geo, DateTime date)
        {
            var url = new StringBuilder("http://api.geonames.org/timezone?");
            url.Append("lat=").Append(geo.Latitude).Append("&lng=").Append(geo.Longitude);
            url.Append("&date=").Append(date.ToString("yyyy-MM-dd"));
            url.Append("&username="******"GetAstroData => {0}", url);

            XElement root = XDocument.Load(url.ToString()).Root;

            XElement elem = root.Element("timezone");
            if (elem == null) { return null; }

            XElement sunr = elem.Element("date");
            if (sunr == null) { return null; }

            var data = new AstronomicalData {
                Sunrise = DateTime.Parse(sunr.Element("sunrise").Value),
                Sunset = DateTime.Parse(sunr.Element("sunset").Value),

                Source = new WhenAndWhere {
                    When = date, Where = geo
                }
            };

            return data;
        }
Beispiel #3
0
        ///////////////////////////////////////////////////////////////////////
        // http://developer.yahoo.com/geo/geoplanet/
        public static GeoData GetGeoData(String woeid)
        {
            String url = String.Format("http://where.yahooapis.com/v1/place/{0}?appid={1}", woeid, _appid);

            _logger.Debug("GetGeoData({0})", url);

            // the result declares a default namespace on the root node
            XElement elem = XDocument.Load(url).Root;
            XNamespace ns = elem.GetDefaultNamespace();

            // holds the lat/lon of the woeid region center
            XElement latlon = elem.Element(ns + "centroid");

            var data = new GeoData {
                LocationID = elem.Element(ns + "woeid").Value,

                Name = elem.Element(ns + "name").Value,
                Country = elem.Element(ns + "country").Value,
                Region = elem.Element(ns + "admin1").Value,

                Latitude = decimal.Parse(latlon.Element(ns + "latitude").Value),
                Longitude = decimal.Parse(latlon.Element(ns + "longitude").Value),

                LastUpdated = DateTime.Now
            };

            return data;
        }
        public object GetValue(GeoData geoData)
        {
            var result = Convert.ToInt32(geoData.Values[geoData.Values.Keys.ElementAt(0)]);

            if (result < 80 || result > 100)
            {
                return(0);
            }

            return(1);
        }
Beispiel #5
0
 private float GetRelativeOffset(GeoData geoData)
 {
     if (geoData.hasModel)
     {
         return(yOffsetWithModel);
     }
     else
     {
         return(yOffset);
     }
 }
Beispiel #6
0
        private string GetContinent(AddNewDiaryRequest addNewDiaryRequest, Diary diary)
        {
            string countryCode = addNewDiaryRequest.Countries.FirstOrDefault();

            if (countryCode == null)
            {
                return(null);
            }

            return(GeoData.GetContinentByCountry(countryCode));
        }
Beispiel #7
0
 public static GeoResult Create(GeoData data)
 {
     return(new GeoResult {
         Id = data.Id.ToString(),
         Lon = data.Location.Coordinates.Longitude,
         Lat = data.Location.Coordinates.Latitude,
         Content = data.Content,
         Name = data.Name,
         //ContentType = data.ContentType,
         Tag = data.Tags
     });
 }
 private void updateSelectedTexts()
 {
     countrySelect.Content = (Chart.CountryCode.Length > 0 ? Chart.CountryName : "");
     placeSelect.Content   = (Chart.PlaceName.Length > 0 ?
                              Chart.PlaceName +
                              " (" + GeoData.coordinatesToString(Chart.Latitude, Chart.Longitude) + ")"
         : "Select Place");
     timeZoneSelect.Content = (Chart.TimeZone.Length > 0 ? Chart.TimeZone : "Select Time Zone");
     //hidePlacesIfNoCountry();
     MyDatePicker.Value = new DateTime(Chart.Year, Chart.Month, Chart.Day);
     MyTimePicker.Value = new DateTime(Chart.Year, Chart.Month, Chart.Day, Chart.Hour, Chart.Minute, 0);
 }
Beispiel #9
0
        public async Task <IHttpActionResult> PostGeoData([FromBody] GeoData geoData)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.GeoDatas.Add(geoData);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = geoData.id }, geoData));
        }
Beispiel #10
0
 //Function for Drop pin on the map
 void DrawPoints(GeoData geoData)
 {
     geoData.Coordinates.ForEach((Coordinate coordinate) =>
                                 // Drop Pin
                                 myMap.Pins.Add(new Pin()
     {
         Type     = PinType.Generic,
         Label    = geoData.Name,
         Address  = String.Format("latitude : {0:F3}, longitude : {1:F3}", coordinate.Latitude, coordinate.Longitude),
         Position = new Position(coordinate.Latitude, coordinate.Longitude)
     })
                                 );
 }
 private bool IsInitializing(GeoData geoData)
 {
     return(geoData.PositionData.InsData.Status != NavigationStatus.Locked ||
            geoData.PrecisionData.NorthPositionAccuracy > 0.6 ||
            geoData.PrecisionData.EastPositionAccuracy > 0.6 ||
            geoData.PrecisionData.DownPositionAccuracy > 0.9 ||
            geoData.PrecisionData.NorthVelocityAccuracy > 0.5 ||
            geoData.PrecisionData.EastVelocityAccuracy > 0.5 ||
            geoData.PrecisionData.DownVelocityAccuracy > 0.75 ||
            geoData.PrecisionData.HeadingAccuracy > 0.35 ||
            geoData.PrecisionData.PitchAccuracy > 0.09 ||
            geoData.PrecisionData.RollAccuracy > 0.09);
 }
Beispiel #12
0
        public GeoData GetLocationData()
        {
            var loc = new GeoData
            {
                Latitude  = Location.Latitude,
                Longitude = Location.Longitude,
                Altitude  = Location.Latitude,
                Heading   = Location.Heading,
                Speed     = Location.Speed
            };

            return(loc);
        }
Beispiel #13
0
        private void reciver_MessageRecieved(object sender, QuickRabbitMQ.MessageRecivedEventArgs e)
        {
            try
            {
                if (e != null && e.MessageBody != null)
                {
                    string json = System.Text.Encoding.UTF8.GetString(e.MessageBody);
                    log.Debug(" 收到消息:" + json);

                    if (!string.IsNullOrEmpty(json))
                    {
                        Newtonsoft.Json.Linq.JObject jsonJobject = Newtonsoft.Json.JsonConvert.DeserializeObject(json) as Newtonsoft.Json.Linq.JObject;
                        if (jsonJobject == null)
                        {
                            return;
                        }

                        Newtonsoft.Json.Linq.JToken typeJToken = jsonJobject["msgType"];
                        if (typeJToken == null)
                        {
                            log.Debug("未解析到messageType");
                            return;
                        }
                        int messageType = (int)typeJToken;

                        switch (messageType)
                        {
                        case 0:
                            GeoData geoData = JsonHelper.JsonDeserialize <GeoData>(json);
                            if (geoData != null)
                            {
                                var handler = GeoDataReceiveEvent;
                                if (handler != null)
                                {
                                    handler(this, new GeoDataReceivedArgs(geoData));
                                }
                            }
                            break;

                        default:
                            log.Error("未知的消息类型," + messageType);
                            break;
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                log.Error(exp);
            }
        }
Beispiel #14
0
        public async Task <GeoData> GetLocationByIp(string ip)
        {
            var loc = new GeoData();
            var url = "http://api.2ip.com.ua/geo.xml?ip=" + ip;

            try
            {
                var request = WebRequest.Create(url);
                request.Timeout = 10000;
                using (var response = (HttpWebResponse)await request.GetResponseAsync())
                {
                    if (response == null)
                    {
                        return(null);
                    }
                    var encoding = !string.IsNullOrWhiteSpace(response.CharacterSet)
                        ? Encoding.GetEncoding(response.CharacterSet)
                        : null;
                    var responseStream = response.GetResponseStream();
                    if (responseStream == null)
                    {
                        return(null);
                    }
                    using (var sr = encoding != null
                        ? new StreamReader(responseStream, encoding)
                        : new StreamReader(responseStream, true))
                    {
                        var response2  = sr.ReadToEnd();
                        var doc        = XDocument.Parse(response2);
                        var geoData    = doc.Element("geo_api");
                        var locCountry = geoData?.Element("country_rus")?.Value;
                        var locCity    = geoData?.Element("city_rus")?.Value;
                        var zip        = geoData?.Element("zip_code")?.Value;
                        if (zip == "-")
                        {
                            zip = "";
                        }
                        var countryCode = geoData?.Element("country_code")?.Value.ToLower();
                        loc.CountryCode = countryCode;
                        loc.City        = locCity == "" ? "Unknown" : locCity;
                        loc.Country     = locCountry == "" ? "Unknown" : locCountry;
                        loc.Index       = zip == "" ? "" : zip;
                    }
                }
            }
            catch
            {
                loc = null;
            }
            return(loc);
        }
Beispiel #15
0
        public async Task <GeoData> GetLocationByIp(string ip)
        {
            var loc = new GeoData();
            var url = "https://ipinfo.io/" + ip + "/json";

            try
            {
                var request = WebRequest.Create(url);
                request.Timeout = 10000;
                using (var response = (HttpWebResponse)await request.GetResponseAsync())
                {
                    if (response == null)
                    {
                        return(null);
                    }
                    var encoding = !string.IsNullOrWhiteSpace(response.CharacterSet)
                        ? Encoding.GetEncoding(response.CharacterSet)
                        : null;
                    var responseStream = response.GetResponseStream();
                    if (responseStream == null)
                    {
                        return(null);
                    }
                    using (var sr = encoding != null
                        ? new StreamReader(responseStream, encoding)
                        : new StreamReader(responseStream, true))
                    {
                        var response2 = sr.ReadToEnd();
                        var geoData   = Json.DeserializeDataFromString <ProviderGeoData>(response2);
                        if (geoData != null)
                        {
                            loc.Isp         = geoData.Org;
                            loc.CountryCode = geoData.Country?.ToLower();
                            loc.City        = string.IsNullOrWhiteSpace(geoData.City) ? "Unknown" : $"{geoData.City}-{geoData.Region}";
                            loc.Country     = string.IsNullOrWhiteSpace(geoData.Country) ? "Unknown" : geoData.Country;
                            loc.Index       = geoData.Postal == "" ? "" : geoData.Postal;
                        }
                        else
                        {
                            loc = null;
                        }
                    }
                }
            }
            catch
            {
                loc = null;
            }
            return(loc);
        }
Beispiel #16
0
        public GeoData GetGeoDataDemo()
        {
            GeoData data = new GeoData();

            data.Locations.Add(new Location()
            {
                Lat = "34.452218", Lon = "-111.408234"
            });
            data.Locations.Add(new Location()
            {
                Lat = "28.88316", Lon = "-106.222687"
            });
            return(data);
        }
        public CountrySelector()
        {
            InitializeComponent();
            IList <GeoData.GeoCountryInfo> ctrs = GeoData.loadCountryInfo();

            GeoData.GeoCountryInfo custom = new GeoData.GeoCountryInfo();
            custom.countryName = "[CUSTOM LOCATION]";
            custom.countryCode = "CUSTOM";

            ctrs.Insert(0, custom);

            listBox1.ItemTemplate = countryTemplate;
            listBox1.ItemsSource  = ctrs;
        }
Beispiel #18
0
        public mapZoom(GeoData data)
        {
            InitializeComponent();
            key     = false;
            geodata = LocalDatabase.GetGeoDataById(data.Id);
            btn_locate.IsVisible = true;
            // Map Set Up function
            myMap.UiSettings.ZoomControlsEnabled     = false;
            myMap.UiSettings.CompassEnabled          = false;
            myMap.UiSettings.MyLocationButtonEnabled = true;
            displayBasicGeodataInformation();

            RedirectMapToPinLocation();
        }
Beispiel #19
0
        public JsonResult GetGeoDataByExactName(string location)
        {
            Dictionary <string, string> filters = new Dictionary <string, string>()
            {
                { "country", "LT" },
                { "lang", "LT" },
                { "feature_code", "PPL" },
                { "name_equals", location }
            };

            GeoData geoData = new GeoData(filters);

            return(Json(JsonConvert.SerializeObject(geoData.Results), JsonRequestBehavior.AllowGet));
        }
Beispiel #20
0
        public JsonResult GetAutoCompleteGeoData(string location)
        {
            Dictionary <string, string> filters = new Dictionary <string, string>()
            {
                { "country", "LT" },
                { "lang", "LT" },
                { "feature_code", "PPL" },
                { "name_startsWith", location }
            };
            GeoData geoData = new GeoData(filters);

            geoData.GetAutoCompleteData(4);
            return(Json(JsonConvert.SerializeObject(geoData.AutoCompleteGeoData), JsonRequestBehavior.AllowGet));
        }
        public IActionResult OnGet()
        {
            if (GeoData == null)
            {
                GeoData = new GeoData {
                    Result = new GeoDataMapper
                    {
                        location = new GeoDataMapper.Location()
                    }
                };
            }

            return(Page());
        }
        public void FillGeoData(GeoData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (this.Sentence == null)
            {
                return;
            }

            data.DeviceType = GpsDeviceType.Gps;
            this.Sentence.FillGeoData(data);
        }
Beispiel #23
0
        public async Task <IHttpActionResult> DeleteGeoData(int geoid)
        {
            GeoData geoData = await db.GeoDatas.FindAsync(geoid);

            if (geoData == null)
            {
                return(NotFound());
            }

            db.GeoDatas.Remove(geoData);
            await db.SaveChangesAsync();

            return(Ok(geoData));
        }
Beispiel #24
0
        public IEnumerable <GeoData> ParseGeodataFromSource(LayersConfiguration sourceData)
        {
            string filePath = sourceData.Source;

            foreach (var line in File.ReadLines(filePath))
            {
                if (line == null)
                {
                    continue;
                }

                var components = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                var longitude = double.Parse(components[0], new CultureInfo("en-US"));
                var latitude  = double.Parse(components[1], new CultureInfo("en-US"));

                var geodata = new GeoData
                {
                    Values = new Dictionary <string, object>(StringComparer.InvariantCultureIgnoreCase),
                    Points = new PointXY[1][]
                };

                if (Math.Abs(sourceData.XOffset) > (decimal)0.0 && Math.Abs(sourceData.YOffset) > (decimal)0.0)
                {
                    geodata.Points[0] = new[]
                    {
                        new PointXY(longitude - (double)sourceData.XOffset,
                                    latitude - (double)sourceData.YOffset), //TOP-LEFT

                        new PointXY(longitude + (double)sourceData.XOffset,
                                    latitude + (double)sourceData.YOffset) //BOTTOM-RIGHT
                    }
                }
                ;
                else
                {
                    geodata.Points[0] = new[] { new PointXY(longitude, latitude) };
                }

                var values = components.Skip(2);

                var fieldCount = 0;
                foreach (var value in values)
                {
                    geodata.Values.Add("custom_" + fieldCount++, value);
                }

                yield return(geodata);
            }
        }
Beispiel #25
0
    private IEnumerator TryCreateGeoAudioObject(string audioURL, AudioType audioType,
                                                GeoData geoData, Vector3 objectPlace)
    {
        if (geoData.hasAudio)
        {
            // Create dummy object while loading audio.
            GameObject prefab = Instantiate(GeoAudioPrefab, objectPlace, Quaternion.identity);
            prefab.name = "GeoAudio " + ("[LOADING] ") + geoData.title;
            GeoObject geoObject = prefab.AddComponent <GeoObject>();
            geoObject.GeoData = geoData;
            geoObjectsInScene[2].Add(geoData.id, prefab);

            // Load audio from server.
            using (var request = UnityWebRequestMultimedia.GetAudioClip(audioURL, audioType))
            {
                yield return(request.SendWebRequest());

                bool result = request.result == UnityWebRequest.Result.Success;

                // Instantiate GeoAudio object.
                // Don't display radio model if geoData.hasModel.

                prefab.name = "GeoAudio " + (result ? "" : "[ERROR] ") + geoData.title;
                prefab.transform.SetParent(ToNorth.transform);
                prefab.transform.position = objectPlace;
                prefab.tag = nameof(GeoAudio);

                AudioClip audio = null;

                Debug.Log(audioURL + " " + geoData.title);

                if (result)
                {
                    audio = DownloadHandlerAudioClip.GetContent(request);
                }
                else
                {
                    Debug.LogError("Failed to load Audio: " + audioURL);
                }

                prefab.GetComponent <GeoAudio>().Initialize(geoObject, audio, GetRelativeOffset(geoData));
                // Display title if GeoAudio don't have GeoText.
                prefab.GetComponent <GeoAudio>().SetTitle(geoData.title, !geoData.hasText);

                prefab.GetComponent <AudioSource>().volume = 1;
                prefab.GetComponent <AudioSource>().Play();
            }
        }
    }
        private void fillForm(GeoData data)
        {
            label_IP.Content  = data.IpAddress.ToString();
            label_Geo.Content = string.Format("{0}, {1}", data.Country, data.City);

            label_Carrier.Content = data.Carrier;
            label_Org.Content     = data.Organisation;
            label_State.Content   = data.State;
            label_Sld.Content     = data.Sld;

            Uri         uri    = new Uri(string.Format("/Resources/flag-icons/{0}.png", data.CountryCode), UriKind.Relative);
            BitmapImage bitmap = new BitmapImage(uri);

            image_CountryFlag.Source = bitmap;
        }
        public void GeoDataExplicitGeoDataToStringTest()
        {
            var testGeoData = new GeoData();

            Assert.Equal((string)testGeoData, "<geoData />");

            testGeoData.Name = "tName";
            Assert.Equal((string)testGeoData, "<geoData name=\"tName\" />");

            testGeoData.AxesSystem = "tAxesSystem";
            Assert.Equal((string)testGeoData, "<geoData name=\"tName\" axes=\"tAxesSystem\" />");

            testGeoData.Poligons = "tPoligons";
            Assert.Equal((string)testGeoData, "<geoData name=\"tName\" axes=\"tAxesSystem\" wkt=\"tPoligons\" />");
        }
Beispiel #28
0
        /// <summary>
        /// Gets all textboxes values and creating library
        /// </summary>
        /// <returns>Created library</returns>
        private Library CreateLibFromTextBoxes()
        {
            OrgInfo orgInfo = new OrgInfo(TaxPayerIdTextBox.Text, FullNameTextBox.Text,
                                          HeadPhoneTextBox.Text, new Person(NameTextBox.Text, SecondNameTextBox.Text, SurnameTextBox.Text),
                                          TaxIdTextBox.Text, GovermentIdTextBox.Text);
            Address address = new Address(DistrictTextBox.Text, AreaTextBox.Text,
                                          StreetTextBox.Text, PostIndexTextBox.Text, BuildingTextBox.Text, HousingTextBox.Text,
                                          CityTextBox.Text);
            Contact      contact      = new Contact(PhoneTextBpx.Text, FaxTextBox.Text, EmailTextBox.Text, SiteTextBox.Text);
            WorkingHours workingHours = new WorkingHours(int.Parse(OpenHourTextBox.Text), int.Parse(CloseHourTextBox.Text));
            GeoData      geoData      = new GeoData(double.Parse(LatitudeTextBox.Text), double.Parse(LongitudeTextBox.Text));
            Library      lib          = new Library(orgInfo, address, geoData, workingHours, contact);

            return(lib);
        }
 public override void FillGeoData(GeoData data)
 {
     if (this.Year > 0 && this.Month > 0 && this.Day > 0)
     {
         data.PositionData.Utc = new DateTime(
             this.Year,
             this.Month,
             this.Day,
             this.Utc.Hours,
             this.Utc.Minutes,
             this.Utc.Seconds,
             this.Utc.Milliseconds,
             DateTimeKind.Utc);
     }
 }
        void SubmitBtn_Clicked(object sender, System.EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(name_Entry.Text))
            {
                DisplayAlert("Name Entry Field is empty !", " Please insert the name of the object ", "Okay");
                return;
            }

            // Will show bug in IOS version
            //if (string.IsNullOrWhiteSpace(type_Entry.SelectedItem.ToString()))
            //{

            //    DisplayAlert("Type Entry Field is empty !", "Please insert the type of the object", "Okay");
            //    return;
            //}

            if (string.IsNullOrWhiteSpace(description_Entry.Text))
            {
                DisplayAlert("Description Entry Field is empty !", "Please insert the Description for the object", "Okay");
                return;
            }

            if (PositionsList.Count == 0)
            {
                DisplayAlert("Object coordinate undefine!", "Please point out the object coordinate on the map ", "Okay");
                return;
            }

            List <Coordinate> coorList = new List <Coordinate>();

            PositionsList.ForEach((Position pos) => coorList.Add(new Coordinate(pos.Latitude, pos.Longitude)));

            if (PositionsList.Count >= 3)
            {
                coorList.Add(new Coordinate(PositionsList[0].Latitude, PositionsList[0].Longitude));
            }

            GeoData data = new GeoData(name_Entry.Text, type_Entry.SelectedItem.ToString(), User.nickname, description_Entry.Text);

            // Insert the Geodata into SQLite database and recieve the message
            string msg = LocalDatabase.InsertNewGeodataToDB(coorList, data);

            //Display msg to the user
            DisplayAlert($"{msg}", $"GeoData Insert {msg}", "Okay");

            //Go Back to Previous Page
            Navigation.PopAsync();
        }
        /// <summary>
        /// Method to search locations close to other one
        /// </summary>
        /// <param name="pLocation">Location</param>
        /// <param name="maxDistance">Max Distance</param>
        /// <param name="maxResults">Max number of Results</param>
        /// <returns></returns>
        public async Task <List <Location> > GetLocationsAsync(Location pLocation, int maxDistance, int maxResults)
        {
            List <Location> filteredList = new List <Location>();

            try
            {
                //Get all Locations
                List <Location> lLocationsJoined = new List <Location>();

                using (GeoData gData = new GeoData())
                {
                    int   totalL      = 1000000;
                    int   paralellism = 100000;
                    int   nThreads    = totalL / paralellism;
                    int[] arrayRanges = new int[nThreads];

                    for (int i = 0; i < nThreads; i++)
                    {
                        arrayRanges[i] = i * paralellism;
                    }

                    IEnumerable <Task <List <Location> > > getLocationsTasksQuery = from range in arrayRanges
                                                                                    select gData.getAllLocationsByRange(range, paralellism);

                    // Use ToArray to execute the query and start the getLocations tasks.
                    Task <List <Location> >[] downloadTasks = getLocationsTasksQuery.ToArray();

                    List <Location>[] lLocations = await Task.WhenAll(downloadTasks);
                }

                //Sort by Distance
                List <Location> SortedList = lLocationsJoined.OrderBy(o => o.CalculateDistance(pLocation)).ToList();

                //Filter the Locations with the same Distance, Longitude and Latitude
                List <Location> filterRepeated = SortedList.GroupBy(x => new { x.Distance, x.Longitude, x.Latitude })
                                                 .Select(g => g.First())
                                                 .ToList();

                //Filter by the max Number of Results
                filteredList = filterRepeated.Where(x => x.Distance <= maxDistance).Take(maxResults).ToList();
            }
            catch
            {
                throw;
            }

            return(filteredList);
        }
        private async void searchImage_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (!searchBox.Text.Equals(string.Empty) && searchBox.Text.Count() <= 4)
            {
                XDocument loaded = XDocument.Load("allStops.txt");
                var       stops  = (from el in loaded.Elements("Buses").Descendants("Stop")
                                    where (string)el.Attribute("Line") == searchBox.Text && (string)el.Attribute("Dir") == "1"
                                    select el.Attribute("StopID").Value).ToList();

                Stream stream;

                string      fileContent;
                StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(@"ms-appx:///stops.txt"));

                using (StreamReader sRead = new StreamReader(await file.OpenStreamForReadAsync()))
                {
                    fileContent = await sRead.ReadToEndAsync();

                    string[] stopsGeoData = fileContent.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                    MapIcon  mapIcon      = new MapIcon();
                    foreach (string line in stopsGeoData)
                    {
                        if (stops.Contains(line.Split(',')[0]))
                        {
                            string lat = line.Split(',')[4];
                            string lon = line.Split(',')[5];

                            mapIcon = new MapIcon();
                            // Locate your MapIcon
                            mapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/AppIcons/ATH_icons_bus_grey.png"));
                            // Show above the MapIcon
                            mapIcon.Title = line.Split(',')[2];
                            // Setting up MapIcon location
                            mapIcon.Location = new Geopoint(new BasicGeoposition()
                            {
                                Latitude  = Convert.ToDouble(lat),
                                Longitude = Convert.ToDouble(lon)
                            });
                            // Positon of the MapIcon
                            mapIcon.NormalizedAnchorPoint = new Point(0.5, 0.5);
                            GeoData.MapElements.Add(mapIcon);
                        }
                    }

                    await GeoData.TrySetViewAsync(mapIcon.Location, 15d, 0, 0, MapAnimationKind.Bow);
                }
            }
        }
Beispiel #33
0
        private static Hexagon CreateHexagon(GeoData geoData, LayersLoaderTarget[] targets, HexagonLocationUV hexagonLocation, TargetHandler TargetValueStrategy)
        {
            Hexagon hexagon = new Hexagon {
                LocationUV = hexagonLocation, HexagonData = new HexagonData()
            };

            if (targets != null)
            {
                foreach (LayersLoaderTarget target in targets)
                {
                    hexagon.HexagonData[target.Destination] = TargetValueStrategy(geoData, target);
                }
            }

            return(hexagon);
        }
Beispiel #34
0
 public int TestBallot(ref GeoData geoData)
 {
     try
     {
         _isRunningNow = false;
         return TestBallot(_lastLines[0], _lastLines[1], ref geoData);
     }
     catch (Exception ex)
     {
         SetError(ErrorCode.UnexpectedError, string.Format("TestBallot: {0}", ex));
         throw;
     }
 }
Beispiel #35
0
 public static string GetGeoResultMessage(GeoData geoData, long squareCount)
 {
     if ((GeoResult)geoData.result == GeoResult.OK)
     {
         long maxSquareSkew = 0;
         long maxSquareSkewH = 0, minSquareSkewH = Int32.MaxValue;
         long maxSquareSizeSkew = 0, minSquareSizeSkew = Int32.MaxValue;
         int minColor, maxColor;
         minColor = maxColor = geoData.topMarkerColor;
         minColor = Math.Min(minColor, geoData.bottomMarkerColor);
         maxColor = Math.Max(maxColor, geoData.bottomMarkerColor);
         minColor = Math.Min(minColor, geoData.baseLineColor);
         maxColor = Math.Max(maxColor, geoData.baseLineColor);
         for (int i = 0; i < squareCount; i++)
         {
             if (geoData.squares[i] == 1)
             {
                 maxSquareSkew = Math.Max(maxSquareSkew, geoData.squaresSkewV[i]);
                 maxSquareSkew = Math.Max(maxSquareSkew, geoData.squaresSkewV[i]);
                 maxSquareSkewH = Math.Max(maxSquareSkewH, geoData.squaresSkewH[i]);
                 minSquareSkewH = Math.Min(minSquareSkewH, geoData.squaresSkewH[i]);
                 maxSquareSizeSkew = Math.Max(maxSquareSizeSkew, geoData.squaresSize[i]);
                 minSquareSizeSkew = Math.Min(minSquareSizeSkew, geoData.squaresSize[i]);
                 minColor = Math.Min(minColor, geoData.squaresColor[i]);
                 maxColor = Math.Max(maxColor, geoData.squaresColor[i]);
             }
         }
         if (minSquareSizeSkew == Int32.MaxValue)
         {
             minSquareSizeSkew = maxSquareSizeSkew;
         }
         if (maxSquareSkew > 3 ||
             maxSquareSkewH != minSquareSkewH && maxSquareSkewH > 2 ||
             maxSquareSizeSkew != 0)
         {
             return "Некорректное расположение квадратов";
         }
         if (maxColor - minColor > 20 && maxColor > minColor * 2)
         {
             return "Нарушена равномерность черного цвета";
         }
         if (maxColor > 64)
         {
             return "Недостаточная интенсивность черного цвета";
         }
     }
     switch ((GeoResult)geoData.result)
     {
         case GeoResult.OK:
             return "бюллетень соответствует модели";
         case GeoResult.TopMarker:
             return "не найдены маркеры";
         case GeoResult.BottomMarker:
             return "не найден или не определен нижний маркер";
         case GeoResult.Markers:
             return "несовпадение маркеров";
         case GeoResult.BadMarkerNum:
             return "недопустимый код маркера";
         case GeoResult.LeftSide:
             return "не найдена левая граница бюллетеня";
         case GeoResult.BaseLine:
             return "не найдена базовая линия";
         case GeoResult.BadBaseLine:
             return "неверное положение базовой линии";
         case GeoResult.Squares:
             return "не найдены квадраты";
         default:
             return "неожиданный код возврата";
     }
 }
Beispiel #36
0
 internal static extern int TestBallot(int y0, int y1, ref GeoData pData);