예제 #1
0
        void SignedAllGoogleServices(IUnityContainer container)
        {
            var configuration = container.Resolve <IConfiguration>();
            var gooleApiKey   = configuration.GetString("google:ApiKey");

            GoogleSigned.AssignAllServices(new GoogleSigned(gooleApiKey));
        }
예제 #2
0
 void Application_Start(object sender, EventArgs e)
 {
     // Code that runs on application startup
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     GoogleSigned.AssignAllServices(new GoogleSigned("AIzaSyCxOXK6QIQRnC5NxEl0BqQ20XqwkVVbdK0"));
 }
예제 #3
0
        static void Main(string[] args)
        {
            // GlobalLibraryState.Init("ZipKoo", "Marcel", "YyQzKeSSX0TlgsI4", "POL");
            GlobalLibraryState.Init("ZipKoo", "root", "bloodrayne", "POL");
            GoogleSigned.AssignAllServices(new GoogleSigned("AIzaSyCzOcXgCQ_1Nng6shWR9FRS2tRFBItyG0E"));

            var taskList = new List <Task>();

            var zipReader = DatabaseHelper.ExecuteReader(GlobalLibraryState.ConnectionString,
                                                         "SELECT DISTINCT district_code AS ZIP " +
                                                         "FROM zip_koo " +
                                                         "WHERE lat IS NULL OR lng IS NULL;");

            using (zipReader)
            {
                while (zipReader.Read())
                {
                    string zip = zipReader.GetString("ZIP");
                    // taskList.Add(Task.Run(() =>
                    AddZipCoordinate(zip);
                    _progress.PrintProgress();
                    Log.Flush();
                    // ));
                }
            }

            var whenAll = Task.WhenAll(taskList);

            while (!whenAll.IsCompleted)
            {
                _progress.PrintProgress();
                Thread.Sleep(1000);
                Log.Flush();
            }
        }
예제 #4
0
 public ViewModel()
 {
     GoogleSigned.AssignAllServices(new GoogleSigned(Environment.GetEnvironmentVariable("GoogleApiKey")));
     Times     = Enumerable.Range(0, 24).Select(i => i.ToString("00")).ToArray();
     Zoom      = 8;
     PlanTypes = new[] { PlanType.Direct, PlanType.OneSwitchNoWalking, PlanType.OneSwitchLessThen500Meters };
 }
예제 #5
0
        static void DoGeocodeRequest()
        {
            //always need to use AIzaSyDyrcySjhH_JOpJ9461agf8vkyJbvkmD_k for requests.  Do this in App_Start.
            GoogleSigned.AssignAllServices(new GoogleSigned("AIzaSyDyrcySjhH_JOpJ9461agf8vkyJbvkmD_k"));
            //commented out in the loop

            Console.WriteLine();
            Console.WriteLine("Enter an address to geocode: ");
            string geocodeAddress = Console.ReadLine();

            var request = new GeocodingRequest();

            request.Address = geocodeAddress;
            var response = new GeocodingService().GetResponse(request);

            //The GeocodingService class submits the request to the API web service, and returns the
            //response strongly typed as a GeocodeResponse object which may contain zero, one or more results.

            //Assuming we received at least one result, let's get some of its properties:
            if (response.Status == ServiceResponseStatus.Ok && response.Results.Count() > 0)
            {
                var result = response.Results.First();

                Console.WriteLine("Full Address: " + result.FormattedAddress);                         // "1600 Pennsylvania Ave NW, Washington, DC 20500, USA"
                Console.WriteLine("Latitude: " + result.Geometry.Location.Latitude);                   // 38.8976633
                Console.WriteLine("Longitude: " + result.Geometry.Location.Longitude);                 // -77.0365739
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("Unable to geocode.  Status={0} and ErrorMessage={1}", response.Status, response.ErrorMessage);
            }
        }
예제 #6
0
        public static int GetDistance(List <string> locations)
        {
            int distance = 0;

            GoogleSigned.AssignAllServices(new GoogleSigned(apiKey));

            var request = new DistanceMatrixRequest();

            foreach (string s in locations)
            {
                request.AddOrigin(new Google.Maps.Location(s));
                request.AddDestination(new Google.Maps.Location(s));
            }
            request.Units = Units.imperial;

            var response = new DistanceMatrixService().GetResponse(request);

            if (response.Status == ServiceResponseStatus.Ok && response.Rows.Count() > 0)
            {
                for (int i = 0; i < response.Rows.Length - 1; i++)
                {
                    distance += (int)response.Rows[i].Elements[i + 1].distance.Value;
                }
            }

            return(distance);
        }
예제 #7
0
        /// <summary>
        /// Retrieves the map with the given request and writes the image bytes to the given target stream.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="targetStream"></param>
        /// <returns>number of bytes written to the target stream</returns>
        public int GetMapToStream(StaticMapRequest mapOptions, System.IO.Stream outputStream)
        {
            Uri          requestUri      = new Uri(BaseUri, mapOptions.ToUri());
            GoogleSigned signingInstance = GoogleSigned.SigningInstance;

            if (signingInstance != null)
            {
                requestUri = new Uri(signingInstance.GetSignedUri(requestUri));
            }

            int totalBytes = 0;

            WebRequest request = WebRequest.Create(requestUri);

            using (WebResponse response = request.GetResponse())
            {
                Stream inputStream = response.GetResponseStream();

                int       bytesRead          = 0;
                const int BYTE_BUFFER_LENGTH = 4096;
                byte[]    buffer             = new byte[BYTE_BUFFER_LENGTH];

                do
                {
                    bytesRead = inputStream.Read(buffer, 0, BYTE_BUFFER_LENGTH);
                    outputStream.Write(buffer, 0, bytesRead);
                    totalBytes += bytesRead;
                }while(bytesRead > 0);
            }

            return(totalBytes);
        }
예제 #8
0
        static void README_QuickStart_Sample1()
        {
            //always need to use YOUR_API_KEY for requests.  Do this in App_Start.
            GoogleSigned.AssignAllServices(new GoogleSigned("YOUR_API_KEY"));

            var request = new GeocodingRequest();

            request.Address = "1600 Pennsylvania Ave NW, Washington, DC 20500";
            var response = new GeocodingService().GetResponse(request);

            //The GeocodingService class submits the request to the API web service, and returns the
            //response strongly typed as a GeocodeResponse object which may contain zero, one or more results.

            //Assuming we received at least one result, let's get some of its properties:
            if (response.Status == ServiceResponseStatus.Ok && response.Results.Count() > 0)
            {
                var result = response.Results.First();

                Console.WriteLine("Full Address: " + result.FormattedAddress);                         // "1600 Pennsylvania Ave NW, Washington, DC 20500, USA"
                Console.WriteLine("Latitude: " + result.Geometry.Location.Latitude);                   // 38.8976633
                Console.WriteLine("Longitude: " + result.Geometry.Location.Longitude);                 // -77.0365739
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("Unable to geocode.  Status={0} and ErrorMessage={1}", response.Status, response.ErrorMessage);
            }
        }
예제 #9
0
        public static void Register(HttpConfiguration config)
        {
            //always need to use YOUR_API_KEY for requests.  Do this in App_Start.
            GoogleSigned.AssignAllServices(new GoogleSigned(ConfigurationManager.AppSettings["GoogleMapAPI"]));

            // Json settings
            config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver  = new CamelCasePropertyNamesContractResolver();
            config.Formatters.JsonFormatter.SerializerSettings.Formatting        = Formatting.Indented;
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
            {
                ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                Formatting        = Newtonsoft.Json.Formatting.Indented,
                NullValueHandling = NullValueHandling.Ignore,
            };

            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
예제 #10
0
        public LocationDto GetLocalization(DataDto dto)
        {
            IConfigurationSection googleMapsSection = _configuration.GetSection("Integrations:Google");
            var apiKey = googleMapsSection["ApiKey"];

            GoogleSigned.AssignAllServices(new GoogleSigned(apiKey));

            var request = new GeocodingRequest
            {
                Address = dto.Address
            };
            var response = new GeocodingService().GetResponse(request);
            var result   = response.Results.FirstOrDefault();

            if (result != null)
            {
                return(new LocationDto
                {
                    Latitude = result.Geometry.Location.Latitude,
                    Longitude = result.Geometry.Location.Longitude
                });
            }

            return(null);
        }
예제 #11
0
        public string GetCoordinates(ref string longitude, ref string latitude, string addressFrom)
        {
            string google_api_key = System.Configuration.ConfigurationManager.AppSettings["google_api_key"];

            try
            {
                GoogleSigned.AssignAllServices(new GoogleSigned(google_api_key));

                var request = new GeocodingRequest();
                request.Address = addressFrom;
                var response = new GeocodingService().GetResponse(request);

                //Assuming we received at least one result, let's get some of its properties:
                if (response.Status == ServiceResponseStatus.Ok && response.Results.Count() > 0)
                {
                    var result = response.Results.First();

                    longitude = result.Geometry.Location.Longitude.ToString();
                    latitude  = result.Geometry.Location.Latitude.ToString();

                    return("success");
                }
                else
                {
                    throw new System.ArgumentException();
                }
            }
            catch (Exception ex)
            {
                string strError = "";
                strError = "No Longitude/Latitude Found for " + addressFrom + ". Please enter a valid City, State.";
                return(strError);
            }
        }
예제 #12
0
        GetCoordinates(string address)
        {
            MapsCoordinatesBindingModel result =
                new MapsCoordinatesBindingModel();

            GoogleSigned.AssignAllServices(
                new GoogleSigned(CommonSecurityConstants
                                 .GoogleMapsApiKey));

            GeocodingRequest request = new GeocodingRequest();

            request.Address = new Location(address);

            GeocodeResponse response = await Task.Run(() => {
                return(new GeocodingService()
                       .GetResponseAsync(request).Result);
            });

            if (response.Status == ServiceResponseStatus.Ok &&
                response.Results.Count() > 0)
            {
                Result placeResult = response
                                     .Results.FirstOrDefault();

                result.Lat = placeResult.Geometry
                             .Location.Latitude;

                result.Lng = placeResult.Geometry
                             .Location.Longitude;
            }

            return(result);
        }
예제 #13
0
        static LocationDetails GetLocationDetails(String postcode)
        {
            LocationDetails locationDetails = new LocationDetails();

            GoogleSigned.AssignAllServices(new GoogleSigned("APIKEY")); // APIKEY van Google hier zetten

            var request = new GeocodingRequest();

            request.Address = postcode;
            {
                var response = new GeocodingService().GetResponse(request);
                if (response.Status == ServiceResponseStatus.OverQueryLimit)
                {
                    WriteLine("API Quotum Reached");
                }

                if (response.Status == ServiceResponseStatus.Ok && response.Results.Count() > 0)
                {
                    var result = response.Results.First();
                    if (result.AddressComponents.Length > 2)
                    {
                        locationDetails = new LocationDetails(
                            result.AddressComponents[0].ShortName,
                            result.AddressComponents[1].LongName,
                            result.AddressComponents[2].LongName,
                            result.Geometry.Location.Longitude,
                            result.Geometry.Location.Latitude,
                            result.PlaceId);

                        Console.WriteLine("Postcode: " +
                                          result.AddressComponents[0].LongName + "plaats: " +
                                          result.AddressComponents[1].LongName + "regio: " +
                                          result.AddressComponents[2].LongName + "," + result.Geometry.Location.Longitude + ", " +
                                          result.Geometry.Location.Latitude,
                                          result.PlaceId);
                    }
                    else
                    {
                        locationDetails = new LocationDetails(
                            result.AddressComponents[0].ShortName,
                            result.AddressComponents[1].LongName, "",
                            result.Geometry.Location.Longitude,
                            result.Geometry.Location.Latitude,
                            result.PlaceId);
                        Console.WriteLine("Postcode: " +
                                          result.AddressComponents[0].LongName + "plaats: " +
                                          result.AddressComponents[1].LongName + "," + result.Geometry.Location.Longitude + ", " +
                                          result.Geometry.Location.Latitude,
                                          result.PlaceId);
                    }
                }
                else
                {
                    Console.WriteLine("Unable to geocode.  Status={0} and ErrorMessage={1}",
                                      response.Status, response.ErrorMessage);
                }
                return(locationDetails);
            }
        }
예제 #14
0
        public GeocodeTransform(IContext context) : base(context, "object")
        {
            ProducesFields = true;

            if (context.Operation.Parameters.Any())
            {
                var lat = context.Operation.Parameters.FirstOrDefault(p => p.Name.ToLower().In("lat", "latitude"));
                if (lat == null)
                {
                    Error("The fromaddress (geocode) transform requires an output field named lat, or latitude.");
                    Run = false;
                    return;
                }
                if (lat.Type != "double")
                {
                    Error($"The goecode {lat.Name} field must be of type double.");
                    Run = false;
                    return;
                }

                var lon = context.Operation.Parameters.FirstOrDefault(p => p.Name.ToLower().In("lon", "long", "longitude"));
                if (lon == null)
                {
                    Error("The fromaddress (geocode) transform requires an output field named lon, long, or longitude.");
                    Run = false;
                    return;
                }
                if (lon.Type != "double")
                {
                    Error($"The goecode {lon.Name} field must be of type double.");
                    Run = false;
                    return;
                }
            }
            else
            {
                Error("The fromaddress (geocode) transform requires a collection of output fields; namely: latitude, longitude, and formattedaddress (optional).");
                Run = false;
                return;
            }

            _input  = SingleInput();
            _output = MultipleOutput();
            if (context.Operation.Key != string.Empty)
            {
                GoogleSigned.AssignAllServices(new GoogleSigned(context.Operation.Key));
            }
            _originalConnectionLimit = ServicePointManager.DefaultConnectionLimit;
            ServicePointManager.DefaultConnectionLimit = 255;
            _rateGate        = new RateGate(context.Operation.Limit, TimeSpan.FromMilliseconds(context.Operation.Time));
            _componentFilter = new ComponentFilter {
                AdministrativeArea = context.Operation.AdministrativeArea,
                Country            = context.Operation.Country,
                Locality           = context.Operation.Locality,
                PostalCode         = context.Operation.PostalCode,
                Route = context.Operation.Route
            };
        }
예제 #15
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;

            MapService.ServiceToken  = Secrets.MapToken;
            AppConstants.ShyftClient = new ShyftClient(Secrets.LyftClientId, Secrets.LyftClientSecret);
            GoogleSigned.AssignAllServices(new GoogleSigned(Secrets.GoogleMapsApiKey));
        }
예제 #16
0
 public Data()
 {
     GoogleSigned.AssignAllServices(new GoogleSigned(Globals.API_KEY));
     homeAddress    = Deserialize <Address>(HOME_ADDRESS_FILENAME);
     customersList  = Deserialize <List <Address> >(CUSTOMERS_FILENAME);
     distanceMatrix = DeserializeDistanceMatrix(DIMENSIONS_MATRIX_FILENAME);
     carsList       = Deserialize <List <Car> >(CAR_LIST_FILENAME);
     currentCars    = Deserialize <List <Car> >(CURRENT_CARS_LIST_FILENAME);
 }
예제 #17
0
 public DataCopy(Data other)
 {
     GoogleSigned.AssignAllServices(new GoogleSigned(Globals.API_KEY));
     homeAddress    = other.HomeAddress();
     customersList  = new List <Address>(other.AllCustomers().ToList());
     distanceMatrix = (DistanceMatrixResponse.DistanceMatrixRows[])other.GetDistanceMatrix().Clone();
     carsList       = new List <Car>(other.AllCarsList().ToList());
     currentCars    = new List <Car>(other.CurrentCars());
 }
예제 #18
0
        static Utils()
        {
            // GoogleSigned.AssignAllServices(new GoogleSigned("AIzaSyCtcn_dJ3F-DfVCKyaO1-lTBIkoIbyZZYo"));
            GoogleSigned.AssignAllServices(new GoogleSigned("AIzaSyCcGVtsZ0A0QHv8Kq04Uh6fCke2ajKLbvQ"));
            //GoogleSigned.AssignAllServices(new GoogleSigned("AIzaSyDG4k1RT9mdKFtSlUC5D0K04_IXCtyb2po"));


            Cargado = true;
        }
        /// <summary>
        /// Set the Google ClientId and PrivateKey in order to use Google API for Business
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="privateKey"></param>
        internal void SetCreditals(string clientId, string privateKey)
        {
            _clientId   = clientId;
            _privateKey = privateKey;

            if (!String.IsNullOrEmpty(_clientId) && !String.IsNullOrEmpty(_privateKey))
            {
                GoogleSigned.AssignAllServices(new GoogleSigned(clientId, privateKey));
            }
        }
예제 #20
0
 static void Main()
 {
     // custom settings
     AppDomain.CurrentDomain.SetData("DataDirectory", Settings.GetAppDataDirectory());
     GoogleSigned.AssignAllServices(new GoogleSigned(Settings.API_KEY));
     // winforms settings
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new GeographyForm());
 }
예제 #21
0
        public MapsHttp(GoogleSigned signingSvc)
        {
            this.signingSvc = signingSvc;
            this.client     = new HttpClient();

            if (signingSvc != null && string.IsNullOrEmpty(signingSvc.ReferralUrl) == false)
            {
                client.DefaultRequestHeaders.Add("Referer", signingSvc.ReferralUrl);
            }
        }
예제 #22
0
        /// <summary>
        /// Gets a Uri with a signature calculated.
        /// See https://developers.google.com/maps/documentation/maps-static/get-api-key
        /// for more info.
        /// </summary>
        /// <param name="signingInfo"></param>
        /// <returns></returns>
        public string ToUriSigned(GoogleSigned signingInfo = null)
        {
            if (signingInfo == null)
            {
                signingInfo = GoogleSigned.SigningInstance;
            }

            Uri reqUri = this.ToUri();

            return(signingInfo.GetSignedUri(reqUri));
        }
        public void SignedUrl_1()
        {
            GoogleSigned sign = GetGoogleSigned_TestInstance();

            var uri = "http://testserver/maps/api/outputType?sensor=false";

            uri += "client=" + sign.ClientId;

            string expected = "nEt2lIqwIuMkMia4OtJhsCc8cT0=";
            string actual   = sign.GetSignature(uri);

            Assert.AreEqual(expected, actual);
        }
예제 #24
0
            protected virtual StreamReader GetStreamReader(Uri uri, GoogleSigned signingInstance)
            {
                if (signingInstance != null)
                {
                    uri = new Uri(signingInstance.GetSignedUri(uri));
                }

                WebResponse response = WebRequest.Create(uri).GetResponse();

                StreamReader sr = new StreamReader(response.GetResponseStream());

                return(sr);
            }
예제 #25
0
        public void Signed_GeocodingRequest_Works()
        {
            var request = new GeocodingRequest
            {
                Address = "Stathern, UK",
                Sensor  = false
            };

            GoogleSigned.AssignAllServices(GetRealSigningInstance());
            var response = new GeocodingService().GetResponse(request);

            Assert.AreEqual(ServiceResponseStatus.Ok, response.Status);
        }
예제 #26
0
        public BitmapImage GenerateMap(string address)
        {
            GoogleSigned.AssignAllServices(new GoogleSigned(API_KEY));
            var map = new StaticMapRequest();

            map.Center = new Location(address);
            map.Size   = new System.Drawing.Size(400, 400);
            map.Zoom   = 14;

            StaticMapService staticMapService = new StaticMapService();
            BitmapImage      img = new BitmapImage();

            img.StreamSource = staticMapService.GetStream(map);
            return(img);
        }
예제 #27
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GoogleApiKey = WebConfigurationManager.AppSettings["GoogleMapsApiKey"];
            GoogleSigned.AssignAllServices(new GoogleSigned(GoogleApiKey));

            heightRequestThreadReference =
                new Thread(new ThreadStart(new HeightRequestProcessor().Process));
            heightRequestThreadReference.IsBackground = true;
            heightRequestThreadReference.Start();
        }
예제 #28
0
        public void ConfigureServices(IServiceCollection services)
        {
            var gooleMapsApiKey = _configuration["GoogleMapsApiKey"];

            GoogleSigned.AssignAllServices(new GoogleSigned(gooleMapsApiKey));

            services.AddScoped <IDistanceMatrixService, DistanceMatrixService>();
            services.AddMvc();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Maps API", Version = "v1"
                });
            });
        }
예제 #29
0
        public static void Configure(HttpConfiguration config)
        {
            GoogleSigned.AssignAllServices(new GoogleSigned(ConfigurationManager.AppSettings["GMAPS_API_KEY"]));

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            Injector.Begins(config);

            config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(Injector.GetContainer);
        }
예제 #30
0
        private LatLng GetCoordinatesFromAddress(string address)
        {
            GoogleSigned.AssignAllServices(new GoogleSigned("AIzaSyDNyG3Se0JEtTj20OiN4qea8rKcvaYHdjI"));

            var request = new GeocodingRequest {
                Address = address
            };
            var response = new GeocodingService().GetResponse(request);

            if (response.Status != ServiceResponseStatus.Ok || !response.Results.Any())
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            return(response.Results.First().Geometry.Location);
        }