Beispiel #1
0
        private async void RunAddress()
        {
            this.SetSearchState(true);
            this.SearchDescription = "Ermittle Position der Adresse ...";
            GlobalCoordinate position = await GeoCoder.GetPositionForAddress(this.AddressStreet + "\n" + this.AddressTown);

            if (position == null)
            {
                this.SetSearchState(false);
                CrossToast.ShowToast("Positionsermittlung fehlgeschlagen");
                return;
            }
            this.SearchDescription = "Suche Tankstellen ...";
            List <PriceInfo> results = await ApiRequests.RequestGasStations(position);

            if (results == null)
            {
                this.SetSearchState(false);
                CrossToast.ShowToast("Suche fehlgeschlagen!");
                return;
            }
            if (results.Count > 0)
            {
                // Add prices to the database
                DbDataProvider.Instance.AddPricesToHistory(results);
                this.ResultsFound?.Invoke(this, results);
                this.SearchDescription = String.Empty; // bug fix for small return delay
            }
            else
            {
                this.SetSearchState(false);
                CrossToast.ShowToast("Es wurden keine Tankstellen gefunden.");
            }
        }
Beispiel #2
0
        protected void btnSaveDetails_Click(object sender, EventArgs e)
        {
            if (txtZip.Text != Entity.Zip)
            {
                Entity.CityStateZip = GeoCoder.TryGeocodeZip(txtZip.Text);
            }

            if (!string.IsNullOrEmpty(fuImage.FileName) && IsImage(fuImage.FileName))
            {
                if (Entity.ShopImages == null)
                {
                    Entity.ShopImages = new List <ShopImage>();
                }
                var img = Bitmap.FromStream(new MemoryStream(fuImage.FileBytes));
                img = img.ResizeImage(300, 300, false);
                var ms = new MemoryStream();
                img.Save(ms, ImageFormat.Jpeg);
                for (int i = Entity.ShopImages.Count - 1; i >= 0; i--)
                {
                    EasyContext.ShopImages.Remove(Entity.ShopImages.ElementAt(i));
                }
                Entity.ShopImages.Add(new ShopImage()
                {
                    ImageData = ms.GetBuffer()
                });
            }

            Update();
        }
        public static List<SearchResult> GetSearchResultsFromRepository(string query, double radiusInMiles = 5)
        {
            List<SearchResult> searchResults = new List<SearchResult>();
            List<DayCareRepository> allDayCareCenters = RepositoryService.GetAllDayCareRepositoryData();

            GeoCoder coder = new GeoCoder();
            List<GeoCoder.Location> locations = coder.GetLocationsByQueryFromGoogle(query);
            if (locations == null || locations.Count == 0)
                return searchResults;

            var location = locations[0];
            foreach (var dc in allDayCareCenters)
            {
                double distance = 0.621 * GeographyUtils.HaversineDistance(dc.Latitude, dc.Longitude, location.Latitude, location.Longitude);
                if (distance <= radiusInMiles)
                {
                    SearchResult sr = dc.ToSearchResult();
                    sr.Distance = distance;
                    //TODO: Remove dummy phone
                    sr.Phone = "615-555-5555";
                    searchResults.Add(sr);
                }
            }

            return searchResults.OrderBy(sr => sr.Distance).ThenBy(sr => sr.Name).ToList();
        }
        public void GeoCodeLocation()
        {
            // call the geo-coder
            var result = GeoCoder.LookUpGeoLocation(this);

            if (result.Action == GeoCoder.GeoCodeResult.GeoCodeAction.Clear)
            {
                // set the status
                this.GeocodingStatus = result.GeocodingStatus;

                // set the latitude, longitude, and DB location
                this.Latitude  = null;
                this.Longitude = null;
                this.Location  = null;
            }

            else if (result.Action == GeoCoder.GeoCodeResult.GeoCodeAction.Set)
            {
                // set the status
                this.GeocodingStatus = result.GeocodingStatus;

                // set the latitude, longitude, and DB location
                this.Latitude  = Convert.ToDouble(result.Latitude);
                this.Longitude = Convert.ToDouble(result.Longitude);
                this.Location  = new[] { this.Longitude.Value, this.Latitude.Value };
            }
        }
        public void GeoCode_Country_Gets_Info()
        {
            var geoCoder = new GeoCoder();

            var result = geoCoder.Request("Spain");

            Assert.That(result, Is.Not.Null);
        }
Beispiel #6
0
        public void CodeAll_InputContainMissSpellingsWithDifferentCasingToSavedMatches_AllCodesAdded()
        {
            // arrange
            GeoCoder geoCoder =
                new GeoCoder(MockRepository.GenerateStub <IDbConnection>() as DbConnection);
            InputColumnHeaders     inputColumnHeaders     = InputColumnNames();
            GazetteerColumnHeaders gazetteerColumnHeaders = GazetteerColumnNames();

            //gazetteer data
            string[] names1 = { "P1", "T1", "V1" };
            string[] codes1 = { "1", "10", "100" };

            // saved matched names data
            string[] names2 = { "P1x", "T1x", "V1x" };

            // input data
            // line 1, all names miss-spelt with different casing
            string[] names3 = { "p1x", "t1x", "v1x" };

            InputTestData inputTestData = new InputTestData();

            inputTestData.AddLine(names3);
            geoCoder.SetInputData(inputTestData.Data(inputColumnHeaders));
            geoCoder.SetInputColumns(inputColumnHeaders);

            // create gazetteer data
            GazetteerRecords gazetteerRecords = new GazetteerRecords();

            gazetteerRecords.AddLine(names1, codes1);
            geoCoder.SetGazetteerData(gazetteerRecords.Data(gazetteerColumnHeaders));

            // add records matched names records
            MatchProviderTestData matchProviderTestData = new MatchProviderTestData();

            // add records matching saved matched names to gazetteer names
            matchProviderTestData.AddLevel1(names2, names1);
            matchProviderTestData.AddLevel2(names2, names1);
            matchProviderTestData.AddLevel3(names2, names1);
            MatchProviderStub matchProviderStub = new MatchProviderStub(matchProviderTestData);

            geoCoder.SetMatchProvider(matchProviderStub.MatchProvider());

            geoCoder.SetGazetteerColumns(gazetteerColumnHeaders, false);

            // act
            geoCoder.AddAllLocationCodes();

            // assert
            var columns = geoCoder.LocationCodeColumnHeaders();

            //line 1 - should contain codes 1
            DataRow line1 = geoCoder.InputData.Rows[0];

            Assert.AreEqual(codes1[0], line1[columns.Level1]);
            Assert.AreEqual(codes1[1], line1[columns.Level2]);
            Assert.AreEqual(codes1[2], line1[columns.Level3]);
        }
 public UserSettingsCommandHandler(RaidBattlesContext context, ITelegramBotClient bot, IMemoryCache cache, IClock clock, GeoCoder geoCoder, IDateTimeZoneProvider dateTimeZoneProvider)
 {
     myContext              = context;
     myBot                  = bot;
     myCache                = cache;
     myClock                = clock;
     myGeoCoder             = geoCoder;
     myDateTimeZoneProvider = dateTimeZoneProvider;
 }
Beispiel #8
0
        //
        // GET: /Api/Place/

        public ActionResult Detected()
        {
            var id = GeoCoder.GetPlaceIdByIPAddress(WebContext.Current.ClientIP);

            using (var context = ContextFactory.SizeUpContext)
            {
                var data = Core.DataLayer.Place.Get(context, id);
                return(Json(data, JsonRequestBehavior.AllowGet));
            }
        }
Beispiel #9
0
        public ActionResult Detected()
        {
            var ip = Request.Headers["X-Forwarded-For"];
            var id = GeoCoder.GetPlaceIdByIPAddress(ip);

            using (var context = ContextFactory.SizeUpContext)
            {
                var data = Core.DataLayer.Place.Get(context, id);
                return(Json(data, JsonRequestBehavior.AllowGet));
            }
        }
Beispiel #10
0
        /// <summary>Geolocalizza il transito e salva le coordinate sul database.</summary>
        /// <returns>void</returns>
        public void GeoLocalizzaTransito()
        {
            string indirizzo  = this.Indirizzo + ", " + this.Cap + " " + this.Citta + ", " + this.Provincia + " " + this.Nazione;
            string coordinate = GeoCoder.EncodeAddress(indirizzo);

            this.GeoCoordinate = coordinate;
            Dao    dao = new Dao();
            string sql = "UPDATE TariffeTransiti SET GeoCoordinate = '" + this.GeoCoordinate + "' WHERE Id=" + this.Id;

            dao.ExecuteNonQuery(sql);
        }
        /// <summary>Geolocalizza la spedizione e salva le coordinte sul database.</summary>
        /// <returns>void</returns>
        private void GeoLocalizzaSpedizione()
        {
            string indirizzo  = this.DestinazioneIndirizzo + ", " + this.DestinazioneCAP + " " + this.DestinazioneLocalita + ", " + this.DestinazioneProvincia + " " + this.DestinazioneNazione;
            string coordinate = GeoCoder.EncodeAddress(indirizzo);

            this.DestinazioneGeoLoc = coordinate;
            Dao    dao = new Dao();
            string sql = "UPDATE Spedizioni SET DestinazioneGeoLoc = '" + this.DestinazioneGeoLoc + "' WHERE Id=" + this.Id;

            dao.ExecuteNonQuery(sql);
        }
Beispiel #12
0
        public void GeoCoder_PerfsTestsUsingMatchedNamesCache()
        {
            const string dbLocation1 = @"TestGeoLocationTool.sdf";

            connection = DBHelper.GetDbConnection(dbLocation1);
            GeoCoder geoCoder = new GeoCoder(connection);

            geoCoder.LoadGazetteerFile(@"TestGaz1.csv");
            Stopwatch watch = new Stopwatch();

            geoCoder.SetGazetteerColumns(
                new GazetteerColumnHeaders
            {
                Level1Code = "ID_1",
                Level2Code = "ID_2",
                Level3Code = "ID_3",
                Level1Name = "NAME_1",
                Level2Name = "NAME_2",
                Level3Name = "NAME_3"
            },
                false);


            foreach (
                string inputFile in
                new[]
                { @"TestInput1000.csv", @"TestInput10000.csv", @"TestInput50000.csv" })
            {
                geoCoder.LoadInputFileCsv(inputFile);
                geoCoder.SetInputColumns(geoCoder.DefaultInputColumnHeaders());

                // use cache
                watch.Restart();
                InputData.UseMatchedNamesCache = true;
                geoCoder.AddAllLocationCodes();
                var elapsed = watch.Elapsed.TotalSeconds;

                // don't use cache
                geoCoder.LoadInputFileCsv(inputFile);
                geoCoder.SetInputColumns(geoCoder.DefaultInputColumnHeaders());
                watch.Restart();
                InputData.UseMatchedNamesCache = false;
                geoCoder.AddAllLocationCodes();
                Debug.WriteLine(
                    "input file: " + inputFile + " cached: " + elapsed +
                    " vs " + "non cached: " + watch.Elapsed.TotalSeconds);
            }

            // Example results
            // input file: TestInput1000.csv cached: 0.0089728 vs non cached: 0.3835499
            // input file: TestInput10000.csv cached: 0.073879 vs non cached: 2.8980328
            // input file: TestInput50000.csv cached: 0.3852506 vs non cached: 14.464649
        }
Beispiel #13
0
        public async Task LookupSetsLocation()
        {
            var handler  = new FakeHttpMessageHandler(new AssemblyResources(this.GetType().GetTypeInfo().Assembly));
            var geocoder = new GeoCoder(handler, "xxxxx");

            var vm = new MainViewModel(geocoder)
            {
                Landmark = "Eiffel Tower"
            };
            await vm.Lookup();

            Assert.IsTrue(!string.IsNullOrEmpty(vm.Location));
        }
Beispiel #14
0
        public void GeoCoder_PerfsTestsUsingDictionaries()
        {
            connection = DBHelper.GetDbConnection(dbLocation);
            connection.InitializeDB();
            GeoCoder geoCoder = new GeoCoder(connection);

            geoCoder.LoadGazetteerFile(@"PHL_adm3.csv");
            //You need to copy this file manually
            Stopwatch watch = new Stopwatch();

            watch.Start();
            geoCoder.SetGazetteerColumns(
                new GazetteerColumnHeaders
            {
                Level1Code = "ID_1",
                Level2Code = "ID_2",
                Level3Code = "ID_3",
                Level1Name = "NAME_1",
                Level2Name = "NAME_2",
                Level3Name = "NAME_3"
            },
                false);

            Debug.WriteLine("Time to create dictionaries: " + watch.Elapsed.TotalSeconds);

            foreach (int linesCount in new[] { 500, 1000, 2000 })
            {
                geoCoder.LoadInputFileCsv(GenerateInputFile(linesCount));
                geoCoder.SetInputColumns(geoCoder.DefaultInputColumnHeaders());
                watch.Restart();
                geoCoder.AddAllLocationCodes();
                var elapsed = watch.Elapsed.TotalSeconds;
                //LocationCodes.useDictionaries = !LocationCodes.useDictionaries;
                geoCoder.LoadInputFileCsv(GenerateInputFile(linesCount));
                geoCoder.SetInputColumns(geoCoder.DefaultInputColumnHeaders());
                watch.Restart();
                geoCoder.AddAllLocationCodes();
                Debug.WriteLine(
                    linesCount + " input lines: " + elapsed + " vs " +
                    watch.Elapsed.TotalSeconds);
                // LocationCodes.useDictionaries = !LocationCodes.useDictionaries;

                foreach (var row in geoCoder.InputData.AsEnumerable())
                {
                    var elems = row.ItemArray;
                    Assert.IsFalse(elems[5] is DBNull);
                    Assert.IsFalse(elems[6] is DBNull);
                    Assert.IsFalse(elems[7] is DBNull);
                }
            }
        }
Beispiel #15
0
        public async Task NotFoundSetsErrorMessage()
        {
            var handler  = new FakeHttpMessageHandler(new AssemblyResources(this.GetType().GetTypeInfo().Assembly));
            var geocoder = new GeoCoder(handler, "key");

            var vm = new MainViewModel(geocoder)
            {
                Landmark = "This won't be found"
            };
            await vm.Lookup();

            Assert.IsTrue(!string.IsNullOrEmpty(vm.ErrorMessage));
            Assert.IsTrue(vm.ErrorMessage.Contains("404"));
        }
Beispiel #16
0
        public async Task RoundtripPostalCode()
        {
            MessageHandlerFactory.Mode = MessageHandlerMode.Capture;
            var handler = MessageHandlerFactory.CreateMessageHandler(new FileSystemResources(TestContext.TestRunDirectory));
            var service = new GeoCoder(handler, CredentialStore.RetrieveObject("bing.key.json").Key);

            var coord = await service.GetCoordinate(new Address()
            {
                postalCode = "55116", countryRegion = "US"
            });

            var address = await service.GetAddress(coord.Item1, coord.Item2);

            Assert.AreEqual("55116", address.postalCode);
        }
Beispiel #17
0
        public void GeoCoderDefault()
        {
            // Google Assert
            GeoCoder gc       = new GeoCoder();
            var      Expected = new{
                Latitude  = 30.267153,
                Longitude = -97.7430608
            };


            IGeoCodeResult Target = gc.GetCoordinates("Austin, TX");

            Assert.AreEqual(Expected.Latitude, Target.Latitude);
            Assert.AreEqual(Expected.Longitude, Target.Longitude);
        }
Beispiel #18
0
        public async Task ParseACanadianAddress()
        {
            var handler = SimpleIoc.Default.GetInstance<HttpMessageHandler>();
            var coord = new Tuple<double, double>(62.832908630371094, -95.913322448730469);
            using (var service = new GeoCoder(handler, CredentialStore.RetrieveObject("bing.key.json").Key, "Portable Bing GeoCoder unit tests", "en-CA", new UserContext(coord)))
            {
                var address = await service.ParseAddress("1950 Meadowvale Blvd., Mississauga, ON L5N 8L9");

                Assert.AreEqual("1950 Meadowvale Blvd", address.addressLine);
                Assert.AreEqual("Mississauga", address.locality);
                Assert.AreEqual("ON", address.adminDistrict);
                Assert.AreEqual("L5N 8L9", address.postalCode);
                Assert.AreEqual("Canada", address.countryRegion);
            }
        }
Beispiel #19
0
        public async Task ParseACanadianAddress()
        {
            var handler = SimpleIoc.Default.GetInstance <HttpMessageHandler>();
            var coord   = new Tuple <double, double>(62.832908630371094, -95.913322448730469);

            using (var service = new GeoCoder(handler, CredentialStore.RetrieveObject("bing.key.json").Key, "Portable Bing GeoCoder unit tests", "en-CA", new UserContext(coord)))
            {
                var address = await service.ParseAddress("1950 Meadowvale Blvd., Mississauga, ON L5N 8L9");

                Assert.AreEqual("1950 Meadowvale Blvd", address.addressLine);
                Assert.AreEqual("Mississauga", address.locality);
                Assert.AreEqual("ON", address.adminDistrict);
                Assert.AreEqual("L5N 8L9", address.postalCode);
                Assert.AreEqual("Canada", address.countryRegion);
            }
        }
Beispiel #20
0
        public void GeoCoderAlternate()
        {
            var Expected = new
            {
                Latitude  = 30.1968545,
                Longitude = -97.5975533560703
            };

            IGeoCodeResult Target = new GeoCodeResult();

            GeoCoder gc = new GeoCoder();

            gc.AddProvider(new OpenStreetMap());
            Target = gc.GetCoordinates("Austin, TX");
            Assert.AreEqual(Expected.Latitude, Target.Latitude);
            Assert.AreEqual(Expected.Longitude, Target.Longitude);
        }
Beispiel #21
0
        public void GeoCoderYahooPlaceFinder()
        {
            YahooPlaceFinderConfig yph = new YahooPlaceFinderConfig().SetKey(YahooAppId);
            YahooPlaceFinder       ypf = new Lucuma.Libs.YahooPlaceFinder(yph);

            GeoCoder g = new GeoCoder(ypf);

            var Expected = new {
                Latitude  = 30.267605,
                Longitude = -97.742984
            };

            IGeoCodeResult Target = new GeoCodeResult();

            Target = g.GetCoordinates("Austin, TX");
            Assert.AreEqual(Expected.Latitude, Target.Latitude);
            Assert.AreEqual(Expected.Longitude, Target.Longitude);
        }
Beispiel #22
0
        public void GeoCoderBingTest()
        {
            GeoCoder      gc  = new GeoCoder();
            BingMapConfig bmc = new BingMapConfig()
                                .SetKey(BingKey);

            gc.AddProvider(new BingMap(bmc));  // bing requires a key

            IGeoCodeResult Target = new GeoCodeResult();

            var Expected = new{
                Latitude  = 30.267599105834961,
                Longitude = -97.74298095703125
            };

            Target = gc.GetCoordinates("Austin, TX");
            Assert.AreEqual(Expected.Latitude, Target.Latitude);
            Assert.AreEqual(Expected.Longitude, Target.Longitude);
        }
Beispiel #23
0
        public void GeoCoderFirstFails()
        {
            var Expected = new {
                Latitude  = 30.1968545,
                Longitude = -97.5975533560703
            };

            IGeoCodeResult Target = new GeoCodeResult();

            GoogleGmapConfig gmc =
                new GoogleGmapConfig()
                .SetUrl("http://madps.googleapis.com/maps/api/geocode/json?address={0}&sensor=true");

            GeoCoder gc = new GeoCoder()
                          .AddProvider(new GoogleGmap(gmc))
                          .AddProvider(new OpenStreetMap());


            Target = gc.GetCoordinates("Austin, TX");
            Assert.AreEqual(Expected.Latitude, Target.Latitude);
            Assert.AreEqual(Expected.Longitude, Target.Longitude);
        }
Beispiel #24
0
        public void GeoCoderCodeAll_PerfsTests_TimeToCodeAll()
        {
            const string dbLocation1 = @"TestGeoLocationTool.sdf";

            connection = DBHelper.GetDbConnection(dbLocation1);

            GeoCoder geoCoder = new GeoCoder(connection);

            geoCoder.LoadGazetteerFile(@"TestGaz1.csv");
            Stopwatch watch = new Stopwatch();

            geoCoder.SetGazetteerColumns(
                new GazetteerColumnHeaders
            {
                Level1Code    = "ID_1",
                Level2Code    = "ID_2",
                Level3Code    = "ID_3",
                Level1Name    = "NAME_1",
                Level2Name    = "NAME_2",
                Level3Name    = "NAME_3",
                Level1AltName = "VARNAME_1",
                Level2AltName = "VARNAME_2",
                Level3AltName = "VARNAME_3"
            },
                false);

            geoCoder.LoadInputFileCsv("TestInput1.csv");
            geoCoder.SetInputColumns(geoCoder.DefaultInputColumnHeaders());
            watch.Start();
            geoCoder.AddAllLocationCodes();
            Debug.WriteLine(
                geoCoder.InputData.Rows.Count + " input lines: " +
                watch.Elapsed.TotalSeconds);

            // Example results
            // 25 input lines: 0.072016
        }
Beispiel #25
0
    public void SaveToLiteDB(int NumPage)
    {
        //Инициализация чтения Exel
        XSSFWorkbook xssfworkbook = null; //книга xlsx (2010+)
        HSSFWorkbook hssfworkbook = null; //книга xls (2007)
        string       path         = ConfigurationManager.AppSettings["StorageRoot"] + FName;
        string       ext          = Path.GetExtension(path);

        Status = TipExel.error;
        if (ext == ".xls")
        {
            using (FileStream file = new FileStream(path, System.IO.FileMode.Open, FileAccess.Read))
            {
                hssfworkbook = new HSSFWorkbook(file);
            }
            Status = TipExel.xsl;
        }
        if (ext == ".xlsx")
        {
            using (FileStream file = new FileStream(path, System.IO.FileMode.Open, FileAccess.Read))
            {
                xssfworkbook = new XSSFWorkbook(file);
            }
            Status = TipExel.xslx;
        }
        if (Status == TipExel.error)
        {
            return;
        }
        //Загрузка данных в БД===========================================================
        using (var db = new LiteDatabase(ConfigurationManager.AppSettings["LiteDB"]))
        {
            var head     = db.GetCollection <ExelHeaders>("H" + FName.GetHashCode());
            var col      = db.GetCollection <ExelRows>("C" + FName.GetHashCode());
            var AllCount = db.GetCollection <AllCount>("A" + FName.GetHashCode());
            var ADRCashe = db.GetCollection <AdressCashe>("AdresCashe");

            ISheet sheet = null;
            if (Status == TipExel.xsl)
            {
                sheet = hssfworkbook.GetSheetAt(NumPage);
            }
            if (Status == TipExel.xslx)
            {
                sheet = xssfworkbook.GetSheetAt(NumPage);
            }
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            int A = 0;
            while (rows.MoveNext())
            {
                A++;
            }
            ; rows.Reset(); A = A - 1;
            AllCount ALL = AllCount.FindOne(x => x.Id == 1);
            ALL.Value = A;
            AllCount.Update(ALL);

            int  idElement = 0;
            int  GeoHeader = -1;
            bool header    = true;
            while (rows.MoveNext())
            {
                IRow row = null;
                if (Status == TipExel.xsl)
                {
                    row = (HSSFRow)rows.Current;
                }
                if (Status == TipExel.xslx)
                {
                    row = (XSSFRow)rows.Current;
                }

                //Обработка заголовка файла:
                if (header)
                {
                    for (int j = 0; j < row.LastCellNum; j++)
                    {
                        var H = new ExelHeaders {
                            HeadName = GetTxtFromCell(row.GetCell(j))
                        };
                        if (H.HeadName.ToUpper().IndexOf("АДРЕС") >= 0)
                        {
                            GeoHeader = j;
                        }
                        head.Insert(H);
                    }
                    header = false;
                    continue;
                }
                //Обработка строк файла:
                if (GeoHeader >= 0)
                {
                    string   Adress = null, Error = null, Coord1 = null, Coord2 = null, AdresC = null;
                    bool     isGeoCode  = false;
                    string[] ColumnText = new string[row.LastCellNum];
                    for (int i = 0; i < row.LastCellNum; i++)
                    {
                        ColumnText[i] = GetTxtFromCell(row.GetCell(i));
                    }
                    Adress = ColumnText[GeoHeader];
                    if (Adress.Length >= 3)
                    {
                        AdresC = Adress.Trim().Replace(" ", "").ToUpper();
                        if (AdresC.IndexOf(",КВ.") > 0)
                        {
                            AdresC = AdresC.Remove(AdresC.IndexOf(",КВ."));
                        }
                        ;
                        AdressCashe F_Adr = ADRCashe.FindOne(x => x.Adress == AdresC);
                        if (F_Adr == null)
                        {
                            isGeoCode = GeoCoder.DecodeAdress(Adress, out Coord1, out Coord2, out Error);
                            if (isGeoCode)
                            {
                                var N_Adr = new AdressCashe
                                {
                                    Adress = AdresC,
                                    Coord1 = Coord1,
                                    Coord2 = Coord2
                                };
                                ADRCashe.Insert(N_Adr);
                            }
                        }
                        else
                        {
                            isGeoCode = true;
                            Adress    = F_Adr.Adress;
                            Coord1    = F_Adr.Coord1;
                            Coord2    = F_Adr.Coord2;
                        }
                    }
                    else
                    {
                        Error = "Мало букв в адресе";
                    }
                    var C = new ExelRows
                    {
                        ColumnValue = ColumnText,
                        Adress      = Adress,
                        Coord1      = Coord1,
                        Coord2      = Coord2,
                        isGeoCode   = isGeoCode,
                        Error       = Error
                    };
                    col.Insert(C);
                    idElement++;
                }
            }//Геокодирование и добавление полей результатов:
            ADRCashe.EnsureIndex(x => x.Adress);
            ALL.Value = idElement;
            AllCount.Update(ALL);
        } //Открытие БД LiteDB
    }
Beispiel #26
0
        // GET api/<controller>
        public IGeoCodeResult Query(GeoQuery q)
        {
            string             key      = string.Empty;
            string             query    = string.Empty;
            string             provider = "Google";
            IGeoProviderConfig config;
            IGeoProvider       GeoProvider = null;

            IGeoCodeResult result = new GeoCodeResult();


            if (!String.IsNullOrEmpty(q.Query) && !String.IsNullOrEmpty(q.Providers))
            {
                query = q.Query;
                // we have a search
                provider = q.Providers.Replace("KEY", "");
                if (q.Providers.Contains("KEY"))
                {
                    key = q.Key;
                }

                switch (provider)
                {
                case "Google":
                    config      = new GoogleGmapConfig();
                    GeoProvider = new GoogleGmap(config);
                    break;

                case "Bing":
                    config      = new BingMapConfig().SetKey(key);
                    GeoProvider = new BingMap(config);
                    break;

                case "MapQuest":
                    config      = new MapQuestConfig().SetKey(key);
                    GeoProvider = new MapQuestMap(config);
                    break;

                case "Open Streets":
                    config      = new OpenStreetMapConfig().SetUserAgent("your email here yo");
                    GeoProvider = new OpenStreetMap(config);
                    break;

                case "YahooPlaces":
                    config      = new YahooPlaceFinderConfig().SetKey(key);
                    GeoProvider = new YahooPlaceFinder(config);
                    break;

                case "CloudMade":
                    config      = new CloudMadeConfig().SetKey(key);
                    GeoProvider = new CloudMade(config);
                    break;
                }

                GeoProvider = GeoProvider != null ? GeoProvider : new GoogleGmap();

                GeoCoder gc = new GeoCoder(GeoProvider);

                result = gc.GetCoordinates(query);
            }
            return(result);
        }
Beispiel #27
0
        CodeAll_CorrectAndMissSpeltInputWithSavedMatchesForMissSpellings_AllCodesAdded
            ()
        {
            // arrange
            GeoCoder geoCoder =
                new GeoCoder(MockRepository.GenerateStub <IDbConnection>() as DbConnection);
            InputColumnHeaders     inputColumnHeaders     = InputColumnNames();
            GazetteerColumnHeaders gazetteerColumnHeaders = GazetteerColumnNames();

            // create input test data with
            // line 1, all names correct
            // line 2, all names correct
            // line 3, all names miss-spelt
            string[] names1 = { "P1", "T1", "V1" };
            string[] names2 = { "P2", "T2", "V2" };
            string[] names3 = { "P1x", "T1x", "V1x" };
            string[] codes1 = { "1", "10", "100" };
            string[] codes2 = { "2", "20", "200" };

            InputTestData inputTestData = new InputTestData();

            inputTestData.AddLine(names1);
            inputTestData.AddLine(names2);
            inputTestData.AddLine(names3);
            geoCoder.SetInputData(inputTestData.Data(inputColumnHeaders));
            geoCoder.SetInputColumns(inputColumnHeaders);

            // create gazetteer data
            GazetteerRecords gazetteerRecords = new GazetteerRecords();

            gazetteerRecords.AddLine(names1, codes1);
            gazetteerRecords.AddLine(names2, codes2);
            geoCoder.SetGazetteerData(gazetteerRecords.Data(gazetteerColumnHeaders));

            // add records matching input line 3 names to gazetteer names 1
            MatchProviderTestData matchProviderTestData = new MatchProviderTestData();

            matchProviderTestData.AddLevel1(names3, names1);
            matchProviderTestData.AddLevel2(names3, names1);
            matchProviderTestData.AddLevel3(names3, names1);

            MatchProviderStub matchProviderStub = new MatchProviderStub(matchProviderTestData);

            geoCoder.SetMatchProvider(matchProviderStub.MatchProvider());

            geoCoder.SetGazetteerColumns(gazetteerColumnHeaders, false);

            // act
            geoCoder.AddAllLocationCodes();

            // assert
            var columns = geoCoder.LocationCodeColumnHeaders();

            //line 1 - should contain codes 1
            DataRow line1 = geoCoder.InputData.Rows[0];

            Assert.AreEqual(codes1[0], line1[columns.Level1]);
            Assert.AreEqual(codes1[1], line1[columns.Level2]);
            Assert.AreEqual(codes1[2], line1[columns.Level3]);

            //line 2 - should contain codes 2
            DataRow line2 = geoCoder.InputData.Rows[1];

            Assert.AreEqual(codes2[0], line2[columns.Level1]);
            Assert.AreEqual(codes2[1], line2[columns.Level2]);
            Assert.AreEqual(codes2[2], line2[columns.Level3]);

            //line 3 - should contain codes 1
            DataRow line3 = geoCoder.InputData.Rows[2];

            Assert.AreEqual(codes1[0], line3[columns.Level1]);
            Assert.AreEqual(codes1[1], line3[columns.Level2]);
            Assert.AreEqual(codes1[2], line3[columns.Level3]);
        }
Beispiel #28
0
        public static AreaInfo GetAreaInfo(double Latitude, double Longitude, bool bCheckDbCache = true)
        {
            DateTime tStart = DateTime.Now;

            if (bCheckDbCache)
            {
                try
                {
                    var cache = db.dbAreaCache.Query <AreaInfo>("select * from AreaInfo where boxWest <= ? and boxNorth >= ? and boxEast >= ? and boxSouth <= ?", Longitude, Latitude, Longitude, Latitude);
                    cache.ToString();
                    if (cache.Count > 0)
                    {
                        //xLog.Debug("AreaCacheCheck Volltreffer");
                        if (cache.Count > 1)
                        {
                            cache.ToString();
                        }
                        var ret = cache[0];
                        ret.OnInstanceCreatedDB();
                        return(ret);
                    }
                }
                catch (Exception e)
                {
                    xLog.Error(e);
                }
                finally
                {
                    TimeSpan tsCacheCheck = DateTime.Now - tStart;
                    xLog.Debug("AreaCacheCheck took " + tsCacheCheck.TotalMilliseconds.ToString() + "ms");
                }
            }

            tStart = DateTime.Now;

            try
            {
                var ai = GeoCoder.GetAreaInfo(Latitude, Longitude);

                try
                {
                    var delS = db.dbAreaCache.Query <AreaInfo>("select * from AreaInfo where boxWest = ? and boxNorth = ? and boxEast = ? and boxSouth = ?", ai.boxWest, ai.boxNorth, ai.boxEast, ai.boxSouth);
                    if (delS.Count > 0)
                    {
                        db.dbAreaCache.Delete <AreaInfo>(delS);
                    }
                }
                catch (Exception e) { e.ToString(); }

                try
                {
                    if (Location.CalculateDistance(ai.boxSouth, ai.boxWest, ai.boxNorth, ai.boxEast, DistanceUnits.Kilometers) < 25)
                    {
                        db.dbAreaCache.Insert(ai);
                    }
                }
                catch (Exception e) { e.ToString(); }

                TimeSpan tsOnlineCheck = DateTime.Now - tStart;
                xLog.Debug("AreaCheckOnline took " + tsOnlineCheck.TotalMilliseconds.ToString() + "ms");

                if (ai.boxWest <= Longitude && ai.boxNorth >= Latitude && ai.boxEast >= Longitude && ai.boxSouth <= Latitude)
                {
                    ai.ToString(); //in the box
                }
                else
                {
                    ai.ToString(); //outside the box
                }
                return(ai);
            }
            catch (Exception e)
            {
                e.ToString();

                AreaInfo ai = new AreaInfo();

                return(ai);
            }
        }
 public void ConvertIPAddressToGeoCoordinatesTest()
 {
     GeoCoder geo = new GeoCoder();
     var coords = geo.ConvertIPAddressToGeoCoordinates("11.11.11.11");
 }