Exemple #1
0
        public static void getDistance(string restaurant)
        {
            string urlAddress = googleAddressURL
                                + Uri.EscapeDataString(restaurant);

            if (useGoogleKey == true)
            {
                urlAddress = urlAddress + "&key=" + googleApiKey;
            }
            var result = new System.Net.WebClient().DownloadString(urlAddress);
            GoogleGeoCodeResponse test = JsonConvert.DeserializeObject <GoogleGeoCodeResponse>(result);

            if (test.status == "OK")
            {
                double lat1     = Double.Parse(test.results[0].geometry.location.lat);
                double long1    = Double.Parse(test.results[0].geometry.location.lng);
                double latR1    = Math.PI * (lat1) / 180;
                double longR1   = Math.PI * (long1) / 180;
                double distance = Math.Acos(Math.Sin(latR1) * Math.Sin(userRequest.latitudeR) + Math.Cos(latR1) * Math.Cos(userRequest.latitudeR) * Math.Cos(longR1 - userRequest.longitudeR)) * 3963.1676;
                if (distance <= radiusInMiles)
                {
                    distance = Math.Truncate(100 * distance) / 100;
                    nearbyRestaurants.Add(restaurant + "," + lat1.ToString() + "," + long1.ToString() + ", ; Distance:" + distance + " Miles");
                }
            }
        }
Exemple #2
0
        public async Task <Address> ConvertToGeoAddress(string city, string street, string streetNumber)
        {
            var response = await _httpClient.GetAsync($"{ApiAddress}{city},{street},{streetNumber}&key={_apiMapsAccessKey}");

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Request unsuccesful");
            }
            var responsBody = await response.Content.ReadAsStringAsync();

            GoogleGeoCodeResponse addressDeserializeObject = JsonConvert.DeserializeObject <GoogleGeoCodeResponse>(responsBody);

            var responseLocation = addressDeserializeObject.results.FirstOrDefault();

            if (responseLocation == null)
            {
                throw new MatchingAddressNotFoundException($"{city}, {street}, {streetNumber}");
            }

            _addressValidator.ValidateGoogleApiResponse(city, street, streetNumber, responseLocation);

            dynamic loc = responseLocation.geometry.location;

            var addressObj = new Address();

            addressObj.Latitude  = loc.lat;
            addressObj.Lognitude = loc.lng;
            return(addressObj);
        }
Exemple #3
0
        public string Weather(string city)
        {
            string latitude;
            string longitude;

            string NrelResult    = string.Empty;
            string GeocodeResult = string.Empty;

            string nrel_api_key   = "SLtwKpcnZ6dQ2iT1LLFyJzJSlsgnrWGRAXSd43c6";
            string google_api_key = "AIzaSyACHx0lKjPIXLhqoaVfFeKp8sXqXQw-i8U";

            string geocode_url = @"https://maps.googleapis.com/maps/api/geocode/json?address=" + city + "&key=" + google_api_key;

            string geocode_result = GetRequest(geocode_url);

            GoogleGeoCodeResponse coordinates = JsonConvert.DeserializeObject <GoogleGeoCodeResponse>(geocode_result);

            latitude  = coordinates.results[0].geometry.location.lat;
            longitude = coordinates.results[0].geometry.location.lng;

            string url = @"https://developer.nrel.gov/api/solar/solar_resource/v1.json?api_key=" + nrel_api_key + "&lat=" + latitude + "&lon=" + longitude;

            string weather_request = GetRequest(url);

            NrelResponse nrelResponse = JsonConvert.DeserializeObject <NrelResponse>(weather_request);

            return("The average daily amount of strong sunlight in " + city + " is: " + nrelResponse.outputs.avg_dni.annual + " hours.");
        }
Exemple #4
0
        public static Location GeoCode(string address)
        {
            Location loc = new Location();

            try
            {
                address = HttpUtility.UrlEncode(address);
                string url = String.Format(GoogResources.Geocode, address);
                using (HttpResponseMessage response = Task.Run <HttpResponseMessage>(() => TheApiClient.GetAsync(url)).Result)
                {
                    string respString = response.Content.ReadAsStringAsync().Result;
                    if (response.IsSuccessStatusCode)
                    {
                        GoogleGeoCodeResponse geo = JsonConvert.DeserializeObject <GoogleGeoCodeResponse>(respString);
                        if (geo.status.ToUpper() == "OK")
                        {
                            return(LocFromGeo(geo));
                        }
                        else
                        {
                            return(loc);
                        }
                    }
                    else
                    {
                        return(loc);
                    }
                }
            }
            catch (Exception ex)
            {
                DataAPI.HandleError("GoogleAPI.GeoCode", ex);
                return(loc);
            }
        }
        public IHttpActionResult GetGeoLocation(string latitude, string longitude)
        {
            if ((latitude == null) || (longitude == null))
            {
                return(this.BadRequestEx(Error.PopulateInvalidParameter("latitude and/or longitude", "Can not be empty.")));
            }

            string url            = string.Format(GoogleGeoSearchUrlByGps, latitude, longitude);
            string responseString = string.Empty;
            GoogleGeoCodeResponse googleGeoCodeResponse = null;

            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Method = "GET";
                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

                if (webResponse != null)
                {
                    using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
                    {
                        responseString        = streamReader.ReadToEnd();
                        googleGeoCodeResponse = JsonConvert.DeserializeObject <GoogleGeoCodeResponse>(responseString);
                    }

                    return(Ok(googleGeoCodeResponse));
                }

                return(this.BadRequestEx(Error.AddressInformationNotFound));
            }
            catch (WebException e)
            {
                return(this.BadRequest(Error.PopulateUnexpectedException(e)));
            }
        }
        public static Coordinate GetCoordinates(string loc)
        {
            using (var clt = new WebClient())
            {
                string uri = "https://maps.googleapis.com/maps/api/geocode/json?address=" + loc + "&key=AIzaSyBm90sjnsiX7hNaEeA5nH-CicO5Jo-yUCt6JM";

                string geocodeInfo                = clt.DownloadString(uri);
                JavaScriptSerializer  oJS         = new JavaScriptSerializer();
                GoogleGeoCodeResponse latlongdata = oJS.Deserialize <GoogleGeoCodeResponse>(geocodeInfo);

                return(new Coordinate(Convert.ToDouble(latlongdata.results[0].geometry.location.lat), Convert.ToDouble(latlongdata.results[0].geometry.location.lng)));
            }
        }
Exemple #7
0
        public locationObject processJsonJavaScriptSerializer(String data)
        {
            GoogleGeoCodeResponse locationDetails = JsonConvert.DeserializeObject <GoogleGeoCodeResponse>(data);

            Console.WriteLine(locationDetails.results[0].geometry.location.lat);
            var answer = new locationObject
            {
                latitude  = Convert.ToDouble(locationDetails.results[0].geometry.location.lat),
                longitude = Convert.ToDouble(locationDetails.results[0].geometry.location.lng),
                placeId   = locationDetails.results[0].place_id
            };

            return(answer);
        }
Exemple #8
0
        private void GetGeoInfo()
        {
            string url = "http://maps.google.com/maps/api/geocode/json?address=" + _query + "&sensor=false";
            string JsonText;
            var    request = WebRequest.Create(url);

            request.ContentType = "application/json; charset=utf-8";
            var response = (HttpWebResponse)request.GetResponse();

            using (var sr = new StreamReader(response.GetResponseStream()))
            { JsonText = sr.ReadToEnd(); }

            GoogleGeoCodeResponse results = JsonConvert.DeserializeObject <GoogleGeoCodeResponse>(JsonText);

            _results = results;
        }
Exemple #9
0
        public static void getUserRequest()
        {
            userRequest = null;
            if (addressBoxServer != "")
            {
                string urlAddress = googleAddressURL
                                    + Uri.EscapeDataString(addressBoxServer);
                if (useGoogleKey == true)
                {
                    urlAddress = urlAddress + "&key=" + googleApiKey;
                }

                var result = new System.Net.WebClient().DownloadString(urlAddress);
                GoogleGeoCodeResponse test = JsonConvert.DeserializeObject <GoogleGeoCodeResponse>(result);
                if (test.status == "OK")
                {
                    userRequest = new latLong(test.results[0].geometry.location.lat, test.results[0].geometry.location.lng);
                }
            }
            else if (gpsLatBoxServer != "" && gpsLongBoxServer != "")
            {
                userRequest = new latLong(gpsLatBoxServer.ToString(), gpsLongBoxServer.ToString());
            }

            if (userRequest != null)
            {
                string urlLatLong = googleLatLongURL
                                    + userRequest.latitude + "," + userRequest.longitude;
                if (useGoogleKey == true)
                {
                    urlLatLong = urlLatLong + "&key=" + googleApiKey;
                }
                var resultPinCodes = new System.Net.WebClient().DownloadString(urlLatLong);
                var jsonPinCodes   = JsonConvert.DeserializeObject <GoogleGeoCodeResponse>(resultPinCodes);
                if (jsonPinCodes.status == "OK")
                {
                    address_component[] address_components = jsonPinCodes.results[0].address_components;
                    foreach (address_component add_comp in address_components)
                    {
                        if (add_comp.types[0] == "postal_code")
                        {
                            userRequest.pinCodes.Add(add_comp.long_name);
                        }
                    }
                }
            }
        }
Exemple #10
0
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("1. Busque una direccion");
                Console.WriteLine("2. Salir");
                string opcion = Console.ReadLine();

                if (opcion == "1")
                {
                    Console.WriteLine("Digite la direccion de la siguiente forma Pais, Ciudad, Direccion");
                    string direccion = Console.ReadLine();

                    var address = @"https://maps.googleapis.com/maps/api/geocode/json?&address=" + direccion;
                    var result  = new System.Net.WebClient().DownloadString(address);
                    GoogleGeoCodeResponse respuesta = JsonConvert.DeserializeObject <GoogleGeoCodeResponse>(result);

                    if (respuesta.status == "OK")
                    {
                        Console.Clear();
                        Console.WriteLine("**********************************************************************");
                        Console.WriteLine("*    Encontramos la ubicacion geografica de tu direccion:");
                        Console.WriteLine("*    Latitud: " + respuesta.results[0].geometry.location.lat);
                        Console.WriteLine("*    Longitud: " + respuesta.results[0].geometry.location.lng);
                        Console.WriteLine("*    Direccion: " + respuesta.results[0].formatted_address);
                        Console.WriteLine("**********************************************************************");
                        Console.ReadLine();
                        Console.Clear();
                    }
                    else
                    {
                        Console.WriteLine("No fue posible ubicar la dirección");
                    }
                }
                else if (opcion == "2")
                {
                    break;
                }
            }
        }
        private void CreateRequest(double Latitude, double Longitude)
        {
            string latitude = Latitude.ToString().Replace(",", ".");
            string longitude = Longitude.ToString().Replace(",", ".");
            string UrlRequest = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude;
            string number = "", route = "";

            using (var webClient = new System.Net.WebClient())
            {
                var json = webClient.DownloadString(UrlRequest);
                GoogleGeoCodeResponse test = JsonConvert.DeserializeObject <GoogleGeoCodeResponse>(json);
                foreach (var info in test.results[0].address_components)
                {
                    if (info.types[0] == "street_number")
                    {
                        number = info.long_name;
                    }
                    else if (info.types[0] == "route")
                    {
                        route = info.long_name;
                    }
                    else if (info.types[0] == "administrative_area_level_1")
                    {
                        cityRegion = info.long_name;
                    }
                    else if (info.types[0] == "locality")
                    {
                        cityName = info.long_name;
                    }
                }
                streetAddress   = route + " " + number;
                currentDateTime = GetTimeDate();
                fullName        = test.results[0].formatted_address;
            }
            UpdateDataBase(Latitude, Longitude);
        }
Exemple #12
0
        public static Location LocFromGeo(GoogleGeoCodeResponse geo)
        {
            Location loc = new Location();

            if (geo.status.ToUpper() == "OK" && geo.results.GetLength(0) > 0)
            {
                results result = geo.results[0];
                if (!string.IsNullOrWhiteSpace(result.formatted_address))
                {
                    loc.Address = result.formatted_address;
                }
                if (!string.IsNullOrWhiteSpace(result.place_id))
                {
                    loc.Place_Id = result.place_id;
                }
                if (!string.IsNullOrWhiteSpace(result.geometry.location.lat))
                {
                    loc.Latitude = Convert.ToDecimal(result.geometry.location.lat);
                }
                if (!string.IsNullOrWhiteSpace(result.geometry.location.lng))
                {
                    loc.Longitude = Convert.ToDecimal(result.geometry.location.lng);
                }
                foreach (address_component addr in result.address_components)
                {
                    foreach (string type in addr.types)
                    {
                        switch (type)
                        {
                        case "country":
                            loc.Country = addr.long_name;
                            break;

                        case "postal_code":
                            loc.Postal = addr.long_name;
                            break;

                        case "route":
                        case "street_address":
                            loc.Street = loc.Street + addr.long_name;
                            break;

                        case "postal_town":
                        case "locality":
                            loc.City = addr.long_name;
                            break;

                        case "administrative_area_level_1":
                            loc.State = addr.long_name;
                            break;

                        case "street_number":
                            loc.Street = addr.long_name + " " + loc.Street;
                            break;
                            //case "intersection":
                            //case "political":
                            //case "administrative_area_level_2":
                            //case "administrative_area_level_3":
                            //case "colloquial_area":
                            //case "sublocality":
                            //case "neighborhood":
                            //case "premise":
                            //case "subpremise":
                            //case "natural_feature":
                            //case "airport":
                            //case "park":
                            //case "point_of_interest":
                            //case "post_box":
                            //case "floor":
                            //case "room":
                            //case "establishment":
                            //case "sublocality_level_1":
                            //case "sublocality_level_2":
                            //case "sublocality_level_3":
                            //case "sublocality_level_4":
                            //case "sublocality_level_5":
                            //case "postal_code_suffix":
                            //    break;
                        }
                    }
                }
            }

            return(loc);
        }