Beispiel #1
0
        public void TestLatitudeAndLongitude()
        {
            double accuracy = 0.25;
            var    result   = _geocoder.Geocode(_eastLansingCityHall);

            Assert.IsTrue(Math.Abs(42.7369792 - result.Geocode.Latitude) < accuracy);
            Assert.IsTrue(Math.Abs(-84.4838654 - result.Geocode.Longitude) < accuracy);
        }
        public ActionResult GeoCode()
        {
            IGeocoder geocoder = new GoogleGeocoder()
            {
                ApiKey = "AIzaSyB7Mcq6kcU87hlj3mi8AosJ1R20YETpvjk"
            };

            IEnumerable <House> housesToUpdate = db.Houses.Where(i => i.NeighborhoodID == NeighborhoodID && (!i.Latitude.HasValue || !i.Longitude.HasValue));

            foreach (House house in housesToUpdate)
            {
                Address address = geocoder.Geocode(string.Format("{0}, {1}, NY {2}", house.Address, house.City, house.ZipCode)).FirstOrDefault();

                if (address == null)
                {
                    continue;
                }

                house.Latitude  = Convert.ToDecimal(address.Coordinates.Latitude);
                house.Longitude = Convert.ToDecimal(address.Coordinates.Longitude);
            }

            db.SaveChanges();

            return(RedirectToAction("Index"));
        }
        public string GetLatLonFromAddress(string address)
        {
            Func <string> getCordsFromAddress = delegate()
            {
                IGeocoder googleGeoCoder = new GoogleGeocoder()
                {
                    ApiKey = Config.MappingConfig.GoogleMapsApiKey
                };
                IGeocoder bingGeoCoder = new BingMapsGeocoder(Config.MappingConfig.BingMapsApiKey);
                string    coordinates  = null;

                try
                {
                    var addresses = googleGeoCoder.Geocode(address);

                    if (addresses != null && addresses.Any())
                    {
                        var firstAddress = addresses.First();

                        coordinates = string.Format("{0},{1}", firstAddress.Coordinates.Latitude, firstAddress.Coordinates.Longitude);
                    }
                }
                catch
                { }

                if (string.IsNullOrWhiteSpace(coordinates))
                {
                    try
                    {
                        var coords = GetLatLonFromAddressLocationIQ(address);

                        if (coords != null)
                        {
                            coordinates = string.Format("{0},{1}", coords.Latitude, coords.Longitude);
                        }
                    }
                    catch
                    { }
                }

                if (string.IsNullOrWhiteSpace(coordinates))
                {
                    try
                    {
                        var addresses = bingGeoCoder.Geocode(address);

                        if (addresses != null && addresses.Count() > 0)
                        {
                            coordinates = string.Format("{0},{1}", addresses.First().Coordinates.Latitude, addresses.First().Coordinates.Longitude);
                        }
                    }
                    catch
                    { }
                }

                return(coordinates);
            };

            return(_cacheProvider.Retrieve <string>(string.Format(ForwardCacheKey, address.GetHashCode()), getCordsFromAddress, CacheLength));
        }
Beispiel #4
0
        private List <GeocoderResult> GetAddress(string address, string zone = "ar", Bounds boundsBias = null)
        {
            try
            {
                IGeocoder geocoder = new GoogleGeocoder
                {
                    //ApiKey = "AIzaSyA4guD0ambG70ooNV5D_Cg8zR42GK1rP_I",
                    Language   = "es",
                    RegionBias = zone,
                    BoundsBias = boundsBias,
                };

                IEnumerable <Address> result = geocoder.Geocode(address).Where(x => IsInBound(boundsBias, new Location(x.Coordinates.Latitude, x.Coordinates.Longitude)));

                return(result.Select(x => new GeocoderResult
                {
                    Nombre = x.FormattedAddress,
                    X = x.Coordinates.Latitude,
                    Y = x.Coordinates.Longitude,
                }).ToList());
            }
            catch (Exception)
            {
                return(new List <GeocoderResult>());
            }
        }
Beispiel #5
0
        public static Activity ForcastSearch(Activity activity, string searchTerm)
        {
            var apiKey    = "174629f16ab0dcaf1e63d4853cb66830";
            var geocoder  = new GoogleGeocoder();
            var addresses = geocoder.Geocode(searchTerm);

            double lat   = addresses.First().Coordinates.Latitude;
            double longi = addresses.First().Coordinates.Longitude;

            var apiUrl = $"https://api.darksky.net/forecast/{apiKey}/{lat},{longi}";

            var client = new HttpClient
            {
                BaseAddress = new Uri("https://api.darksky.net/forecast/")
            };

            var    resp = client.GetAsync(apiUrl).Result;
            string json = resp.Content.ReadAsStringAsync().Result;

            var forecast = JsonConvert.DeserializeObject <ForecastAPI.Forecast>(json);

            var sb    = new StringBuilder();
            var reply = activity.CreateReply(sb.ToString());

            reply.Type = "message";
            return(reply);
        }
Beispiel #6
0
 public static void SetLocation(ProductView product, SelectedHotelsEntities db, Hotel hotel, log4net.ILog log)
 {
     if (!String.IsNullOrEmpty(product.Lat) && !String.IsNullOrEmpty(product.Long))
     {
         var location = DbGeography.FromText(String.Format("POINT({0} {1})", product.Long, product.Lat));
         if (hotel.Location != location)
         {
             hotel.Location = location;
         }
     }
     else
     {
         try
         {
             IGeocoder geocoder = new GoogleGeocoder()
             {
                 ApiKey = ""
             };
             var addresses =
                 geocoder.Geocode(String.Format("{0}, {1}, {2}", product.Country, product.City, product.Address));
             if (addresses.Any())
             {
                 var address = addresses.First();
                 hotel.Location =
                     DbGeography.FromText(String.Format("POINT({0} {1})", address.Coordinates.Longitude, address.Coordinates.Latitude));
             }
         }
         catch (Exception ex)
         {
             log.Error("Error error logging", ex);
         }
     }
 }
Beispiel #7
0
        // Geocodes an address using the Bing Maps engine
        public static Location SearchGoogle(string add)
        {
            try
            {
                // Calls the webservice
                GoogleGeocoder geocoder = new GoogleGeocoder()
                {
                    ApiKey = ConfigurationManager.AppSettings["GoogleApiKey"]
                };
                IEnumerable <Address> addresses = geocoder.Geocode(add);

                // Selects the firt result
                GoogleAddress g = (GoogleAddress)addresses.FirstOrDefault();

                Location r = new Location();

                r.Lat     = addresses.FirstOrDefault().Coordinates.Latitude;
                r.Lon     = addresses.FirstOrDefault().Coordinates.Longitude;
                r.Quality = g.LocationType.ToString();
                r.Address = addresses.FirstOrDefault().FormattedAddress;

                return(r);
            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message);
            }
        }
Beispiel #8
0
        ////itoa = for ascii to decimal. ONLY IN C.
        private void Decodemessage_GPRMC()
        { //http://aprs.gids.nl/nmea/
            // format:  $GPRMC,200715.000,A,5012.6991,N,00711.9549,E,0.00,187.10,270115,,,A*65
            DateTime dateNow = DateTime.Now;

            if (Rx_BufferBufferd[18] == 'A')   // A meens data valid
            {
                int index = 6, tmp, hour, minutes, seconds, dotmilseconds;

                string[]           str_gga = new string(Rx_BufferBufferd).Split(',');
                GPSReceive.MSG_GGA gga     = new GPSReceive.MSG_GGA();
                gga.Receive_Time = str_gga[1];

                tmp      = ASCII_to_byte(Rx_BufferBufferd[++index]);
                hour     = (tmp * 10);
                hour    += ASCII_to_byte(Rx_BufferBufferd[++index]);
                tmp      = ASCII_to_byte(Rx_BufferBufferd[++index]);
                minutes  = (tmp * 10);
                minutes += ASCII_to_byte(Rx_BufferBufferd[++index]);
                tmp      = ASCII_to_byte(Rx_BufferBufferd[++index]);
                seconds  = tmp * 10;
                seconds += ASCII_to_byte(Rx_BufferBufferd[++index]);
                index++;
                // dotmilisec is not implemented in the gps receiver
                tmp            = ASCII_to_byte(Rx_BufferBufferd[++index]);
                dotmilseconds  = tmp * 100;
                tmp            = ASCII_to_byte(Rx_BufferBufferd[++index]);
                dotmilseconds += tmp * 10;
                dotmilseconds += ASCII_to_byte(Rx_BufferBufferd[++index]);
                DateTime date              = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, hour, minutes, seconds);
                SetControlPropertyThreadSafe(lbl_gpstime, "Text", "GPS time: " + date.TimeOfDay.ToString());

                //gga.Position_Fix = int.Parse(str_gga[2]);
                gga.Latitude     = str_gga[3];
                gga.NS_Indicator = Convert.ToChar(str_gga[4].Substring(0, 1));
                gga.Longitude    = str_gga[5];
                gga.EW_Indicator = Convert.ToChar(str_gga[6].Substring(0, 1));


                // gga.Satellites_Used = str_gga[7];
                // gga.HDOP = str_gga[8];
                // gga.Altitude = str_gga[9];
                // gga.Altitude_Units = Convert.ToChar(str_gga[10].Substring(0, 1));
                // gga.DGPS_Station_ID = str_gga[11];

                IGeocoder             geocoder  = new GoogleGeocoder();
                IEnumerable <Address> addresses = geocoder.Geocode("1600 pennsylvania ave washington dc");
                //Address[] addressess = geocoder.Geocode("123 Main St");
                //  Console.WriteLine("Formatted: " + addresses.First().FormattedAddress); //Formatted: 1600 Pennslyvania Avenue Northwest, Presiden'ts Park, Washington, DC 20500, USA
                // Console.WriteLine("Coordinates: " + addresses.First().Coordinates.Latitude + ", " + addresses.First().Coordinates.Longitude); //Coordinates: 38.8978378, -77.0365123

                //geocoder.ReverseGeocode(gga.Latitude,gga.Longitude);

                Updatewebbrouwser();
            }
        }
Beispiel #9
0
        public static double GetLongFromCountryName(string country)
        {
            IGeocoder geocoder = new GoogleGeocoder()
            {
                ApiKey = "AIzaSyCPWzQ0h1vedStiQWFQ5Ez1Jf2f1rj209Q"
            };
            var addresses = geocoder.Geocode(country);

            return(addresses.First().Coordinates.Longitude);
        }
Beispiel #10
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);
            }
        }
Beispiel #11
0
        public Coordinates Geocode(string ApiKey, string Address)
        {
            GoogleGeocoder coder = new GoogleGeocoder(ApiKey);

            IEnumerable <GoogleAddress> address = coder.Geocode(Address);

            //if (address != null)
            //    return new Coordinates() { Latitude = address.Coordinates.Latitude, Longitude = address.Coordinates.Longitude };
            //else
            //    return null;

            return(null);
        }
        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);
        }
        public static Tuple <double, double> getLatLong(string location)
        {
            GoogleGeocoder geocoder  = new GoogleGeocoder();
            var            addresses = geocoder.Geocode(location);

            foreach (var coord in addresses)
            {
                Thread.Sleep(500);
                Tuple <double, double> result = new Tuple <double, double>(coord.Coordinates.Latitude, coord.Coordinates.Longitude);
                return(result);
            }

            return(null);
        }
Beispiel #14
0
        public ActionResult Create([Bind(Include = "ID,name,description,address1,address2,city,state,zip,lat,lng")] Entity entity)
        {
            if (ModelState.IsValid)
            {
                //Instantiating userUtil to get the ID of currently logged in user
                Utils.Utility userUtil = new Utils.Utility();

                //Using geocoder from Google to get latitude and longitude from entity address
                IGeocoder geocoder = new GoogleGeocoder()
                {
                    ApiKey = "AIzaSyDOH51wduQKexTyFXGy0tdDqfXw47XIrjA"
                };
                IEnumerable <Address> addresses = geocoder.Geocode(entity.address1 + " " + entity.address2 + " " + entity.city + " " + entity.state + " " + entity.zip);
                entity.lat = Convert.ToString(addresses.First().Coordinates.Latitude);
                entity.lng = Convert.ToString(addresses.First().Coordinates.Longitude);

                //user is the currently logged in user; attach the entity we're making to the user
                var user = db.users.Find(userUtil.UserID(User));
                db.entities.Add(entity);
                db.SaveChanges();
                user.entity = entity;
                db.SaveChanges();

                //Creating a default project each time that an entity is created
                Project project = new Project();
                project.name        = "General Fund";
                project.description = "General Pool of Funds - unassigned to a project";
                project.entity      = entity;
                db.projects.Add(project);
                db.SaveChanges();
                //Add the project to this entity's list of projects
                entity.projects.Add(project);
                db.SaveChanges();

                //Once the entity is created, redirect to the dashboard IF there are categories in the system
                //If there aren't, that means no base categories exist and the user will be redirected to make one
                List <Category> categoriesList = db.categories.ToList();
                if (categoriesList.Count > 0)
                {
                    return(RedirectToAction("Index", "Dashboard"));
                }
                else
                {
                    return(RedirectToAction("CreateBase", "Categories"));
                }
            }

            return(View(entity));
        }
        public LocationInfo Geocode(string input)
        {
            IGeocoder             geocoder  = new GoogleGeocoder();
            IEnumerable <Address> addresses = geocoder.Geocode(input);

            GoogleAddress address = (GoogleAddress)addresses.First();

            return(new LocationInfo
            {
                Latitude = address.Coordinates.Latitude.ToString(),
                Longitude = address.Coordinates.Longitude.ToString(),
                City = address[GoogleAddressType.Locality].LongName,
                State = address[GoogleAddressType.AdministrativeAreaLevel1].ShortName
            });
        }
        public JsonResult GetAddressLocation(string searchAddress)
        {
            IGeocoder geocoder = new GoogleGeocoder()
            {
            };
            IEnumerable <Address> addresses = geocoder.Geocode(searchAddress);

            var enumerable = addresses as IList <Address> ?? addresses.ToList();

            if (enumerable.Any())
            {
                return(this.Json(new { success = true, data = enumerable.First().Coordinates }));
            }
            else
            {
                return(this.Json(new { success = false }));
            }
        }
Beispiel #17
0
        static void Main(string[] args)
        {
            GoogleGeocoder googleGeocoder = new GoogleGeocoder();
            YandexGeocoder yandexGeocoder = new YandexGeocoder();

            RequestData request = new RequestData()
            {
                Address = "inönü mahallesi atatürk caddesi birlik apt. no:55 daire 7 istanbul ataşehir türkiye"
            };

            ResponseData googleResult = googleGeocoder.Geocode(request);

            List <GoogleResult> googleGeocodeResultList = googleGeocoder.GeocodeAndParse(request);

            ResponseData yandexResult = yandexGeocoder.Geocode(request);

            List <YandexResult> yandexGeocodeResultList = yandexGeocoder.GeocodeAndParse(request);
        }
Beispiel #18
0
        // Geocodes an address using the Bing Maps engine
        public static Location Geocode_Google(string ADDRESS)
        {
            try
            {
                // Calls the webservice
                GoogleGeocoder GEOCODER = new GoogleGeocoder()
                {
                    ApiKey = ConfigurationManager.AppSettings["GoogleApiKey"]
                };
                IEnumerable <Address> addresses = GEOCODER.Geocode(ADDRESS);

                Location R = new Location();

                // Checks if the process returned a valid result
                if (addresses.Count() > 0)
                {
                    // Selects the firt result
                    GoogleAddress G = (GoogleAddress)addresses.FirstOrDefault();

                    R.Lat     = G.Coordinates.Latitude;
                    R.Lon     = G.Coordinates.Longitude;
                    R.Address = Find_Value(G, "ROUTE") + " " +
                                Find_Value(G, "STREETNUMBER");
                    R.City       = Find_Value(G, "ADMINISTRATIVEAREALEVEL2");
                    R.State      = Find_Value(G, "ADMINISTRATIVEAREALEVEL1");
                    R.PostalCode = Find_Value(G, "POSTALCODE");
                    R.Quality    = G.LocationType.ToString();
                    R.Complete   = G.FormattedAddress;
                }
                else
                {
                    R.Lat     = 0;
                    R.Lon     = 0;
                    R.Quality = "Bad";
                }

                return(R);
            }
            catch (Exception ERROR)
            {
                throw new Exception(ERROR.Message);
            }
        }
Beispiel #19
0
        public Coordinates Geocode(string ApiKey, string Address)
        {
            GoogleGeocoder coder = new GoogleGeocoder(ApiKey);

            GoogleAddress address = coder.Geocode(Address).FirstOrDefault();

            if (address != null)
            {
                return new Coordinates()
                       {
                           Latitude = address.Coordinates.Latitude, Longitude = address.Coordinates.Longitude
                       }
            }
            ;
            else
            {
                return(null);
            }
        }
        static void Main(string[] args)
        {
            string search      = "victoria";
            string baseAddress = "https://www.aif.adfa.edu.au/";

            HtmlAgilityPack.HtmlWeb      web = new HtmlAgilityPack.HtmlWeb();
            HtmlAgilityPack.HtmlDocument doc = web.Load($"{baseAddress}search?type=search&name=&regNum=&place={search}&includeNOK=n&townOnly=n&start=0&pageSize=1000&totFound=1000");

            var listings = doc.DocumentNode.SelectNodes("//tr");

            System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Aidan\Desktop\aifScrap.json");
            file.AutoFlush = true;

            file.WriteLine("[");

            foreach (var item in listings.Where(l => l != listings.Last()))
            {
                string num       = item.ChildNodes[1].InnerHtml;
                string name      = item.ChildNodes[2].InnerText;
                string address   = item.ChildNodes[3].InnerHtml;
                string battalion = item.ChildNodes[4].InnerText;


                IGeocoder geocoder = new GoogleGeocoder()
                {
                    ApiKey = "AIzaSyBPiIqz1gTyYxOQqRIm47zjLtpP3TknBRo"
                };

                try
                {
                    Console.WriteLine(num);
                    IEnumerable <Address> addresses = geocoder.Geocode(address);
                    string entry = "{\"name\": \"" + name + "\"," +
                                   "\"coords\": \"[" + addresses.First().Coordinates.Latitude + ", " + addresses.First().Coordinates.Longitude + "]\"},";
                    file.WriteLine(entry);
                }
                catch (Exception e)
                {
                    Console.WriteLine("[ERROR] - " + e.Message);
                }
            }
            file.WriteLine("]");
        }
        //GET DIRETIONS TO RESTAURANT
        public ActionResult GetDirections(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Restaurant restaurant = db.Restaurants.Find(id);

            if (restaurant == null)
            {
                return(HttpNotFound());
            }

            //PassRestaurantName to view
            var restaurantName = restaurant.RestaurantName.ToString();

            ViewBag.RestaurantName = restaurantName;

            //Getting the coordinates of the Restaurant
            IGeocoder geoCode;

            geoCode = new GoogleGeocoder();

            //Combine location into one string
            string address = string.Format("{0}, {1}, {2}, Ireland", restaurant.RestaurantAddress, restaurant.RestaurantTown, restaurant.County);

            var coordinates = geoCode.Geocode(address).ToList();

            //Check if coordinates are valid
            if (coordinates.Count > 0)
            {
                var longlat = coordinates.First();

                //Pass variables to View
                ViewBag.Address = address;
                ViewBag.Lat     = Convert.ToDouble(longlat.Coordinates.Latitude);
                ViewBag.Long    = Convert.ToDouble(longlat.Coordinates.Longitude);

                ViewBag.mapAvailable = true;
            }

            return(View());
        }
Beispiel #22
0
        public IHttpActionResult PostListing(Listing listing)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var username = User.Identity.Name;

            var currentUser = db.Users.FirstOrDefault(u => u.UserName == username);

            // this is where we'll add lat/long
            IGeocoder geocoder  = new GoogleGeocoder();
            var       addresses = geocoder.Geocode($"{listing.Address}, {listing.City} {listing.State} {listing.Zip}");

            try
            {
                listing.UserId    = currentUser.Id;
                listing.Latitude  = addresses.First().Coordinates.Latitude;
                listing.Longitude = addresses.First().Coordinates.Longitude;
            }
            catch (Exception)
            {
            }

            db.Listings.Add(listing);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = listing.ListingId }, new
            {
                listing.ListingId,
                listing.UserId,
                listing.Latitude,
                listing.Longitude,
                listing.Address,
                listing.City,
                listing.Description,
                listing.Price,
                listing.State,
                listing.Zip
            }));
        }
        public HttpResponseMessage Insert(Company comp)
        {
            var l = new RadarModels.Location();

            l.Street  = comp.Location.Street;
            l.Number  = comp.Location.Number;
            l.Box     = comp.Location.Box;
            l.Zipcode = comp.Location.Zipcode;
            l.City    = comp.Location.City;
            l.Country = comp.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);

                Adapter.LocationRepository.Insert(l);
                Adapter.Save();
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new Exception("Address not found")));
            }

            comp.Location    = l;
            comp.CreatedDate = DateTime.Now;
            Adapter.CompanyRepository.Insert(comp);
            Adapter.Save();

            Employee emp = new Employee();

            emp.CompanyId   = comp.CompanyId;
            emp.UserId      = comp.UserId;
            emp.CreatedDate = DateTime.Now;
            emp.RoleId      = Adapter.RoleRepository.GetByID(4).RoleId;
            Adapter.EmployeeRepository.Insert(emp);
            Adapter.Save();

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        public static GeocodedLocation GeoCodeAddress(string target)
        {
            var geocoder = new GoogleGeocoder {
                ApiKey = ApiKey
            };
            var geocoded = geocoder.Geocode(target).ToList();

            if (!geocoded.Any())
            {
                return(null);
            }

            var latitude  = geocoded.FirstOrDefault().Coordinates.Latitude;
            var longitude = geocoded.FirstOrDefault().Coordinates.Longitude;
            var rv        = new GeocodedLocation {
                Latitude = latitude, Longitude = longitude
            };

            return(rv);
        }
        public ActionResult Create(Garage garage, string StateId, string CityId)
        {
            ModelState.Remove("Country");
            ModelState.Remove("CreatedDt");
            ModelState.Remove("CreatedBy");
            ModelState.Remove("IsActive");
            IGeocoder geocoder = new GoogleGeocoder()
            {
                ApiKey = "AIzaSyA3CNMI-_JAV9-dWIctroZQTuUwjZygT3A"
            };
            IEnumerable <Address> addresses = geocoder.Geocode(garage.Garage_Address);

            garage.Latitute  = addresses.First().Coordinates.Latitude;
            garage.Longitude = addresses.First().Coordinates.Longitude;
            var             response = Request["g-recaptcha-response"];
            CaptchaResponse cap      = new CaptchaResponse();

            if (cap.ValidateCaptcha(response))
            {
                if (ModelState.IsValid)
                {
                    garage.City      = Convert.ToInt32(CityId);
                    garage.State     = Convert.ToInt32(StateId);
                    garage.Country   = "US";
                    garage.CreatedBy = "WebsiteUser";
                    garage.CreatedDt = DateTime.Now;
                    garage.IsActive  = false;
                    db.Garages.Add(garage);
                    db.SaveChanges();
                    //Send Mail
                    return(RedirectToAction("Thankyou"));
                }
            }
            else
            {
                ViewBag.CaptchaError = "<p class='alert alert-danger'>Invalid Captcha</p>";
            }
            ViewBag.StateId = new SelectList(db.States, "Id", "StateName", garage.State);
            ViewBag.CityId  = new SelectList(db.Cities.Where(b => b.StateID == garage.State), "Id", "CityName", garage.City);
            return(View(garage));
        }
Beispiel #26
0
        public ActionResult Edit([Bind(Include = "ID,name,description,address1,address2,city,state,zip,lat,lng")] Entity entity)
        {
            Utils.Utility userUtil = new Utils.Utility();

            IGeocoder geocoder = new GoogleGeocoder()
            {
                ApiKey = "AIzaSyDOH51wduQKexTyFXGy0tdDqfXw47XIrjA"
            };
            IEnumerable <Address> addresses = geocoder.Geocode(entity.address1 + " " + entity.address2 + " " + entity.city + " " + entity.state + " " + entity.zip);

            if (ModelState.IsValid)
            {
                entity.lat = Convert.ToString(addresses.First().Coordinates.Latitude);
                entity.lng = Convert.ToString(addresses.First().Coordinates.Longitude);

                db.Entry(entity).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index", "Dashboard"));
            }
            return(View(entity));
        }
Beispiel #27
0
        /// <summary>
        /// Gibt den Längen- und Breitengrad der angegebene Adresse zurück - wenn Google die findet.
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public static GeoCoordinate GetAddressCoordinates(string company, string address)
        {
            GeoCoordinate result = null;
            //var key = "i3rES5dwvGCBmvrXAyMtHRbKHpwhVgwT";
            //var geocoder = new MapQuestGeocoder(key);

            var geocoder = new GoogleGeocoder();

            try
            {
                var addresses = geocoder.Geocode(address);
                if (addresses.First() != null)
                {
                    result = new GeoCoordinate(addresses.First().Coordinates.Latitude, addresses.First().Coordinates.Longitude);
                }
                return(result);
            }
            catch (Exception ex)
            {
                var msg = string.Format("Fehler: {0}\nDer Webservice kann die Adresse '{1}' nicht ermitteln.\nDie Adresse gehört zu Firma '{2}'", ex.Message, address, company);
                throw new ArgumentException(msg, nameof(address));
            }
        }
 public HttpResponseMessage Update(int id, [FromBody] Company comp)
 {
     if (ModelState.IsValid && id == comp.CompanyId)
     {
         var com = Adapter.CompanyRepository.GetByID(id);
         Adapter.CompanyRepository.UpdateValues(comp, com);
         IGeocoder geocoder  = new GoogleGeocoder();
         Address[] addresses = geocoder.Geocode(com.Location.Street + " " + com.Location.Number + ", " + com.Location.Zipcode + " " + com.Location.City + ", " + com.Location.Country).ToArray();
         if (addresses.Length != 0 && addresses[0].Coordinates != null)
         {
             com.Location.Latitude  = Convert.ToDecimal(addresses[0].Coordinates.Latitude);
             com.Location.Longitude = Convert.ToDecimal(addresses[0].Coordinates.Longitude);
         }
         else
         {
             return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new Exception("Address not found")));
         }
         com.ModifiedDate = DateTime.Now;
         Adapter.CompanyRepository.Update(com);
         Adapter.Save();
         return(Request.CreateResponse(HttpStatusCode.OK));
     }
     throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
 }
 public void CanParseAddressTypes(string address, GoogleAddressType type)
 {
     GoogleAddress[] addresses = geocoder.Geocode(address).ToArray();
     Assert.Equal(type, addresses[0].Type);
 }
Beispiel #30
0
    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);
    }