Esempio n. 1
0
        public void TestGeocoderUSInvoke()
        {
            Console.WriteLine("Test - GeocoderUS Invoke");
            GeocodeRequest gr = new GeocodeRequest();
            gr.Address = "1 Main st.";
            gr.City = "Burlington";
            gr.State = "VT";
            gr.PostalCode = "05401";

            GeocodeResponse gRes = _geocoderUS.Geocode(gr);
            TestUtils.OutputGeocodeResponses(gRes);
            Assert.IsTrue(gRes.HasCandidates, "Geocoder US geocoder returned no responses");
        }
Esempio n. 2
0
        public void TestGoogleGeocoderInvoke()
        {
            Console.WriteLine("Test - Google Geocoder Invoke");
            GeocodeRequest gr = new GeocodeRequest();

            gr.TextString = "1 main st., Burlington, vt";

            GeocodeResponse gRes = _googleGeocoder.Geocode(gr);

            TestUtils.OutputGeocodeResponses(gRes);
            Assert.IsTrue(gRes.Candidates.Count == 1, "Expected the geocoder to return 3 results");

            Assert.AreEqual("premise", gRes.Candidates[0].MatchType, "Expected the first match to have the type 'premise'");
        }
Esempio n. 3
0
        private void btCalcularOrcamento_Click(object sender, EventArgs e)
        {
            markerOverlay = new GMapOverlay("Marcador");


            var origem = geocoder.Geocode(txtOrigem.Text).First();

            inicio = new PointLatLng(origem.LatLng.Latitude, origem.LatLng.Longitude);

            var destino = geocoder.Geocode(txtDestino.Text).First();

            final = new PointLatLng(destino.LatLng.Latitude, destino.LatLng.Longitude);


            GMarkerGoogle markerOrigem = new GMarkerGoogle(inicio, GMarkerGoogleType.green);

            markerOrigem.Position    = inicio;
            markerOrigem.ToolTipMode = MarkerTooltipMode.Always;
            markerOrigem.ToolTipText = string.Format("Origem: \n {0}", txtOrigem.Text);
            markerOverlay.Markers.Add(markerOrigem);

            GMarkerGoogle markerDestino = new GMarkerGoogle(final, GMarkerGoogleType.red);

            markerDestino.Position    = final;
            markerDestino.ToolTipMode = MarkerTooltipMode.Always;
            markerDestino.ToolTipText = string.Format("Destino: \n {0}", txtOrigem.Text);
            markerOverlay.Markers.Add(markerDestino);

            GDirections direction;

            var         RotasDirection = GMapProviders.GoogleMap.GetDirections(out direction, inicio, final, false, false, false, false, false);
            GMapRoute   RotaObtida     = new GMapRoute(direction.Route, "Rota Obtida");
            GMapOverlay CamadaRotas    = new GMapOverlay("Camada da Rota");

            CamadaRotas.Routes.Add(RotaObtida);

            gMapControl.Overlays.Add(markerOverlay);
            gMapControl.Overlays.Add(CamadaRotas);

            gMapControl.Zoom = gMapControl.Zoom + 1;
            gMapControl.Zoom = gMapControl.Zoom - 1;


            double valorTotal = CalculoOrcamento.CalcularOrcamento(RotaObtida.Distance, cbVeiculo.SelectedValue);

            lbDistancia.Text = Math.Round(RotaObtida.Distance, 2).ToString() + "KM";
            lbValor.Text     = valorTotal.ToString();
        }
Esempio n. 4
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim().Equals(string.Empty))
            {
                MessageBox.Show("Lütfen bir adres giriniz!");
                return;
            }

            string address      = textBox1.Text.Trim();
            string fixedAddress = FixAddress(address);

            AddressLevel  addressLevel = tokenizer.ParseAddress(fixedAddress);
            List <string> list         = tokenizer.NotParsedList;

            list = geocoder.CheckForCity(list, ref addressLevel);

            if (!addressLevel.Il.Equals(string.Empty))
            {
                list = geocoder.CheckForTown(list, ref addressLevel);
            }

            addressLevel = geocoder.Geocode(addressLevel);

            FillScreen(addressLevel);
        }
        public void TestReplacement()
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(@"
            <components>
                <component name='Geocoder'>
                    <parameter name='DummyGeocoder' value='Azavea.Open.Geocoding.Tests.GeocoderSourceDummy,Azavea.Open.Geocoding' />
                </component>

                <component name='DummyGeocoder'>
                    <parameter name='CandidateTextReplacer' value='Azavea.Open.Geocoding.Processors.CandidateTextReplacer,Azavea.Open.Geocoding' />
                </component>

                <component name='CandidateTextReplacer'>
                    <parameter name='ReplaceField' value='Address' />
                    <parameter name='Find' value='340' />
                    <parameter name='ReplaceWith' value='680' />
                </component>
            </components>
            ");
            Config gcCfg = new Config("GcConfig", doc);
            Geocoder gc = new Geocoder(gcCfg, "Geocoder");

            GeocodeRequest gReq = new GeocodeRequest();
            gReq.Address = "340 N 12th St";
            IList<GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates;
            Assert.AreEqual(1, candidates.Count);
            Assert.AreEqual("680 N 12th St", candidates[0].Address);
        }
Esempio n. 6
0
        public void TestReplacementWithExpansion()
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(@"
            <components>
                <component name='Geocoder'>
                    <parameter name='DummyGeocoder' value='Azavea.Open.Geocoding.Tests.GeocoderSourceDummy,Azavea.Open.Geocoding' />
                </component>

                <component name='DummyGeocoder'>
                    <parameter name='CandidateTextReplacer' value='Azavea.Open.Geocoding.Processors.CandidateTextReplacer,Azavea.Open.Geocoding' />
                </component>

                <component name='CandidateTextReplacer'>
                    <parameter name='ReplaceField' value='StandardizedAddress' />
                    <parameter name='Find' value='^' />
                    <parameter name='ReplaceWith' value='{Address}, {PostalCode}, {Country}' />
                </component>
            </components>
            ");
            Config   gcCfg = new Config("GcConfig", doc);
            Geocoder gc    = new Geocoder(gcCfg, "Geocoder");

            GeocodeRequest gReq = new GeocodeRequest();

            gReq.Address = "340 N 12th St";
            IList <GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates;

            Assert.AreEqual(1, candidates.Count);
            Assert.AreEqual("340 N 12th St, 19107, USA", candidates[0].StandardizedAddress);
        }
Esempio n. 7
0
        public void TestGoogleGeocoderInvoke()
        {
            Console.WriteLine("Test - Google Geocoder Invoke");
            GeocodeRequest gr = new GeocodeRequest();

            gr.TextString = "1 main st., Burlington, vt";

            GeocodeResponse gRes = _googleGeocoder.Geocode(gr);

            TestUtils.OutputGeocodeResponses(gRes);
            Assert.IsTrue(gRes.HasCandidates, "Google Geocoder returned no responses");
            Assert.AreEqual("Address", gRes.Candidates[0].MatchType, "Google Geocoder didn't return proper MatchType");
        }
Esempio n. 8
0
        private static async Task <GeocoderResponse> CallApi(string apiKey, string query)
        {
            GeocoderResponse response = null;
            var gc = new Geocoder(apiKey);
            await Task.Run(() => { response = gc.Geocode(query); });

            return(response);
        }
Esempio n. 9
0
 /// <summary>
 /// An edit was made to the InputField.
 /// Unity will send the string from _inputField.
 /// Make geocoder query.
 /// </summary>
 /// <param name="searchString">Search string.</param>
 private void HandleUserInput(string searchString)
 {
     _hasResponse = false;
     if (!string.IsNullOrEmpty(searchString))
     {
         _coordinate     = Conversions.StringToLatLon(searchString);
         _resource.Query = _coordinate;
         _geocoder.Geocode(_resource, HandleGeocoderResponse);
     }
 }
Esempio n. 10
0
        public void TestLoadDummyGeocoderWithProcessorWithConfig()
        {
            Config dummyConfig = new Config("../../Tests/TestConfig.config", "TestConfig");
            Geocoder gc = new Geocoder(dummyConfig, "GeocoderSourcesWithProcessorsWithConfigs");

            GeocodeRequest gReq = new GeocodeRequest();
            gReq.Address = "tS ht21 N 043";
            IList<GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates;
            Assert.AreEqual(1, candidates.Count);
        }
Esempio n. 11
0
        public void TestLoadDummyGeocoder()
        {
            Config dummyConfig = new Config("../../Tests/TestConfig.config", "TestConfig");
            Geocoder gc = new Geocoder(dummyConfig);

            GeocodeRequest gReq = new GeocodeRequest();
            gReq.Address = "340 N 12th St";
            IList<GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates;
            Assert.AreEqual(1, candidates.Count);
        }
Esempio n. 12
0
        private void gMap_Load(object sender, EventArgs e)
        {
            // Initialize map:
            gMap.MapProvider             = GMap.NET.MapProviders.GoogleMapProvider.Instance;
            GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
            //gMap.SetPositionByKeywords("Bogota, Colombia");
            var location = geocoder.Geocode("Bogota, Colombia");

            double lat = location.First().LatLng.Latitude;
            double lgn = location.First().LatLng.Longitude;

            gMap.Position = new GMap.NET.PointLatLng(lat, lgn);

            //Cambiando opciones del Gmap, no mostrar el centro y cambiando el boton derecho a izquierdo para mover el mapa.
            gMap.ShowCenter = false;
            gMap.DragButton = MouseButtons.Left;
            addMarkers(t.Accidents);
            gMap.Overlays.Add(markerOverlay);
        }
Esempio n. 13
0
        public void TestLoadDummyGeocoder()
        {
            Config dummyConfig = new Config("../../Tests/TestConfig.config", "TestConfig");
            Geocoder gc = new Geocoder(dummyConfig);

            GeocodeRequest gReq = new GeocodeRequest();
            gReq.Address = "340 N 12th St";
            IList<GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates;
            Assert.AreEqual(1, candidates.Count);
        }
Esempio n. 14
0
        public void TestLoadDummyGeocoderWithProcessorWithConfig()
        {
            Config dummyConfig = new Config("../../Tests/TestConfig.config", "TestConfig");
            Geocoder gc = new Geocoder(dummyConfig, "GeocoderSourcesWithProcessorsWithConfigs");

            GeocodeRequest gReq = new GeocodeRequest();
            gReq.Address = "tS ht21 N 043";
            IList<GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates;
            Assert.AreEqual(1, candidates.Count);
        }
Esempio n. 15
0
            /// <summary>
            /// 从System.Data.DataTable导入数据到数据库
            /// </summary>
            /// <param name="dt"></param>
            /// <returns></returns>
            public int InsetData(System.Data.DataTable dt)
            {
                int    i          = 0;
                string name       = "";
                string address    = "";
                string suburb     = "";
                string facilities = "";
                string lat        = "";
                string lon        = "";
                int    activityId = 0;

                foreach (DataRow dr in dt.Rows)
                {
                    name       = dr["name"].ToString().Trim();
                    address    = dr["address"].ToString().Trim();
                    suburb     = dr["suburb"].ToString().Trim();
                    facilities = dr["facilities"].ToString().Trim();
                    activityId = Int32.Parse(dr["Activity_id"].ToString().Trim());
                    var geocoder  = new Geocoder("AIzaSyDJeTABC7AwjSI-x7dm2cVlbHvA3yN65HA");
                    var locations = geocoder.Geocode(address);
                    if (locations.Count() != 0)
                    {
                        lon = (locations.ToList()[0].LatLng.Longitude).ToString("f9");
                        lat = (locations.ToList()[0].LatLng.Latitude).ToString("f9");
                        //sw = string.IsNullOrEmpty(sw) ? "null" : sw;
                        //kr = string.IsNullOrEmpty(kr) ? "null" : kr;
                        string        strSql        = string.Format("Insert into Places (Name,Address,Facility,Suburb,ActivityActivityId,Lat,Lon) Values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", name, address, facilities, suburb, activityId, lat, lon);
                        string        strConnection = ConfigurationManager.ConnectionStrings["FamilyGoModel"].ToString();
                        SqlConnection sqlConnection = new SqlConnection(strConnection);
                        try
                        {
                            // SqlConnection sqlConnection = new SqlConnection(strConnection);
                            sqlConnection.Open();
                            SqlCommand sqlCmd = new SqlCommand();
                            sqlCmd.CommandText = strSql;
                            sqlCmd.Connection  = sqlConnection;
                            SqlDataReader sqlDataReader = sqlCmd.ExecuteReader();
                            i++;
                            sqlDataReader.Close();
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                        finally
                        {
                            sqlConnection.Close();
                        }
                    }

                    //if (opdb.ExcSQL(strSql))
                    // i++;
                }
                return(i);
            }
        public static void Main(string[] args)
        {
            var gc = new Geocoder("YOURKEYHERE");
            // simplest example with no optional parameters
            var result = gc.Geocode("newcastle");

            result.PrintDump();

            //  example with lots of optional parameters
            var result2 = gc.Geocode("newcastle", countrycode: "gb", limit: 2, minConfidence: 6, language: "en", abbrv: true, noAnnotations: true, noRecord: true, addRequest: true);

            result2.PrintDump();

            var reserveresult = gc.ReverseGeocode(51.4277844, -0.3336517);

            reserveresult.PrintDump();

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
        }
Esempio n. 17
0
        private void btnSaveStart_Click(object sender, EventArgs e)
        {
            var location = geocoder.Geocode(txtCurrentAddress.Text);

            current         = GetAddressPoints(txtCurrentAddress.Text);
            start           = current;
            map.DragButton  = MouseButtons.Left;
            map.MapProvider = GMapProviders.BingMap;
            map.Position    = new PointLatLng(current.Lat, current.Lng);
            map.MinZoom     = 5;
            map.MaxZoom     = 100;
            map.Zoom        = 17;
            PointLatLng point   = new PointLatLng(current.Lat, current.Lng);
            GMapMarker  marker  = new GMarkerGoogle(point, GMarkerGoogleType.arrow);
            GMapOverlay markers = new GMapOverlay("markers");

            markers.Markers.Add(marker);
            map.Overlays.Add(markers);
            txtCurrentAddress.Enabled = false;
            map.Refresh();
        }
Esempio n. 18
0
 /// <summary>
 /// An edit was made to the InputField.
 /// Unity will send the string from _inputField.
 /// Make geocoder query.
 /// </summary>
 /// <param name="searchString">Search string.</param>
 void HandleUserInput(string searchString)
 {
     _hasResponse = false;
     if (!string.IsNullOrEmpty(searchString))
     {
         var latLon = searchString.Split(',');
         _coordinate.x   = double.Parse(latLon[0]);
         _coordinate.y   = double.Parse(latLon[1]);
         _resource.Query = _coordinate;
         _geocoder.Geocode(_resource, HandleGeocoderResponse);
     }
 }
Esempio n. 19
0
        /// <summary>
        /// Main entry point.
        /// </summary>
        /// <param name="args">Arguments of the program.</param>
        static void Main(string[] args)
        {
            // Create new Geocoder and pass GOOGLE_MAPS_API_KEY(in this example it's stored in .config)
            IGeocoder geocoder = new Geocoder(ConfigurationManager.AppSettings["GOOGLE_MAPS_API_KEY"]);

            // Get GeocodeResponse C# object from address or from Latitude Longitude(reverse geocoding)
            GeocodeResponse response = geocoder.Geocode("1984 west armitage ave chicago il");
            GeocodeResponse reversGeocoderesponse = geocoder.ReverseGeocode(40.714224, -73.961452);

            // You can then query the response to get what you need
            double latitude = response.Results[0].Geometry.Location.Lat;
            string address  = reversGeocoderesponse.Results[1].FormattedAddress;

            // ..or you can get a response in JSON, XML string foramt(for whatever reason) and "play" with it
            string responseJson       = geocoder.Geocode("1984 west armitage ave chicago il", ResponseFormat.JSON);
            string reverseResponseXml = geocoder.ReverseGeocode(40.714224, -73.961452, ResponseFormat.XML);

            // Then you can deserialize it to C# object again
            GeocodeResponse geocodeFromJson       = geocoder.FromJson(responseJson);
            GeocodeResponse reverseGeocodeFromXml = geocoder.FromXml(reverseResponseXml);
        }
Esempio n. 20
0
        // Fonction qui ajoute un cabinet a la BDD et qui utilise l'API Google Maps
        private void validerbutton_Click(object sender, EventArgs e)
        {
            var        geocoder   = new Geocoder("AIzaSyDoOuaAcFk-apUd7qNPaVnJcPV7a8iUTn0");
            var        locations  = geocoder.Geocode(adresseBox.Text);
            string     lat        = locations.First().LatLng.Latitude.ToString();
            string     lon        = locations.First().LatLng.Longitude.ToString();
            string     adresse    = locations.First().LocationName.ToString().Split(',').First();
            string     request    = "insert into cabinet (adresse,code_postal,ville,latitude,longitude) values (\"" + adresse + "\",\"" + cPostalBox.Text + "\",\"" + villeBox.Text + "\",\"" + lat + "\",\"" + lon + "\")";
            BddRequest newCabinet = new BddRequest();

            newCabinet.DataRequest(request);
            this.Close();
        }
Esempio n. 21
0
        public static void Main(string[] args)
        {
            var gc     = new Geocoder("924d139f8c45a512fd0fe1cfc6eb741f");
            var result = gc.Geocode("newcastle", country: "GBR");

            result.PrintDump();

            var reserveresult = gc.ReverseGeocode(51.4277844, -0.3336517);

            reserveresult.PrintDump();

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
        }
Esempio n. 22
0
    public void ForwardGeocoder()
    {
        var input          = this.GetComponent <InputField>();
        var forwardGeocode = new ForwardGeocodeResource(input.text);

        var slippy = GameObject.Find("Slippy").GetComponent <Slippy>();

        fs.AccessToken = slippy.Token;

        geocoder.Geocode(forwardGeocode, (ForwardGeocodeResponse res) =>
        {
            if (res.Features.Count > 0)
            {
                slippy.SetCenter(res.Features[0].Center);
            }
        });
    }
Esempio n. 23
0
        public AddressLevel Geocode(string address)
        {
            string fixedAddress = Fixer.Prepare(address);

            AddressLevel  addressLevel = tokenizer.ParseAddress(fixedAddress);
            List <string> list         = tokenizer.NotParsedList;

            list = geocoder.CheckForCity(list, ref addressLevel);

            if (!addressLevel.Il.Equals(string.Empty))
            {
                list = geocoder.CheckForTown(list, ref addressLevel);
            }

            addressLevel = geocoder.Geocode(addressLevel);

            return(addressLevel);
        }
Esempio n. 24
0
        public static Coordenada ObtenerCoordenada(string direccion)
        {
            try
            {
                string          apiKey   = "AIzaSyAm9iOzpnEzKPKWmwKhPOVW811qMoxvZDM";
                IGeocoder       geocoder = new Geocoder(apiKey);
                GeocodeResponse response = geocoder.Geocode(direccion);

                Coordenada coordenadas = new Coordenada();
                coordenadas.lat = response.Results[0].Geometry.Location.Lat;
                coordenadas.lng = response.Results[0].Geometry.Location.Lng;

                return(coordenadas);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Esempio n. 25
0
        public OpenCageResponseForward GetCoordinateFromAddress([FromQuery] string address, [FromQuery] string openCageApiKey)
        {
            var gc            = new Geocoder(openCageApiKey);
            var forwardResult = gc.Geocode(address);

            var geometry         = forwardResult.Results.FirstOrDefault()?.Geometry;
            var openCageResponse = new OpenCageResponseForward()
            {
                StatusCode    = forwardResult.Status.Code,
                StatusMessage = forwardResult.Status.Message
            };

            if (geometry != null)
            {
                openCageResponse.Latitude  = Convert.ToDecimal(geometry.Latitude);
                openCageResponse.Longitude = Convert.ToDecimal(geometry.Longitude);
            }
            return(openCageResponse);
        }
Esempio n. 26
0
        private void validerbutton_Click(object sender, EventArgs e)
        {
            var        geocoder      = new Geocoder("AIzaSyDoOuaAcFk-apUd7qNPaVnJcPV7a8iUTn0");
            var        locations     = geocoder.Geocode(cabinetAdresseBox.Text);
            string     lat           = locations.First().LatLng.Latitude.ToString();
            string     lon           = locations.First().LatLng.Longitude.ToString();
            string     adresse       = locations.First().LocationName.ToString().Split(',').First();
            BddRequest updateCabinet = new BddRequest();
            string     request       = "UPDATE cabinet set adresse= \"" + adresse + "\",code_postal= '" + cabinetCPBox.Text + "',ville=\"" + cabinetVillebox.Text + "\",longitude=\"" + lon + "\",latitude=\"" + lat + "\" where id = " + id;

            updateCabinet.DataRequest(request);
            MessageBox.Show("Vos informations ont été enregistrées avec succès");
            utilisateurAccueil accueil    = Application.OpenForms["utilisateurAccueil"] as utilisateurAccueil;
            utilisateurAccueil newaccueil = new utilisateurAccueil();
            var upt = this;

            accueil.willCloseduti = false;
            accueil.Close();
            newaccueil.Show();
            upt.Close();
        }
Esempio n. 27
0
        public Geo GetClienteLocalizacao()
        {
            try
            {
                IGeocoder geocoder = new Geocoder(ChaveGoogle);

                ObjUsuario.Id = ObjGeo.IdUsr;
                ObjUsuario    = new ManterUsuarioDAO(ObjUsuario).ConsultaUsuarioByIdDAO();

                GeocodeResponse response = geocoder.Geocode(ObjUsuario.Endereco);

                ObjGeo.NomeUsuario = ObjUsuario.Nome;
                ObjGeo.Endereco    = ObjUsuario.Endereco;
                ObjGeo.Latitude    = response.Results[0].Geometry.Location.Lat.ToString().Replace(",", ".");
                ObjGeo.Longitude   = response.Results[0].Geometry.Location.Lng.ToString().Replace(",", ".");

                return(ObjGeo);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 28
0
    // ---

    public static IPromise <LatLong> GetLatLongForAddress(string streetAddress, string city, string country)
    {
        // Get access singleton (object that holds a token and associated geocoder).
        MapboxAccess access   = MapboxAccess.Instance;
        Geocoder     geocoder = access.Geocoder;

        var promise = new Promise <LatLong>();

        string forwardGeocodeQuery = $"{streetAddress} {city} {country}";

        Debug.Log($"Performing forward geocode with query \"{forwardGeocodeQuery}\"");
        ForwardGeocodeResource forwardGeocode = new ForwardGeocodeResource(forwardGeocodeQuery);

        geocoder.Geocode(forwardGeocode, (ForwardGeocodeResponse response) => {
            /*
             * Debug.Log($"Forward geocode response has features:");
             * foreach (Feature feature in response.Features) {
             *  Debug.Log($" - {feature.Id} {feature.PlaceName} {feature.Address} {feature.Center}");
             * }
             */

            // There are lots of interesting types of features returned by the API, places, POIs, localities, etc.
            // I'm assuming they're ordered by relevance, so let's just pick the first one.
            if (response.Features.Count > 0)
            {
                Feature chosenFeature = response.Features[0];
                Vector2d coordinates  = chosenFeature.Center;
                promise.Resolve(new LatLong((float)coordinates.x, (float)coordinates.y));
            }
            else
            {
                promise.Resolve(new LatLong());
            }
        });

        return(promise);
    }
Esempio n. 29
0
        static void Main(string[] args)
        {
            // Initiate Geocoder Class
            var geocoder = new Geocoder("My API KEY");

            // Lists to Hold Addresses and Geocodes
            List <Address>   Addresses    = new List <Address>();
            List <Locations> LocationList = new List <Locations>();

            // SQL to add to SitesList

            using (SqlConnection sqlConnection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Con1"].ConnectionString))
            {
                sqlConnection2.Open();

                using (SqlCommand command = new SqlCommand("SELECT CONCAT(StreetAddress,' ',City + ', ',State + ' ',Zip) as 'Full Address' FROM [FM_OPERATIONS].[dbo].[xRef_MasterFile] where Latitude is null", sqlConnection2))
                {
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Addresses.Add(new Address(reader.GetString(0)));
                        }
                    }
                }
                sqlConnection2.Close();
            }



            // Run Address List to Gooogle API

            foreach (var item in Addresses)
            {
                var x = geocoder.Geocode(item.PostalAddress);

                var y = x.ElementAt(0).LatLng.ToString().Trim().Split(',');

                Console.WriteLine("{0}|{1}|{2}", item.PostalAddress, Convert.ToDouble(y[0]), Convert.ToDouble(y[1]));
            }

            /*
             * foreach (var item in LocationList)
             * {
             *  Console.WriteLine("{0}|{1}|{2}", item.SiteName, item.Latitude, item.Longitude);
             * }
             */



            /* Test Examples for Data Structure
             *
             * var address = geocoder.Geocode("21000 Twelve Mile Rd., MI");
             * address.ElementAt(0);
             *
             * Console.WriteLine(address);
             * Console.WriteLine(address.GetType());
             * var stp = address.ElementAt(0);
             *
             * var output = stp.LatLng.ToString().Trim().Split(',');
             *
             * Console.WriteLine("Latitude: {0}",output[0].Trim());
             * Console.WriteLine("Longitude: {0}",output[1].Trim());
             *
             *
             * foreach (var item in Addresses)
             * {
             *  Console.WriteLine(item.PostalAddress);
             * }
             */



            Console.ReadLine();
        }
Esempio n. 30
0
 public AddressLevel Geocoder(AddressLevel addressLevel)
 {
     return(geocoder.Geocode(addressLevel));
 }
Esempio n. 31
0
        private void Button_Click(object sender, RoutedEventArgs e)

        {
            if (this.TimeTextBox.Text == "")
            {
                MessageBox.Show("No text in Time");
            }
            else
            if (this.Date.Text == "")
            {
                MessageBox.Show("No text in Date");
            }


            else
            {
                var      h   = int.Parse(this.TimeTextBox.Text[0].ToString()) * 10 + int.Parse(this.TimeTextBox.Text[1].ToString());
                var      m   = int.Parse(this.TimeTextBox.Text[3].ToString()) * 10 + int.Parse(this.TimeTextBox.Text[4].ToString());
                Random   rnd = new Random();
                int      x   = rnd.Next(0, 59);
                DateTime dt  = new DateTime(FactoryBl.GetBL().ChangeDateToNumber(this.Date.ToString()).Year, FactoryBl.GetBL().ChangeDateToNumber(this.Date.ToString()).Month, FactoryBl.GetBL().ChangeDateToNumber(this.Date.ToString()).Day, h, m, x);
                if (dt.Day == DateTime.Now.Day && dt.Month == DateTime.Now.Month && dt.Year == DateTime.Now.Year && dt.Hour == DateTime.Now.Hour && dt.Minute - 5 > DateTime.Now.Minute || dt.Day == DateTime.Now.Day && dt.Month == DateTime.Now.Month && dt.Year == DateTime.Now.Year && dt.Hour > DateTime.Now.Hour && dt.Minute - 5 > 0)
                {
                    MessageBox.Show("Date not vailed");
                }
                else
                if (this.IntensityTextBox.Text == "" || int.Parse(this.IntensityTextBox.Text) < 1)
                {
                    MessageBox.Show("worng intensity");
                }
                else
                if (this.BoomsNTextBox.Text == "" || int.Parse(this.BoomsNTextBox.Text) < 1)
                {
                    MessageBox.Show("worng Booms");
                }
                else
                if (this.CityTextBox.Text == "")
                {
                    MessageBox.Show("No text in city");
                }
                else
                if (this.AddressTextBox.Text == "")
                {
                    MessageBox.Show("No text in street");
                }
                else
                if (this.NameTextBox.Text == "")
                {
                    MessageBox.Show("No text in Name");
                }
                else
                {
                    var      id = 0;
                    Geocoder g  = new Geocoder();
                    var      v  = g.Geocode(AddressTextBox.Text, CityTextBox.Text);
                    if (v.Latitude == 0 && v.Longitude == 0)
                    {
                        MessageBox.Show("Sorry, but the address you gave does not exsist");
                    }
                    else
                    {
                        FactoryBl.GetBL().AddReport(new BE.Report(0, dt, this.NameTextBox.Text, this.AddressTextBox.Text, this.CityTextBox.Text, int.Parse(this.BoomsNTextBox.Text), int.Parse(this.IntensityTextBox.Text), new BE.Coordinate()));
                        foreach (var r in FactoryBl.GetBL().GetAllReport())
                        {
                            if (r.City == this.CityTextBox.Text && r.NameReporter == this.NameTextBox.Text && r.Address == this.AddressTextBox.Text)
                            {
                                id = r.FallId;
                            }
                        }
                        MapG w = new MapG(id);
                        w.Show();
                        this.Close();
                    }
                }
            }
        }
Esempio n. 32
0
        public MainWindow()
        {
            InitializeComponent();

            routerDb = new RouterDb();


            //GetOsmData();
            //ContractRouterDb();
            //GenerateRouterDb();
            LoadFromGeneratedRouterDb();

            var router = new Router(routerDb);

            gc = new Geocoder(openCageDataApiKey);

            //read the text file with provided pathway
            string allAddInfo = File.ReadAllText(mapsFilePath);

            string[] mapsTextList = Regex.Split(allAddInfo, "\r\n");

            //get start location lat&long
            GeocoderResponse startLocResult = gc.Geocode(ProcessStartLocationFile(mapsTextList));
            float            startLocLat    = GetLat(startLocResult);
            float            startLocLong   = GetLong(startLocResult);

            //get end location lat&long
            GeocoderResponse endLocResult = gc.Geocode(ProcessEndLocationFile(mapsTextList));
            float            endLocLat    = GetLat(endLocResult);
            float            endLocLong   = GetLong(endLocResult);

            //Convert or write them from float to string then can just print in string form
            string startLocLatString   = startLocLat.ToString();
            string startLocLongString  = startLocLong.ToString();
            string fullStartCoordinate = ("GPS coordinate for departure: (" + startLocLatString + ", " + startLocLongString + ")");

            string endLocLatString   = endLocLat.ToString();
            string endLocLongString  = endLocLong.ToString();
            string fullEndCoordinate = ("GPS coordinate for arrival: (" + endLocLatString + ", " + endLocLongString + ")");


            var profile = Vehicle.Car.Shortest();
            var route   = router.Calculate(profile, startLocLat, startLocLong, endLocLat, endLocLong);

            var geoJson = route.ToGeoJson();



            //change the meters into km
            float  totalDistance     = route.TotalDistance;
            double totalDistanceInKm = Math.Round(totalDistance / 1000, 2);
            string distanceInKm      = "Estimated Route Distance: " + totalDistanceInKm.ToString() + " km";

            //change the seconds to hour and minute
            float totalTimeSec        = route.TotalTime;
            float totalTimeMin        = totalTimeSec / 60;
            int   roundedTotalTimeMin = (int)Math.Round(totalTimeMin, 0);

            int   totalTimeHour       = roundedTotalTimeMin / 60;
            float totalTimeRem        = totalTimeMin % 60;
            float roundedTotalTimeRem = (int)Math.Round(totalTimeRem, 0);



            //Special Condition for travel duration
            string etdString    = "Estimated Travel Duration: ";
            string hourString   = "hour";
            string minuteString = "minute";

            if (totalTimeHour > 1)
            {
                hourString = "hours";
            }
            if (roundedTotalTimeRem > 1)
            {
                minuteString = "minutes";
            }

            //Combination of travel time
            string finalTextToPrint = etdString + totalTimeHour.ToString() + " " + hourString + " " + roundedTotalTimeRem.ToString() + " " + minuteString;

            string[] textToPrint = { fullStartCoordinate, fullEndCoordinate, distanceInKm, finalTextToPrint };



            //print or write all needed infos into an auto-generated file(giving specific pathway)
            File.WriteAllLines(@"C:\Users\Hmin\Desktop\Testing2\PrintData.txt", textToPrint);
            this.Close();
        }
Esempio n. 33
0
 /// <summary>
 /// An edit was made to the InputField.
 /// Unity will send the string from _inputField.
 /// Make geocoder query.
 /// </summary>
 /// <param name="searchString">Search string.</param>
 public void InputCoords(Vector2d coords)
 {
     _coordinate     = coords;
     _resource.Query = _coordinate;
     _geocoder.Geocode(_resource, HandleGeocoderResponse);
 }