Beispiel #1
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 #2
0
        public async void ConvertToLatLongAsync(string address)
        {
            IGeocoder geocoder = new GoogleGeocoder()
            {
                ApiKey = "AIzaSyAtdAqKhJlXMN2ON9tmKuZQwndEI8dDWe8"
            };

            IEnumerable <Address> addresses = await geocoder.GeocodeAsync(address);

            MySqlConnection conn = DB.Connection();

            conn.Open();

            MySqlCommand cmd = conn.CreateCommand() as MySqlCommand;

            cmd.CommandText = @"UPDATE sightings SET lat = @Latitude, lng = @Longitude ORDER BY id DESC LIMIT 1";

            cmd.Parameters.AddWithValue("@Latitude", addresses.First().Coordinates.Latitude);
            cmd.Parameters.AddWithValue("@Longitude", addresses.First().Coordinates.Longitude);

            cmd.ExecuteNonQuery();

            conn.Close();
            if (conn != null)
            {
                conn.Dispose();
            }
        }
Beispiel #3
0
 static GeocodingManager()
 {
     geocoder = new GoogleGeocoder()
     {
         ApiKey = "AIzaSyCmsW-KsXCLqOZifa0Hwz7jFH3IqfG5CtI"
     };
 }
Beispiel #4
0
        public GoogleAddress GeocodeAddress(IAddress address)
        {
            var key = Engine.Settings.Integrations.GoogleMapsApiKey;

            if (!key.IsSet() || !Engine.Settings.Integrations.EnableGoogleGeocoding)
            {
                return(null);
            }

            IGeocoder geocoder = new GoogleGeocoder()
            {
                ApiKey = key
            };
            IEnumerable <Address> addresses = geocoder.GeocodeAsync(
                address.Number.IsSet() ? string.Format("{0} {1}", address.Number, address.Address1) : address.Address1,
                address.City,
                address.County,
                address.Postcode,
                address.Country
                ).Result;

            if (addresses.Count() == 0)
            {
                addresses = geocoder.GeocodeAsync(address.Postcode).Result;
                if (addresses.Count() == 0)
                {
                    return(null);
                }
            }

            return((GoogleAddress)addresses.First());
        }
Beispiel #5
0
        public async Task ReverseGeocode()
        {
            GoogleGeocoder geocoder  = new GoogleGeocoder();
            var            addresses = await geocoder.ReverseGeocodeAsync(Latitude, Longitude);

            GoogleAddress addr = addresses.Where(a => !a.IsPartialMatch).FirstOrDefault();

            if (addr != null)
            {
                if (addr[GoogleAddressType.Country] != null)
                {
                    Country = addr[GoogleAddressType.Country].LongName;
                }
                if (addr[GoogleAddressType.Locality] != null)
                {
                    Locality = addr[GoogleAddressType.Locality].LongName;
                }
                if (addr[GoogleAddressType.AdministrativeAreaLevel1] != null)
                {
                    AdminLevel1 = addr[GoogleAddressType.AdministrativeAreaLevel1].LongName;
                }
                if (addr[GoogleAddressType.AdministrativeAreaLevel2] != null)
                {
                    AdminLevel2 = addr[GoogleAddressType.AdministrativeAreaLevel2].LongName;
                }
                if (addr[GoogleAddressType.AdministrativeAreaLevel3] != null)
                {
                    AdminLevel3 = addr[GoogleAddressType.AdministrativeAreaLevel3].LongName;
                }
            }
        }
Beispiel #6
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 #7
0
        public void TestCityFromZipSpecialChars()
        {
            var geocoder = new GoogleGeocoder(ApiKey, Region);
            var cities3  = geocoder.CityFromZip(5627);

            Assert.AreEqual("Besenbüren", cities3[0]);
        }
        public async Task <IActionResult> Create([Bind("Id,Name,StreetAddress,AddressCity,AddressState,AddressZip,StoreHours,PhoneNumber,Logo,CompanyVision,Email,Latitude,Longitude")] StoreInfo storeInfo)
        {
            if (ModelState.IsValid)
            {
                _context.Add(storeInfo);
                await _context.SaveChangesAsync();

                var addressString = string.Format("https://maps.googleapis.com/maps/api/geocode/json?address=" + storeInfo.StreetAddress + " " + storeInfo.AddressCity + " " + storeInfo.AddressState + " " + storeInfo.AddressZip + "&key=" + APIKEYS.GoogleAPI);


                IGeocoder geocoder = new GoogleGeocoder()
                {
                    ApiKey = APIKEYS.GoogleAPI
                };
                IEnumerable <Address> addresses = await geocoder.GeocodeAsync(addressString);

                storeInfo.Latitude  = addresses.First().Coordinates.Latitude;
                storeInfo.Longitude = addresses.First().Coordinates.Longitude;
                _context.Update(storeInfo);
                await _context.SaveChangesAsync();



                return(RedirectToAction(nameof(Index)));
            }
            return(View(storeInfo));
        }
        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"));
        }
Beispiel #10
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 #11
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 #12
0
        public static async Task <Geoposition> GetCoordinatesByAddressAsync(Geoposition geoposition)
        {
            try
            {
                IGeocoder geocoder = new GoogleGeocoder()
                {
                    ApiKey = "AIzaSyCDDmQbMj74oDWZoLco5W7t4nMKP8 - 77Qg"
                };

                var literalAddress = new StringBuilder();
                literalAddress.Append(geoposition.Country)
                .Append(' ')
                .Append(geoposition.City)
                .Append(' ')
                .Append(geoposition.Region)
                .Append(' ')
                .Append(geoposition.Address);

                IEnumerable <Address> addresses = await geocoder.GeocodeAsync(literalAddress.ToString());

                var firstAddress = addresses.First();

                geoposition.Latitude  = firstAddress.Coordinates.Latitude.ToString();
                geoposition.Longitude = firstAddress.Coordinates.Longitude.ToString();

                return(geoposition);
            }catch (Exception ex)
            {
                return(geoposition);
            }
        }
        //private void btnGeocode_Click(object sender, RoutedEventArgs e)
        //{
        //    SaveScreenToDealer();
        //    YahooGeoCoder.GeocodeDealer(_selectedDealer);
        //    txtLatitude.Text = _selectedDealer.Latitude.ToString();
        //    txtLongitude.Text = _selectedDealer.Longitude.ToString();
        //}

        // center markers on load

        //void MainMap_MouseEnter(object sender, MouseEventArgs e)
        //{
        //    MainMap.Focus();
        //}

        //void MainMap_Loaded(object sender, RoutedEventArgs e)
        //{
        //    MainMap.ZoomAndCenterMarkers(null);
        //}

        //void MainMap_OnMapTypeChanged(MapType type)
        //{
        //    sliderZoom.Minimum = MainMap.MinZoom;
        //    sliderZoom.Maximum = MainMap.MaxZoom;
        //}

        //void MainMap_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        //{
        //    System.Windows.Point p = e.GetPosition(MainMap);
        //    currentMarker.Position = MainMap.FromLocalToLatLng((int)p.X, (int)p.Y);
        //}

        //// move current marker with left holding
        //void MainMap_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        //{
        //    if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
        //    {
        //        System.Windows.Point p = e.GetPosition(MainMap);
        //        currentMarker.Position = MainMap.FromLocalToLatLng((int)p.X, (int)p.Y);
        //    }
        //}

        //// zoo max & center markers
        //private void button13_Click(object sender, RoutedEventArgs e)
        //{
        //    MainMap.ZoomAndCenterMarkers(null);
        //}

        //// tile louading starts
        //void MainMap_OnTileLoadStart()
        //{
        //    System.Windows.Forms.MethodInvoker m = delegate()
        //    {
        //        //progressBar1.Visibility = Visibility.Visible;
        //    };

        //    try
        //    {
        //        this.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, m);
        //    }
        //    catch
        //    {
        //    }
        //}

        //// tile loading stops
        //void MainMap_OnTileLoadComplete(long ElapsedMilliseconds)
        //{
        //    MainMap.ElapsedMilliseconds = ElapsedMilliseconds;

        //    System.Windows.Forms.MethodInvoker m = delegate()
        //    {
        //        //progressBar1.Visibility = Visibility.Hidden;
        //        //groupBox3.Header = "loading, last in " + MainMap.ElapsedMilliseconds + "ms";
        //    };

        //    try
        //    {
        //        this.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, m);
        //    }
        //    catch
        //    {
        //    }
        //}

        //// current location changed
        //void MainMap_OnCurrentPositionChanged(PointLatLng point)
        //{
        //    //mapgroup.Header = "gmap: " + point;
        //}

        private void SaveDealer()
        {
            if (txtLatitude.Text.Length == 0 || txtLatitude.Text == "0")
            {
                //MapQuestGeoCoder.GeocodeDealer(_selectedDealer);
                GoogleGeocoder.GeocodeDealer(_selectedDealer);
            }
            //TODO put in transation

            DealerService.Save(_selectedDealer);

            //delete all
            DealerService.DeleteDealerZipCodes(_selectedDealer.ID);

            //then add back
            if (_dealerZipCodes != null)
            {
                foreach (ZipGeoCode _zipGeoCode in _dealerZipCodes)
                {
                    DealerService.AddDealerZipCode(new DealerZipCode()
                    {
                        DealerID = _selectedDealer.ID, ZipGeoCodeID = _zipGeoCode.ID
                    });
                }
            }
        }
Beispiel #14
0
        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 #15
0
        public async Task <Patient> AddLatLongToPatient(Patient patient)
        {
            var formattedAddress =
                $"{patient.HouseNumber} {patient.HouseNumberAddon} {patient.Street} {patient.City} {patient.Country}";

            var geocoder = new GoogleGeocoder
            {
                ApiKey = _configuration["GoogleApiKey"]
            };

            try
            {
                var addresses = await geocoder.GeocodeAsync(formattedAddress);

                var enumerable = addresses.ToList();

                patient.Latitude  = enumerable.First().Coordinates.Latitude;
                patient.Longitude = enumerable.First().Coordinates.Longitude;
            }
            catch (Exception)
            {
                throw new ArgumentException("Invalid address.");
            }

            return(patient);
        }
        public async Task <bool> Create(User user)
        {
            IEnumerable <GoogleAddress> addresses = null;

            try
            {
                var geocoder = new GoogleGeocoder();
                addresses = await geocoder.GeocodeAsync($"{user.Organization_Address_Line1} {user.Organization_Address_Line2}, {user.Organization_City}, {user.Organization_State}, {user.Organization_PostalCode}");
            } catch (Exception ex) {
                Console.WriteLine("Error geocoding: " + ex.StackTrace);
            }

            var query = $"INSERT INTO [User] (Oid, Email, Person_Name, Verified, Admin, Recipient, Status, Phone_Number, Organization_Name, Organization_Address_Line1, " +
                        "Organization_Address_Line2, Organization_City, Organization_State, Organization_PostalCode, Organization_Country, Lat, Long) VALUES " +
                        $"(@Oid, " +
                        $"@Email, " +
                        $"@Person_Name, " +
                        "0, " +
                        "0, " +
                        "0, " +
                        $"'{UserStatus.Active.ToString()}', " +
                        $"@Phone_Number, " +
                        $"@Organization_Name, " +
                        $"@Organization_Address_Line1, " +
                        $"@Organization_Address_Line2, " +
                        $"@Organization_City, " +
                        $"@Organization_State, " +
                        $"@Organization_PostalCode, " +
                        $"@Organization_Country, " +
                        $"@Lat, " +
                        $"@Long)";

            using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
            {
                connection.Open();

                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@Oid", user.Oid);
                    command.Parameters.AddWithValue("@Email", user.Email);
                    command.Parameters.AddWithValue("@Person_Name", user.Person_Name ?? "");
                    command.Parameters.AddWithValue("@Phone_Number", user.Phone_Number ?? "");
                    command.Parameters.AddWithValue("@Organization_Name", user.Organization_Name ?? "");
                    command.Parameters.AddWithValue("@Organization_Address_Line1", user.Organization_Address_Line1 ?? "");
                    command.Parameters.AddWithValue("@Organization_Address_Line2", user.Organization_Address_Line2 ?? "");
                    command.Parameters.AddWithValue("@Organization_City", user.Organization_City ?? "");
                    command.Parameters.AddWithValue("@Organization_State", user.Organization_State ?? "");
                    command.Parameters.AddWithValue("@Organization_PostalCode", user.Organization_PostalCode ?? "");
                    command.Parameters.AddWithValue("@Organization_Country", user.Organization_Country ?? "");
                    command.Parameters.AddWithValue("@Lat", addresses?.FirstOrDefault()?.Coordinates.Latitude ?? 0.0);
                    command.Parameters.AddWithValue("@Long", addresses?.FirstOrDefault()?.Coordinates.Longitude ?? 0.0);

                    var res = command.ExecuteNonQuery();
                    command.Parameters.Clear();

                    return(res == 1);
                }
            }
        }
Beispiel #17
0
        public static async Task <Point> GeocodeAsync(string location, GeocodingApi apiType)
        {
            Point result;

            switch (apiType)
            {
            case GeocodingApi.Yandex:
                var codingResult = await YandexGeocoder.GeocodeAsync(location);

                if (!codingResult.Any())
                {
                    return(null);
                }
                var firstPoint = codingResult.First().Point;
                result = new Point
                {
                    Latitude  = firstPoint.Latitude,
                    Longitude = firstPoint.Longitude
                };
                break;

            case GeocodingApi.Google:
                var geocoder = new GoogleGeocoder();
                lock (KeyLock)
                {
                    if (!string.IsNullOrEmpty(_googleApiKey))
                    {
                        geocoder.ApiKey = _googleApiKey;
                    }
                }
                IEnumerable <GoogleAddress> addresses;
                try
                {
                    addresses = await geocoder.GeocodeAsync(location);
                }
                catch (Exception ex)
                {
                    Logger.LogException("GOOGLE GEO", LogLevel.Debug, ex);
                    return(null);
                }

                var firstAddress = addresses?.FirstOrDefault();
                if (firstAddress == null)
                {
                    return(null);
                }
                result = new Point
                {
                    Latitude  = firstAddress.Coordinates.Latitude,
                    Longitude = firstAddress.Coordinates.Longitude
                };

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(apiType), apiType, null);
            }
            return(result);
        }
        public void ServiceUrl_should_contains_channel_name()
        {
            var channel  = "channel1";
            var key      = new BusinessKey("client-id", "signature", channel);
            var geocoder = new GoogleGeocoder(key);

            Assert.Contains("channel=" + channel, geocoder.ServiceUrl);
        }
 protected override IGeocoder CreateGeocoder()
 {
     geocoder = new GoogleGeocoder
     {
         ApiKey = ConfigurationManager.AppSettings["googleApiKey"]
     };
     return(geocoder);
 }
Beispiel #20
0
 public AddressService(IAddressRepository coordinateRepository)
 {
     _addressRepository = coordinateRepository;
     _googleGeocoder    = new GoogleGeocoder()
     {
         ApiKey = API_KEY
     };
 }
Beispiel #21
0
        public GoogleGeocodeService(string apiKey)
        {
            if (String.IsNullOrEmpty(apiKey))
            {
                throw new ArgumentNullException(nameof(apiKey));
            }

            _geocoder = new GoogleGeocoder(apiKey);
        }
Beispiel #22
0
        public async Task <(double lat, double lon)> ObterCoordenadas(string endereco)
        {
            IGeocoder geocoder  = new GoogleGeocoder(_configuration["Maps:ApiKey"]);
            var       enderecos = await geocoder.GeocodeAsync(endereco);

            var resultado = enderecos.First();

            return(resultado.Coordinates.Latitude, resultado.Coordinates.Longitude);
        }
Beispiel #23
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();
            }
        }
        public void SyncDate(DateTime from, DateTime to)
        {
            var fieldControlConfiguration = new FieldControlApi.Configuration.AppSettingsConfiguration();
            var client = new Client(fieldControlConfiguration);

            var authenticationCache = new SimpleFileCache("authentication");
            var accessToken         = authenticationCache.GetOrPut(() => {
                client.Authenticate();
                return(client.AuthenticationToken);
            });

            client.AuthenticationToken = accessToken;

            FileLog.WriteJson(fieldControlConfiguration);
            FileLog.WriteJson(client);

            var cPlusConfiguration = new CPlus.Configurations.AppSettingsConfiguration();
            var cPlusOrdersQuery   = new OrdersQuery(cPlusConfiguration);
            var orderDao           = new OrderDao(cPlusConfiguration);

            FileLog.WriteJson(cPlusConfiguration);

            var orders     = cPlusOrdersQuery.Execute(from, to);
            var activities = client.Execute(new GetActivitiesRequest(from, to));

            FileLog.WriteJson(orders);
            FileLog.WriteJson(activities);

            var       geoCoderConfiguration = new AppSettingsGeoCoderConfiguration();
            IGeocoder geocoder = new GoogleGeocoder()
            {
                ApiKey = geoCoderConfiguration.GoogleKey
            };

            var services  = client.Execute(new GetServicesRequest());
            var employees = client.Execute(new GetActiveEmployeesRequest(from));

            var activityConveter = new ActivityConverter(
                services: services,
                employees: employees,
                customerFieldControlService: new CustomerFieldControlService(client, geocoder)
                );

            FileLog.WriteJson(services);
            FileLog.WriteJson(employees);

            var commands = new List <ICommand>()
            {
                new CreateFieldControlActivityCommand(orders, activities, activityConveter, client),
                new UpdateCPlusOrderStatusCommand(orders, activities, orderDao)
            };

            commands.ForEach(command => {
                command.Run();
            });
        }
Beispiel #25
0
        public async Task <Location> GetLocationByAddress(string address)
        {
            IGeocoder geocoder = new GoogleGeocoder()
            {
                ApiKey = _appConfiguration.GoogleMapApiKey
            };
            IEnumerable <Address> addresses = await geocoder.GeocodeAsync(address);

            return(addresses.First()?.Coordinates ?? new Location(0, 0));
        }
Beispiel #26
0
        public Form1()
        {
            InitializeComponent();

            googleGeocoder  = new GoogleGeocoder();
            yandexGeocoder  = new YandexGeocoder();
            geocoder        = new Geocoder();
            tokenizer       = new Tokenizer();
            geocoderService = new GeocoderService();
        }
Beispiel #27
0
        public static double GetLongFromCountryName(string country)
        {
            IGeocoder geocoder = new GoogleGeocoder()
            {
                ApiKey = "AIzaSyCPWzQ0h1vedStiQWFQ5Ez1Jf2f1rj209Q"
            };
            var addresses = geocoder.Geocode(country);

            return(addresses.First().Coordinates.Longitude);
        }
Beispiel #28
0
        public async Task <string> GetAddressFromLatLong(double lat, double lon)
        {
            async Task <string> getAddressFromCords()
            {
                IGeocoder googleGeoCoder = new GoogleGeocoder()
                {
                    ApiKey = Config.MappingConfig.GoogleMapsApiKey
                };
                IGeocoder bingGeoCoder = new BingMapsGeocoder(Config.MappingConfig.BingMapsApiKey);

                string address = null;

                try
                {
                    var addresses = await googleGeoCoder.ReverseGeocodeAsync(lat, lon);

                    if (addresses != null && addresses.Any())
                    {
                        address = addresses.First().FormattedAddress;
                    }
                }
                catch { /* Don't report on GeoLocation failures */ }

                if (string.IsNullOrWhiteSpace(address))
                {
                    try
                    {
                        var addressGeo = GetAddressFromLatLonLocationIQ(lat.ToString(), lon.ToString());

                        if (!String.IsNullOrWhiteSpace(addressGeo))
                        {
                            address = addressGeo;
                        }
                    }
                    catch { /* Don't report on GeoLocation failures */ }
                }

                if (string.IsNullOrWhiteSpace(address))
                {
                    try
                    {
                        var addresses = await bingGeoCoder.ReverseGeocodeAsync(lat, lon);

                        if (addresses != null && addresses.Count() > 0)
                        {
                            address = addresses.First().FormattedAddress;
                        }
                    }
                    catch { /* Don't report on GeoLocation failures */ }
                }
                return(address);
            }

            return(await _cacheProvider.RetrieveAsync <string>(string.Format(ReverseCacheKey, string.Format("{0} {1}", lat, lon).GetHashCode()), getAddressFromCords, CacheLength));
        }
        public static async Task <Address> GetAddressAsync(string pointAddress)
        {
            var geocoder = new GoogleGeocoder {
                ApiKey = ConfigurationManager.AppSettings["Google.Maps.Key"]
            };
            var addresses = await geocoder.GeocodeAsync(pointAddress);

            var addressesArray = addresses as GoogleAddress[] ?? addresses.ToArray();

            return(addressesArray.Length == 0 ? null : addressesArray.First());
        }
Beispiel #30
0
        public string GetAddressFromLatLong(double Lat, double Long)
        {
            IGeocoder geocoder = new GoogleGeocoder()
            {
                ApiKey = API_KEY
            };
            Location loc = new Location(Lat, Long);
            IEnumerable <Address> coordinates = geocoder.ReverseGeocode(loc);

            return(coordinates.First().FormattedAddress);
        }
        public async Task Integration()
        {
            // Arrange
            var client = new Client();
            var target = new GoogleGeocoder(client, Configuration.GoogleApiKey);

            // Act
            var location = await target.GeocodeAsync("1600 pennsylvania ave nw washington dc 20500");

            // Assert
            Assert.NotNull(location);
            Assert.Equal(1, location.Locations.Length);
            Assert.Equal("The White House, 1600 Pennsylvania Ave NW, Washington, DC 20500, USA", location.Locations[0].Name);
            Assert.Equal(38.90, location.Locations[0].Latitude, 2);
            Assert.Equal(-77.04, location.Locations[0].Longitude, 2);
        }
 public GoogleGeocoderTest()
 {
     _geocoder = new GoogleGeocoder();
 }