Inheritance: GoogleMapsApi.Entities.Common.SignableRequest
        public void GeocodingAsync_TimeoutTooShort_Throws()
        {
            var request = new GeocodingRequest { Address = "285 Bedford Ave, Brooklyn, NY 11211, USA" };

            Assert.Throws(Is.TypeOf<AggregateException>().And.InnerException.TypeOf<TimeoutException>(),
                () => GoogleMaps.Geocode.QueryAsync(request, TimeSpan.FromMilliseconds(1)).Wait());
        }
        public static String getLatFromAddress2(String s)
        {
            s = s.Replace("Suite", "");
            s = s.Replace("suite", "");
            s = s.Replace("Apt", "");
            s = s.Replace("apt", "");

            //Instance class use (Geocode)  (Can be made from static/instance class)
            var geocodeRequest = new GeocodingRequest
                                     {
                                         Address = s,
                                     };
            var geocodingEngine = new GeocodingEngine();

            GeocodingResponse geocode = geocodingEngine.GetGeocode(geocodeRequest);
            Result match1 = null;
            try
            {
                match1 = geocode.Results.First();
            }
            catch (Exception)
            {
                return "notfound";
            }
            Double lat = match1.Geometry.Location.Latitude;

            return lat.ToString();
        }
Beispiel #3
0
        public void GeocodingAsync_InvalidClientCredentials_Throws()
        {
            var request = new GeocodingRequest { Address = "285 Bedford Ave, Brooklyn, NY 11211, USA", ClientID = "gme-ThisIsAUnitTest", SigningKey = "AAECAwQFBgcICQoLDA0ODxAREhM=" };

            Assert.Throws(Is.TypeOf<AggregateException>().And.InnerException.TypeOf<AuthenticationException>(),
                          () => GoogleMaps.Geocode.QueryAsync(request).Wait());
        }
Beispiel #4
0
        public void GeocodingAsync_ReturnsCorrectLocation()
        {
            var request = new GeocodingRequest { Address = "285 Bedford Ave, Brooklyn, NY 11211, USA" };

            var result = GoogleMaps.Geocode.QueryAsync(request).Result;

            if (result.Status == Status.OVER_QUERY_LIMIT)
                Assert.Inconclusive("Cannot run test since you have exceeded your Google API query limit.");
            Assert.AreEqual(Status.OK, result.Status);
            Assert.AreEqual("40.7140415,-73.9613119", result.Results.First().Geometry.Location.LocationString);
        }
Beispiel #5
0
        public void GeocodingAsync_WithPreCanceledToken_Cancels()
        {
            var request = new GeocodingRequest { Address = "285 Bedford Ave, Brooklyn, NY 11211, USA" };
            var cts = new CancellationTokenSource();
            cts.Cancel();

            var task = GoogleMaps.Geocode.QueryAsync(request, cts.Token);

            Assert.Throws(Is.TypeOf<AggregateException>().And.InnerException.TypeOf<TaskCanceledException>(),
                            () => task.Wait());
        }
Beispiel #6
0
        public void Geocoding_ReturnsCorrectLocation()
        {
            var request = new GeocodingRequest
            {
                ApiKey = ApiKey,
                Address = "285 Bedford Ave, Brooklyn, NY 11211, USA"
            };

            var result = GoogleMaps.Geocode.Query(request);

            if (result.Status == Status.OVER_QUERY_LIMIT)
                Assert.Inconclusive("Cannot run test since you have exceeded your Google API query limit.");
            Assert.AreEqual(Status.OK, result.Status);
            // 40.{*}, -73.{*}
            StringAssert.IsMatch("40\\.\\d*,-73\\.\\d*", result.Results.First().Geometry.Location.LocationString);
        }
Beispiel #7
0
        //SiteViewModel
        public static SiteCoord GetLocForAddress(string address)
        {
            GeocodingRequest geocodeRequest = new GeocodingRequest()
            {
                Address = address + ", " + ", Australia"
            };

            GeocodingEngine geocodingEngine = new GeocodingEngine();
            GeocodingResponse geocode = geocodingEngine.GetGeocode(geocodeRequest);

            SiteCoord sc = new SiteCoord();
            sc.latitude = geocode.Results.FirstOrDefault().Geometry.Location.Latitude;
            sc.longitude = geocode.Results.FirstOrDefault().Geometry.Location.Longitude;

            return sc;
        }
        /// <summary>
        /// Pega o lat/lng conforme o local
        /// </summary>  
        /// <param name="local">Endereço</param>
        /// <returns></returns>
        public LatLng Get(string local)
        {
            var geocode = new GeocodingRequest
            {
                Address = local
            };

            var ret = GoogleMapsApi.GoogleMaps.Geocode.Query(geocode);
            var lat = new LatLng();
            foreach (var result in ret.Results)
            {
                lat.Latitude = result.Geometry.Location.Latitude;
                lat.Longitude = result.Geometry.Location.Longitude;
            }

            return lat;
        }
        public GeoCoordinate? GetLatLong(string address)
        {
            try
            {
                var request = new GeocodingRequest { Address = address };
                var result = GoogleMaps.Geocode.QueryAsync(request).Result;

                if (result.Status == Status.OVER_QUERY_LIMIT)
                    _log.WarnFormat("Cannot run test since you have exceeded your Google API query limit - {0} - address:{1}", Library.Utility.GetMethodDescription(), address);
                if (result.Results.Any())
                {
                    var coordinates = result.Results.First().Geometry.Location.LocationString.Split(',');
                    if (coordinates.Length > 0)
                        return new GeoCoordinate(coordinates[0], coordinates[1]);
                }
                return null;
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Errore inaspettato durante il recupero delle coordinate dell'indirizzo - CATCH Principale - {0} - address:{1}", ex, Library.Utility.GetMethodDescription(), address);
                return null;
            }
        } 
Beispiel #10
0
        static void Main(string[] args)
        {
            // Driving directions
            var drivingDirectionRequest = new DirectionsRequest
            {
                Origin = "NYC, 5th and 39",
                Destination = "Philladephia, Chesnut and Wallnut"
            };

            DirectionsResponse drivingDirections = GoogleMaps.Directions.Query(drivingDirectionRequest);
            PrintDirections(drivingDirections);

            // Transit directions
            var transitDirectionRequest = new DirectionsRequest
            {
                Origin = "New York",
                Destination = "Queens",
                TravelMode = TravelMode.Transit,
                DepartureTime = DateTime.Now
            };

            DirectionsResponse transitDirections = GoogleMaps.Directions.Query(transitDirectionRequest);
            PrintDirections(transitDirections);

            var dep_time = DateTime.Today
                            .AddDays(1)
                            .AddHours(13);

            var request = new DirectionsRequest
            {
                Origin = "T-centralen, Stockholm, Sverige",
                Destination = "Kungsträdgården, Stockholm, Sverige",
                TravelMode = TravelMode.Transit,
                DepartureTime = dep_time,
                Language = "sv"
            };

            DirectionsResponse result = GoogleMaps.Directions.Query(request);
            PrintDirections(result);

            // Geocode
            //https://maps.googleapis.com/maps/api/geocode/json?address=Parque+Marechal+Mascarenhas+de+Morais&components=locality:Porto%20Aelgre|administrative_area:RS|country:BR
            var geocodeRequest = new GeocodingRequest
            {
                Address = "Parque Marechal Mascarenhas de Morais",
                Components = new GeocodingComponents()
                {
                    Locality = "Porto Alegre",
                    AdministrativeArea = "RS",
                    Country = "BR"
                }

            };

            GeocodingResponse geocode = GoogleMaps.Geocode.Query(geocodeRequest);
            Console.WriteLine(geocode);

            // Static maps API - get static map of with the path of the directions request
            var staticMapGenerator = new StaticMapsEngine();

            //Path from previous directions request
            IEnumerable<Step> steps = drivingDirections.Routes.First().Legs.First().Steps;
            // All start locations
            IList<ILocationString> path = steps.Select(step => step.StartLocation).ToList<ILocationString>();
            // also the end location of the last step
            path.Add(steps.Last().EndLocation);

            string url = staticMapGenerator.GenerateStaticMapURL(new StaticMapRequest(new Location(40.38742, -74.55366), 9, new ImageSize(800, 400))
            {
                Pathes = new List<Path> { new Path
                    {
                        Style = new PathStyle
                        {
                            Color = "red"
                        },
                        Locations = path
                    }}
            });

            Console.WriteLine("Map with path: " + url);

            // Async! (Elevation)
            var elevationRequest = new ElevationRequest
            {
                Locations = new[] { new Location(54, 78) },
            };

            var task = GoogleMaps.Elevation.QueryAsync(elevationRequest)
                .ContinueWith(t => Console.WriteLine("\n" + t.Result));

            Console.Write("Asynchronous query sent, waiting for a reply..");

            while (!task.IsCompleted)
            {
                Console.Write('.');
                Thread.Sleep(1000);
            }

            Console.WriteLine("Finished! Press any key to exit...");
            Console.ReadKey();
        }
        public void ReverseGeocoding_ReturnsCorrectAddress()
        {
            var request = new GeocodingRequest { Location = new Location(40.7141289, -73.9614074) };

            var result = GoogleMaps.Geocode.Query(request);

            if (result.Status == Status.OVER_QUERY_LIMIT)
                Assert.Inconclusive("Cannot run test since you have exceeded your Google API query limit.");
            Assert.AreEqual(Status.OK, result.Status);
            Assert.AreEqual("285 Bedford Ave, Brooklyn, NY 11211, USA", result.Results.First().FormattedAddress);
        }
        public void Geocoding_TimeoutTooShort_Throws()
        {
            var request = new GeocodingRequest { Address = "285 Bedford Ave, Brooklyn, NY 11211, USA" };

            Utils.ThrowInnerException(() => GoogleMaps.Geocode.Query(request, TimeSpan.FromMilliseconds(1)));
        }
        public void Geocoding_InvalidClientCredentials_Throws()
        {
            var request = new GeocodingRequest { Address = "285 Bedford Ave, Brooklyn, NY 11211, USA", ClientID = "gme-ThisIsAUnitTest", SigningKey = "AAECAwQFBgcICQoLDA0ODxAREhM=" };

            Utils.ThrowInnerException(() => GoogleMaps.Geocode.Query(request));
        }
        public void GeocodingAsync_WithPreCanceledToken_Cancels()
        {
            var request = new GeocodingRequest { Address = "285 Bedford Ave, Brooklyn, NY 11211, USA" };
            var cts = new CancellationTokenSource();
            cts.Cancel();

            var task = GoogleMaps.Geocode.QueryAsync(request, cts.Token);
            task.ThrowInnerException();
        }
        public void GeocodingAsync_Cancel_Throws()
        {
            var request = new GeocodingRequest { Address = "285 Bedford Ave, Brooklyn, NY 11211, USA" };

            var tokeSource = new CancellationTokenSource();
            var task = GoogleMaps.Geocode.QueryAsync(request, tokeSource.Token);
            tokeSource.Cancel();
            task.ThrowInnerException();
        }
Beispiel #16
0
        private bool IsLocationOnEdge(Location[] locations, String from, string to, double tolerance)
        {
            GeocodingRequest startRequest = new GeocodingRequest()
            {
                Address = from,
                ApiKey = ConfigurationManager.AppSettings["GoogleMapsAPIKey"]
            };

            GeocodingRequest endRequest = new GeocodingRequest()
            {
                Address = to,
                ApiKey = ConfigurationManager.AppSettings["GoogleMapsAPIKey"]

            };

            GeocodingResponse startResponse = GoogleMapsApi.GoogleMaps.Geocode.Query(startRequest);
            GeocodingResponse endResponse = GoogleMapsApi.GoogleMaps.Geocode.Query(endRequest);

            Location startLocation = startResponse.Results.ElementAt(0).Geometry.Location;
            Location endLocation = endResponse.Results.ElementAt(0).Geometry.Location;

            bool startIsOnEdge = false;
            bool endIsOnEdge = false;

            for (int a = 0; a < locations.Length; a++)
            {
                if (!startIsOnEdge && this.GetStraightDistance(locations[a], startLocation) <= tolerance)
                {
                    startIsOnEdge = true;
                }

                if (!endIsOnEdge && this.GetStraightDistance(locations[a], endLocation) <= tolerance)
                {
                    endIsOnEdge = true;
                }

                if (startIsOnEdge && endIsOnEdge)
                {
                    break;
                }
            }

            if (startIsOnEdge && endIsOnEdge)
            {
                return true;
            }

            return false;
        }
Beispiel #17
0
		public static GeocodingResponse GetGeocode(GeocodingRequest request)
		{
			return MapsAPIEngine.GetGeocode(request);
		}
        private void AutoGeoCodeAndExport()
        {
            if (!MydataGrid.Columns.Contains("Longitude"))
            {
                MydataGrid.Columns.Add("Longitude", "Longitude");
                comboBoxLongitude.Items.Insert(0, "Latitude");
                comboBoxLatitude.Items.Insert(0, "Longitude");
                comboBoxLongitude.Items.Insert(0, "Longitude");
                comboBoxLatitude.Items.Insert(0, "Latitude");

            }
            if (!MydataGrid.Columns.Contains("Latitude"))
            {
                MydataGrid.Columns.Add("Latitude", "Latitude");

            }

            for (int i = 0; i < this.MydataGrid.Rows.Count - 1; i++)
            {
                DataGridViewRow row = this.MydataGrid.Rows[i];
                string texttogecode = "";
                int cnt = int.Parse(textFieldsToGeocode.Text);
                for (int j = 0; j < cnt; j++)
                {
                    texttogecode += row.Cells[j].Value.ToString() + " ";
                }
            var GeocodeRequest =new GeocodingRequest();
            GeocodeRequest.Address=texttogecode;

            var task= GoogleMaps.Geocode.Query(GeocodeRequest);
            if (task.Results.Count() > 0)
            {
                row.Cells["Longitude"].Value = task.Results.First().Geometry.Location.Longitude.ToString();
                row.Cells["Latitude"].Value = task.Results.First().Geometry.Location.Latitude.ToString();
            }
            else
            {
                row.Cells["Longitude"].Value = -1;
                row.Cells["Latitude"].Value = -1;
            }

            }

            //    ExportToExcel();
        }
Beispiel #19
0
        public Location[] GetLocations()
        {
            List<Location> locations = new List<Location>();

            for (int a = 0; a < this.WayPoints.Length; a++)
            {
                if (!String.IsNullOrEmpty(this.WayPoints[a]) && !String.IsNullOrWhiteSpace(this.WayPoints[a]))
                {
                    GeocodingRequest geocodingRequest = new GeocodingRequest()
                    {
                        Address = this.WayPoints[a]
                    };

                    GeocodingResponse geocodingResponse = GoogleMapsApi.GoogleMaps.Geocode.Query(geocodingRequest);

                    locations.Add(geocodingResponse.Results.ElementAt(0).Geometry.Location);
                }
            }

            return locations.ToArray();
        }
Beispiel #20
0
 public GeocodingResponse GetGeocode(GeocodingRequest request)
 {
     return new GeocodingEngine().GetGeocode(request);
 }
Beispiel #21
0
		static void Main(string[] args)
		{
			// Driving directions
			var drivingDirectionRequest = new DirectionsRequest
			{
				Origin = "NYC, 5th and 39",
				Destination = "Philladephia, Chesnut and Wallnut"
			};

			DirectionsResponse drivingDirections = GoogleMaps.Directions.Query(drivingDirectionRequest);
			PrintDirections(drivingDirections);

			// Transit directions
			var transitDirectionRequest = new DirectionsRequest
			{
				Origin = "New York",
				Destination = "Queens",
				TravelMode = TravelMode.Transit,
				DepartureTime = DateTime.Now
			};

			DirectionsResponse transitDirections = GoogleMaps.Directions.Query(transitDirectionRequest);
			PrintDirections(transitDirections);

			// Geocode
			var geocodeRequest = new GeocodingRequest
			{
				Address = "new york city",
			};

			GeocodingResponse geocode = GoogleMaps.Geocode.Query(geocodeRequest);
			Console.WriteLine(geocode);

			// Static maps API - get static map of with the path of the directions request
			var staticMapGenerator = new StaticMapsEngine();

			//Path from previous directions request
			IEnumerable<Step> steps = drivingDirections.Routes.First().Legs.First().Steps;
			// All start locations
			IList<ILocationString> path = steps.Select(step => step.StartLocation).ToList<ILocationString>();
			// also the end location of the last step
			path.Add(steps.Last().EndLocation);

			string url = staticMapGenerator.GenerateStaticMapURL(new StaticMapRequest(new Location(40.38742, -74.55366), 9, new ImageSize(800, 400))
			{
				Pathes = new List<Path> { new Path
					{
						Style = new PathStyle
						{
							Color = "red"
						},
						Locations = path
					}}
			});

			Console.WriteLine("Map with path: " + url);

			// Async! (Elevation)
			var elevationRequest = new ElevationRequest
			{
				Locations = new[] { new Location(54, 78) },
			};

			var task = GoogleMaps.Elevation.QueryAsync(elevationRequest)
				.ContinueWith(t => Console.WriteLine("\n" + t.Result));

			Console.Write("Asynchronous query sent, waiting for a reply..");

			while (!task.IsCompleted)
			{
				Console.Write('.');
				Thread.Sleep(1000);
			}

			Console.WriteLine("Finished! Press any key to exit...");
			Console.ReadKey();
		}