Geocode() публичный Метод

public Geocode ( string address ) : IEnumerable
address string
Результат IEnumerable
Пример #1
0
        public void GetGeoCode(Classmate entity)
        {
            if (entity != null && entity.HomeAddress == string.Empty)
            {
                entity.Lat = string.Empty;
                entity.Lng = string.Empty;
                return;
            }
            System.Threading.Thread.Sleep(200); // wait a bit to avoid over limit error

            try
            {
                IGeocoder geocoder = new GoogleGeocoder();
                IEnumerable<Address> addresses = geocoder.Geocode(entity.HomeAddress);

                if (addresses.Count() > 0)
                {
                    entity.Lat = addresses.First().Coordinates.Latitude.ToString();
                    entity.Lng = addresses.First().Coordinates.Longitude.ToString();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #2
0
        public static void Main(string[] args)
        {
            var geoCoder = new GoogleGeocoder();
            var addresses = geoCoder.Geocode("53 rue de Rechèvres").ToList();

            foreach (var address in addresses)
            {
                Console.WriteLine("Formatted: " + address.FormattedAddress); //Formatted: 1600 Pennslyvania Avenue Northwest, Presiden'ts Park, Washington, DC 20500, USA
                Console.WriteLine("Coordinates: " + address.Coordinates.Latitude + ", " + address.Coordinates.Longitude); //Coordinates: 38.8978378, -77.0365123

                var reverse = geoCoder.ReverseGeocode(new Location(address.Coordinates.Latitude, address.Coordinates.Longitude));
                var toDisplay = string.Empty;

                foreach (var item in reverse)
                {
                    toDisplay = item.FormattedAddress;
                }

                Console.WriteLine(toDisplay);
            }

            Console.ReadKey();

            var date = DateTime.Now.ToString("yyyyMMdd");

            GenerateFichierPoi(addresses, date);

            Console.ReadKey();
        }
Пример #3
0
 static void set_location(string locationName)
 {
     var geocoder = new GoogleGeocoder() { };
     var loc = geocoder.Geocode(locationName).FirstOrDefault();
     Console.WriteLine("[!] Your given location: {0}", loc.FormattedAddress);
     Console.WriteLine("[!] lat/long/alt: {0} {1} {2}", loc.Coordinates.Latitude, loc.Coordinates.Longitude, 0);
     set_location_coords(loc.Coordinates.Latitude, loc.Coordinates.Longitude, 0);
 }
Пример #4
0
        public void GeoCode()
        {
            GoogleGeocoder geocoder = new GoogleGeocoder() ;
            var addresses = geocoder.Geocode("Mumbai, India");

            var country = addresses.Where(a => !a.IsPartialMatch).Select(a => a[GoogleAddressType.Country]).First();
            Console.WriteLine("Country: " + addresses.ToList()[0].Coordinates.Latitude + ", " + country.ShortName);
            //            IGeocoder geocoder = new GoogleGeocoder() { ApiKey = "AIzaSyDrgMqxT3DIKg4PQkuqNeqbjOCZwLQKxc0" };
            //       var addresses = geocoder.Geocode("").ToArray();
            ////Console.WriteLine("Formatted: " +addresses  .FormattedAddress); //Formatted: 1600 Pennslyvania Avenue Northwest, Presiden'ts Park, Washington, DC 20500, USA
            //        Console.WriteLine("Coordinates: " + addresses[0].Coordinates.Latitude + ", " + addresses[0].Coordinates.Longitude); //Coordinates: 38.8978378, -77.0365123
        }
        public GoogleAddress GetRealAddress(CreateRealEstateViewModel realEstate)
        {
            var geocoder = new GoogleGeocoder();

            if (realEstate.Address != null && realEstate.Address.Length > 5)
            {
                List<GoogleAddress> addresses = geocoder.Geocode(realEstate.Address).ToList();
                var fullAddress = addresses[0];
                return fullAddress;
            }

            return null;
        }
Пример #6
0
        public GoogleAddress GetGeocode(string address)
        {
            if (String.IsNullOrEmpty(address))
            {
                return(null);
            }

            var geoCoder = new Geocoding.Google.GoogleGeocoder();

            try
            {
                return(geoCoder.Geocode(address).FirstOrDefault());
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Пример #7
0
        public bool UpdateProfile(int id,[FromBody] User user)
        {
            if (user == null)
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
            var u = Adapter.UserRepository.GetByID(id);
            if (user.Email == u.Email && id == user.UserId)
            {
                try
                {
                    u.Bio = user.Bio;
                    u.Username = user.Username;
                    u.DateOfBirth = user.DateOfBirth;
                    u.Gender = user.Gender;
                    u.ModifiedDate = DateTime.Now;
                    Adapter.UserRepository.Update(u);

                    var l = Adapter.LocationRepository.GetByID(user.Location.LocationId);
                    l.Street = user.Location.Street;
                    l.Number = user.Location.Number;
                    l.Box = user.Location.Box;
                    l.Zipcode = user.Location.Zipcode;
                    l.City = user.Location.City;
                    l.Country = user.Location.Country;
                    IGeocoder geocoder = new GoogleGeocoder();
                    Address[] addresses = geocoder.Geocode(l.Street + " " + l.Number + ", " + l.Zipcode + " " + l.City + ", " + l.Country).ToArray();
                    if (addresses.Length != 0 && addresses[0].Coordinates != null)
                    {
                        l.Latitude = Convert.ToDecimal(addresses[0].Coordinates.Latitude);
                        l.Longitude = Convert.ToDecimal(addresses[0].Coordinates.Longitude);
                    }
                    else
                        return false;
                    Adapter.LocationRepository.Update(l);

                    Adapter.Save();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
            else
                return false;
        }
Пример #8
0
        private Geography GetLatLng(string address)
        {
            if (address == null)
            {
                return null;
            }

            System.Net.ServicePointManager.Expect100Continue = false;

            GoogleGeocoder geocoder = new GoogleGeocoder();
            IEnumerable<Address> addresses = geocoder.Geocode(address);

            Geography G1 = new Geography();
            if (addresses == null)
            {
                G1.latitude = 0.0m;
                G1.latitude = 0.0m;
                return G1;
            }

            try
            {
                G1.latitude = (decimal)addresses.First().Coordinates.Latitude;
                G1.longitude = (decimal)addresses.First().Coordinates.Longitude;
            }
            catch
            {
                G1.latitude = 0.0m;
                G1.latitude = 0.0m;
            }

            return G1;
        }
Пример #9
0
        private Property Geocode_Create(string address)
        {
            System.Net.ServicePointManager.Expect100Continue = false;

            GoogleGeocoder geocoder = new GoogleGeocoder();
            IEnumerable<GoogleAddress> addresses = geocoder.Geocode(address);

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

            var p = addresses.Where(a => !a.IsPartialMatch).Select
                    (a => new Property()
                    {
                        streetaddress = a[GoogleAddressType.StreetNumber].ShortName,
                        route = a[GoogleAddressType.Route].ShortName,
                        state = a[GoogleAddressType.AdministrativeAreaLevel1].LongName,
                        zip = a[GoogleAddressType.PostalCode].LongName,
                        city = a[GoogleAddressType.Locality].ShortName,
                        country = a[GoogleAddressType.Country].ShortName,
                        latitude = (decimal)addresses.First().Coordinates.Latitude,
                        longitude = (decimal)addresses.First().Coordinates.Longitude
                    }
                    ).First();

            p.formatted_address = p.streetaddress + " " + p.route + ", " + p.city + ", " + p.state + ", " + p.zip + ", " + p.country;

            return p;
        }
Пример #10
0
        //Geocode functions
        private SearchCompare Geocode(string address)
        {
            System.Net.ServicePointManager.Expect100Continue = false;

            GoogleGeocoder geocoder = new GoogleGeocoder();
            IEnumerable<GoogleAddress> addresses = geocoder.Geocode(address);

            if (addresses != null)
            {
                var results = MapProperties(addresses);
                return results;
            }
            else
            {
                return null;
            }
        }
    protected void Button4_Click(object sender, EventArgs e)
    {
        // Response.Write(marker_place);
        List<string> lst_zipscodes = new List<string>();
        IGeocoder geocoder = new GoogleGeocoder() { };
        DataSet ds = new DataSet("Sites_Collection");
        string connection_string = ConfigurationManager.ConnectionStrings["UA_NAVConnectionString"].ConnectionString;
        SqlConnection conn = new SqlConnection(connection_string);

        WeatherReference.WeatherSoapClient weather = new WeatherReference.WeatherSoapClient("WeatherSoap");

        // my source starting placeplace

        for (int i = 0; i < marker_place.Count; i++)
        {
            string source = marker_place[i];
            string[] addr_string = source.Split(',');
            string[] zipcode = null;
            if (addr_string.Count() == 4)
            {
                zipcode = addr_string[2].Trim().Split(' ');
                source = addr_string[1] + "," + zipcode[0];
                lst_zipscodes.Add(zipcode[1]);
            }
            else
            {
                continue;
            }
            IWebDriver driver = null;
            try
            {
                driver = new FirefoxDriver();

                driver.Navigate().GoToUrl("http://www.nwf.org/naturefind.aspx");
                driver.Manage().Window.Maximize();

                var place_name = driver.FindElement(By.Id("content_0_txtBasicSearch"));
                place_name.Clear();
                place_name.SendKeys(source);
                driver.FindElement(By.Id("content_0_btnSearchSites")).Click();
                //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

                IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(15.00));
                // IWait<IWebDriver> wait = null;
                wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

                DataTable dt = new DataTable("Places_" + i);

                DataColumn place_Coulumn = new DataColumn("Scenic_Place_Name", Type.GetType("System.String"));
                DataColumn lat_Coulumn = new DataColumn("Latitude", Type.GetType("System.String"));
                DataColumn lng_Coulumn = new DataColumn("Longitude", Type.GetType("System.String"));
                DataColumn address_of_place = new DataColumn("Address", Type.GetType("System.String"));
                DataColumn Zipscode = new DataColumn("Zipcode", Type.GetType("System.String"));
                DataColumn weather_desc = new DataColumn("Weather", Type.GetType("System.String"));
                DataColumn temperature = new DataColumn("Temperature", Type.GetType("System.String"));
                DataColumn traffic = new DataColumn("Traffic", Type.GetType("System.String"));
                DataColumn safety = new DataColumn("Safety", Type.GetType("System.String"));
                dt.Columns.Add(place_Coulumn);
                dt.Columns.Add(lat_Coulumn);
                dt.Columns.Add(lng_Coulumn);
                dt.Columns.Add(address_of_place);
                dt.Columns.Add(Zipscode);
                dt.Columns.Add(weather_desc);
                dt.Columns.Add(temperature);
                dt.Columns.Add(traffic);
                dt.Columns.Add(safety);

                DataRow dr;
                int count1 = 0;

                try
                {

                    wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[@id='content_0_grdSiteList']//tr[@class='rgRow']//u")));
                    wait.Until(ExpectedConditions.ElementExists(By.XPath("//div[@id='content_0_grdSiteList']//tr[@class='rgRow']//u")));
                    IList<IWebElement> lst_places = driver.FindElements(By.XPath(".//div[@id='content_0_grdSiteList']//tr[@class='rgRow']//u"));

                    if (lst_places == null)
                        continue;
                    int count = 0;
                    foreach (IWebElement place in lst_places)
                    {
                        //   if (count1!= -1)
                        //    {
                        try
                        {
                            dr = dt.NewRow();
                            Thread.Sleep(200);
                            dr["Scenic_Place_Name"] = place.Text;
                            IEnumerable<Address> addresses = geocoder.Geocode(place.Text + "," + zipcode[0]);
                            string place_addr = null;
                            Location ltng = null;

                            foreach (Address adr in addresses)
                            {
                                if (count == 0)
                                {
                                    place_addr = adr.FormattedAddress;
                                    ltng = adr.Coordinates;
                                    dr["Address"] = place_addr;
                                    break;
                                }
                            }

                            dr["Latitude"] = ltng.Latitude;
                            dr["Longitude"] = ltng.Longitude;

                            //tokenize place address

                            string[] array = place_addr.Split(',');
                            string[] waypoints = place_addr.Split(','); ///////*******************
                            string zip = array[array.Length - 2];
                            string[] arr = zip.Trim().Split(' ');
                            string webservicezip = null;
                            if (arr.Length == 1)
                            {
                                dr["Zipcode"] = zipcode[1];
                                webservicezip = zipcode[1];
                            }
                            else if (Regex.IsMatch(place_addr, @"\d"))
                            {
                                arr = zip.Trim().Split(' ');
                                dr["Zipcode"] = arr[1].Trim();
                                webservicezip = arr[1].Trim();
                            }

                            //weather update

                            WeatherReference.WeatherReturn weather_of_place = weather.GetCityWeatherByZIP(webservicezip);  //  arr[1].Trim()
                            dr["Weather"] = weather_of_place.Description;
                            dr["Temperature"] = weather_of_place.Temperature;

                            Random rnd = new Random();
                            dr["Traffic"] = rnd.Next(2, 5);
                            dr["Safety"] = rnd.Next(60, 100);
                            dt.Rows.Add(dr);
                            //break;
                        }

                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                            continue;
                        }
                    }

                }
                finally
                {

                    ds.Tables.Add(dt);
                }

            }

            finally
            {
                driver.Close();
                driver.Dispose();
            }
        }

        WriteDataToDATABASE(ds);
        string[] scenic_places = CreateListScenicPlaces();
        //    DrawScenicDirection();
        foreach (string s in scenic_places)
        {
            ClientScript.RegisterArrayDeclaration("scenic_places", "\"" + s + "\"");
        }

        ClientScript.RegisterStartupScript(Page.GetType(), "Scenic", "scenic_route();", true);
    }
        public IEnumerable<ImplementationDescription> Search(string addr = null, string zipCode = null)
        {
            if (!string.IsNullOrEmpty(addr))
            {
                var geocoder = new GoogleGeocoder();
                var geocodeResponse = geocoder.Geocode(addr).FirstOrDefault();

                if (geocodeResponse != null)
                {
                    var zipComponent = geocodeResponse.Components.First(x => x.Types.Contains(GoogleAddressType.PostalCode));

                    if (zipComponent != null)
                    {
                        var zip = zipComponent.LongName;

                        if (zip.Length > 5)
                            zip = zip.Substring(0, 5);

                        return this.ByZipCode(zip);
                    }
                }

                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, new GenericErrorResponse { Message = "Invalid Address" }));
            }
            else if (!string.IsNullOrEmpty(zipCode))
            {
                return this.ByZipCode(zipCode);
            }

            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, new GenericErrorResponse { Message = "Must pass either the addr or zipCode query parameter!" }));
        }
Пример #13
0
        public ActionResult RegisterPost(Register model, string redirectUrl)
        {
            ViewBag.redirectUrl = redirectUrl;
            if (ModelState.IsValid)
            {
                var userModel = model;
                RadarModels.Location loc = new RadarModels.Location();
                loc.Street = model.Location.Street;
                loc.Number = model.Location.Number;
                loc.Box = model.Location.Box;
                loc.Zipcode = model.Location.Zipcode;
                loc.City = model.Location.City;
                loc.Country = model.Location.Country;
                IGeocoder geocoder = new GoogleGeocoder();
                Address[] addresses = geocoder.Geocode(loc.Street + " " + loc.Number + ", " + loc.Zipcode + " " + loc.City + ", " + loc.Country).ToArray();
                if (addresses.Length != 0 && addresses[0].Coordinates != null)
                {
                    loc.Latitude = Convert.ToDecimal(addresses[0].Coordinates.Latitude);
                    loc.Longitude = Convert.ToDecimal(addresses[0].Coordinates.Longitude);
                    Adapter.LocationRepository.Insert(loc);
                    Adapter.Save();
                }
                else
                {
                    ModelState.AddModelError("", "Het adres kon niet worden gevonden.");
                    return View(model);
                }

                UserMembershipProvider mp = new UserMembershipProvider();

                MembershipCreateStatus status;

                UserMembershipUser mu = mp.CreateUserBetter(model.Username, model.Email, model.Gender?"m":"f", model.Password,model.DateOfBirth, model.Bio, loc.LocationId, out status) as UserMembershipUser;

                if (status == MembershipCreateStatus.DuplicateEmail)
                    ModelState.AddModelError("", "Emailadres heeft al een account.");
                else if(status == MembershipCreateStatus.InvalidPassword)
                    ModelState.AddModelError("", "Paswoord is niet sterk genoeg. Moet minimum 5 karakters zijn.");
                else if (status == MembershipCreateStatus.Success)
                {
                    SendMail(userModel);

                    if (!String.IsNullOrEmpty(redirectUrl))
                    {
                        byte[] b = Convert.FromBase64String(redirectUrl);
                        string url = System.Text.Encoding.UTF8.GetString(b);
                        return Redirect(url + "?&message=registered");
                    }
                    else
                        return Redirect("http://localhost:4911/Radar/app/#/?message=registered");
                }
            }
            else
            {
                ModelState.AddModelError("", "De ingevulde gegevens zijn niet correct.");
            }
            return View(model);
        }
Пример #14
0
        private Address GetGeoInfo(string address)
        {
            Address addressInfo = null;

            // If the geocode has not already be retrieved for this address
            if (!_geoCodes.ContainsKey(address))
            {
                IGeocoder geocoder = new GoogleGeocoder() { ApiKey = _googleApiKey };

                // Get addresses found matching address given
                IEnumerable<Address> addresses = geocoder.Geocode(address);

                // Set addressInfo to the first matching address
                addressInfo = addresses.FirstOrDefault();

                _geoCodes.Add(address, addressInfo);
            }
            else
            {
                _geoCodes.TryGetValue(address, out addressInfo);
            }

            return addressInfo;
        }
Пример #15
0
        public List<TweetInfo> GetSearchByKeyWordAndLocation(bool geoCode = false,  List<string> keywords = null)
        {
            keywords = keywords ?? _preferedkeywordList;
            GoogleGeocoder geocoder = new GoogleGeocoder() ;
            List<TweetInfo> infoList = new List<TweetInfo>();
            foreach (var keyword in keywords)
            {
                var words = keyword.Split(new[] { ',' });
                foreach (string t in words)
                {
                   // searchParameter.
                    var tweets = Search.SearchTweets(t);
                    foreach (var tweet in tweets)
                    {
                        double latitude = 0.0;
                        double longitude = 0.0;

                        var info = new TweetInfo
                                     {
                                         Msg = tweet.Text,
                                         MsgId = tweet.IdStr,
                                         Date = tweet.CreatedAt,
                                         User = new TwitterUser
                                                {
                                                    ScreenName = tweet.Creator.ScreenName,
                                                    ProfileImgUrl = tweet.Creator.ProfileImageUrl,
                                                    Location = tweet.Creator.Location
                                                }
                                     };
                        if (geoCode)
                        {
                            if (tweet.Coordinates != null)
                            {
                                latitude = tweet.Coordinates.Latitude;
                                longitude = tweet.Coordinates.Longitude;
                            }
                            else if (!String.IsNullOrEmpty(tweet.Creator.Location))
                            {
                                try
                                {
                                    var address = geocoder.Geocode(tweet.Creator.Location.Trim()).ToList();
                                    if (address.Count > 0)
                                    {
                                        latitude = address.ToList()[0].Coordinates.Latitude;
                                        longitude = address.ToList()[0].Coordinates.Longitude;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(tweet.Creator.Location);
                                }
                            }
                            info.Lat = latitude;
                            info.Long = longitude;

                        }
                        infoList.Add(info);
                    }
                }
            }
            return infoList;
        }