Inheritance: GoogleMapsApi.Entities.Common.SignableRequest
コード例 #1
0
        public void Directions_SumOfStepDistancesCorrect()
        {
            var request = new DirectionsRequest { Origin = "285 Bedford Ave, Brooklyn, NY, USA", Destination = "185 Broadway Ave, Manhattan, NY, USA" };

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

            if (result.Status == DirectionsStatusCodes.OVER_QUERY_LIMIT)
                Assert.Inconclusive("Cannot run test since you have exceeded your Google API query limit.");
            Assert.AreEqual(DirectionsStatusCodes.OK, result.Status);
            Assert.AreEqual(8229, result.Routes.First().Legs.First().Steps.Sum(s => s.Distance.Value));
        }
コード例 #2
0
        public async Task<Route> PlanNewRoute(Location origin)
        {
            var destination = NextLocation(origin);
            var request = new DirectionsRequest
            {
                Origin = origin.Name,
                Destination = destination.Name,
                TravelMode = TravelMode.Driving
            };

            return await CallGoogleService(origin, request, destination);
        }
コード例 #3
0
        public void Directions_WithWayPoints()
        {
            var request = new DirectionsRequest { Origin = "NYC, USA", Destination = "Miami, USA", Waypoints = new string[] { "Philadelphia, USA" }, OptimizeWaypoints = true };

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

            if (result.Status == DirectionsStatusCodes.OVER_QUERY_LIMIT)
                Assert.Inconclusive("Cannot run test since you have exceeded your Google API query limit.");
            Assert.AreEqual(DirectionsStatusCodes.OK, result.Status);
            Assert.AreEqual(156097, result.Routes.First().Legs.First().Steps.Sum(s => s.Distance.Value), 10 * 1000);

            StringAssert.Contains("Philadelphia", result.Routes.First().Legs.First().EndAddress);
        }
コード例 #4
0
        public TravelTime GetTravelTime(Location origin, Location destination, TravelMode mode)
        {
            string originString = StringForm(origin);
            string destinationString = StringForm(destination);
            var request = new DirectionsRequest()
            {
                ApiKey = apiKey,
                Origin = originString,
                Destination = destinationString,
                TravelMode = mode,
                DepartureTime = DateTime.Now,
            };

            var response = GoogleMapsApi.GoogleMaps.Directions.Query(request);

            var route = response.Routes.FirstOrDefault();
            if (route != null)
            {
                // For routes that contain no waypoints, the route will consist of a single "leg".
                var leg = route.Legs.FirstOrDefault();
                if (leg != null)
                {
                    // Get the origin and destination's lat/long if not yet known.
                    origin.Latitude = origin.Latitude ?? leg.StartLocation.Latitude.ToString();
                    origin.Longitude = origin.Longitude ?? leg.StartLocation.Longitude.ToString();

                    destination.Latitude = destination.Latitude ?? leg.EndLocation.Latitude.ToString();
                    destination.Longitude = destination.Longitude ?? leg.EndLocation.Longitude.ToString();

                    var transitStep = leg.Steps.FirstOrDefault(a => a.TransitDetails != null);

                    TimeSpan duration = leg.Duration.Value;
                    TravelTime time = new TravelTime
                     {
                         Mode = mode.ToString(),
                         Days = duration.Days,
                         Hours = duration.Hours,
                         Minutes = duration.Minutes,
                         Seconds = duration.Seconds,
                         TransitDepartureTime = transitStep == null ? null : transitStep.TransitDetails.DepartureTime.Text,
                         TransitDepartureStop = transitStep == null ? null : transitStep.TransitDetails.DepartureStop.Name,
                         TransitArrivalTime = transitStep == null ? null : transitStep.TransitDetails.ArrivalTime.Text,
                         TransitArrivalStop = transitStep == null ? null : transitStep.TransitDetails.ArrivalStop.Name,
                         TransitRoute = transitStep == null ? null : transitStep.TransitDetails.Lines.ShortName,
                         TransitRouteDescription = transitStep == null ? null : transitStep.TransitDetails.Lines.Name
                     };
                    return time;
                }
            }
            return null;
        }
コード例 #5
0
ファイル: DirectionsTests.cs プロジェクト: maximn/google-maps
 public void Directions_ErrorMessage()
 {
     var request = new DirectionsRequest
     {
         ApiKey = "ABCDEF", // Wrong API Key
         Origin = "285 Bedford Ave, Brooklyn, NY, USA",
         Destination = "185 Broadway Ave, Manhattan, NY, USA"
     };
     var result = GoogleMaps.Directions.Query(request);
     if (result.Status == DirectionsStatusCodes.OVER_QUERY_LIMIT)
         Assert.Inconclusive("Cannot run test since you have exceeded your Google API query limit.");
     Assert.AreEqual(DirectionsStatusCodes.REQUEST_DENIED, result.Status);
     Assert.IsNotNull (result.ErrorMessage);
     Assert.IsNotEmpty (result.ErrorMessage);
 }
コード例 #6
0
        public void Directions_Correct_OverviewPath()
        {
            DirectionsRequest request = new DirectionsRequest();
            request.Destination = "maleva 10, Ahtme, Kohtla-Järve, 31025 Ida-Viru County, Estonia";
            request.Origin = "veski 2, Jõhvi Parish, 41532 Ida-Viru County, Estonia";

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

            OverviewPolyline overviewPath = result.Routes.First().OverviewPath;

            OverviewPolyline polyline = result.Routes.First().Legs.First().Steps.First().PolyLine;

            Assert.AreEqual(DirectionsStatusCodes.OK, result.Status);
            Assert.AreEqual(86, overviewPath.Points.Count());
            Assert.AreEqual(13, polyline.Points.Count());
        }
コード例 #7
0
        public void Directions_VerifysubSteps()
        {
            var request = new DirectionsRequest
            {
                Origin = "King's Cross station, Euston Road, London",
                Destination = "Lukin St, London",
                TravelMode = TravelMode.Transit,
                DepartureTime = new DateTime(2014, 02, 11, 14, 00, 00)
            };

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

            var substeps = result.Routes.First().Legs.First().Steps.First().SubSteps;

            Assert.NotNull(substeps);
        }
コード例 #8
0
        public void HandleMessage(ExampleMessage exampleMessage)
        {
            var directionRequest = new DirectionsRequest()
            {
                Origin = "607 clear spring ln. leander tx 78641",
                Destination = exampleMessage.BodyText //TODO: JSON Deserialization? Common message format? Unsure here
            };

            var directions = GoogleMapsApi.GoogleMaps.Directions.Query(directionRequest);

            var testFile = File.CreateText(Directory.GetCurrentDirectory() + "\\Kbb.txt");
            foreach (var step in directions?.Routes?.FirstOrDefault()?.Legs?.FirstOrDefault()?.Steps)
            {
                testFile.WriteLine(step.HtmlInstructions);
            }
            testFile.Close();
        }
コード例 #9
0
        //
        // GET: /Plan/
        public ActionResult Index()
        {
            string[] listCities = new string[] { "Ho Chi Minh", "Bac Ninh", "Hanoi", "Da Nang" };

            int SIZE = listCities.Length;

            List<int> distances = new List<int>();

            for (int i = 0; i < SIZE - 1; i++)
            {
                for (int j = i + 1; j < SIZE; j++)
                {
                    // Transit directions
                    var transitDirectionRequest = new DirectionsRequest
                    {
                        Origin = listCities[i] + " City, Vietnam",
                        Destination = listCities[j] + " City, Vietnam",
                        TravelMode = TravelMode.Driving,
                        OptimizeWaypoints = true
                    };

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

                    distances.Add(transitDirections.Routes.First().Legs.First().Distance.Value);
                }
            }

            int[,] cities = new int[SIZE, SIZE];

            int d = 0;
            for (int i = 0; i < SIZE - 1; i++)
            {
                for (int j = i + 1; j < SIZE; j++)
                {
                    cities[i, j] = distances[d];
                    cities[j, i] = distances[d];
                    d++;
                }
            }

            var oderedVisit = TSPAlgorithm.GTS(cities, SIZE);

            int x = 9;

            return View();
        }
コード例 #10
0
ファイル: MapRoute.cs プロジェクト: adrianj/GoogleContactsMap
        public void CalculateRoute(Contacts.ContactList contacts)
        {
            Distance = 0;
            contacts = FilterEmptyNames(contacts);
            MapURL = CreateURL(contacts);

            if (contacts.Count == 0)
                return;

            NamesVisited.Clear();
            foreach (Contacts.Contact con in contacts)
                NamesVisited.Add(con.Name);

            DirectionsRequest req = new DirectionsRequest();
            req.Origin = contacts[0].Address;
            req.Destination = contacts[contacts.Count - 1].Address;

            if (contacts.Count > 2)
            {
                List<string> waypoints = new List<string>();
                for (int i = 1; i < contacts.Count - 1; i++)
                {
                    waypoints.Add(contacts[i].Address);
                }
                req.Waypoints = waypoints.ToArray();
            }
            double dist = 0;
            List<Location> locations = new List<Location>();

            DirectionsResponse resp = GoogleMapsApi.MapsAPI.GetDirections(req);

            foreach (Route r in resp.Routes)
            {
                foreach (Leg l in r.Legs)
                {
                    locations.Add(l.StartLocation);
                    locations.Add(l.EndLocation);
                    dist += l.Distance.Value;
                }

            }
            Distance = dist / 1000;
        }
コード例 #11
0
 private static async Task<Route> CallGoogleService(Location origin, DirectionsRequest request, Location destination)
 {
     var count = 0;
     while (count < 3)
     {
         try
         {
             var result = await GoogleMaps.Directions.QueryAsync(request);
             if (result.Status == DirectionsStatusCodes.OK)
             {
                 return MapRoute(origin, destination, result);
             }
         }
         catch (Exception exception)
         {
             Console.WriteLine("Error while contacting the google service: " + exception.ToString());
         }
         count ++;
     }
     throw new InvalidOperationException("Could not contact the Google service after 3 times.");
 }
コード例 #12
0
ファイル: DirectionsTests.cs プロジェクト: maximn/google-maps
        public void Directions_VerifysubSteps()
        {
            var request = new DirectionsRequest
            {
                Origin = "75 9th Ave, New York, NY",
                Destination = "MetLife Stadium Dr East Rutherford, NJ 07073",
                TravelMode = TravelMode.Driving
            };

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

            var route = result.Routes.First();
            var leg = route.Legs.First();
            var step = leg.Steps.First();

            Assert.NotNull(step);
        }
コード例 #13
0
ファイル: Trip.cs プロジェクト: gotcreme/HotCar
        public void CreateDirectionsResponse()
        {
            Location[] locations = new Location[this.RouteLocations.Count];
            for (int a = 0; a < locations.Length; a++)
            {
                locations[a] = new Location(this.RouteLocations[a].Latitude, this.RouteLocations[a].Longitude);
            }

            String[] wayPoints = new String[locations.Length - 2];
            for (int a = 1; a < locations.Length - 1; a++)
            {
                wayPoints[a - 1] = locations[a].LocationString;
            }

            DirectionsRequest directionsRequest = new DirectionsRequest()
            {
                Origin = locations[0].LocationString,
                Destination = locations[locations.Length - 1].LocationString,
                Waypoints = wayPoints,
                TravelMode = TravelMode.Driving,
                ApiKey = ConfigurationManager.AppSettings["GoogleMapsAPIKey"]
            };

            this.DirectionsResponse = GoogleMapsApi.GoogleMaps.Directions.Query(directionsRequest);
        }
コード例 #14
0
ファイル: Trip.cs プロジェクト: gotcreme/HotCar
        public bool IsOnRoute(String from, String to, double tolerance)
        {
            if (this.DirectionsResponse == null)
            {
                this.CreateDirectionsResponse();
            }

            Location[] locations = this.DecodePolyline(this.DirectionsResponse.Routes.ElementAt(0).OverviewPath.GetRawPointsData());

            DirectionsRequest startRequest = new DirectionsRequest()
            {
                Origin = from,
                Destination = locations[locations.Length - 1].LocationString,
                ApiKey = ConfigurationManager.AppSettings["GoogleMapsAPIKey"]
            };

            DirectionsRequest endRequest = new DirectionsRequest()
            {
                Origin = to,
                Destination = locations[locations.Length - 1].LocationString,
                ApiKey = ConfigurationManager.AppSettings["GoogleMapsAPIKey"]
            };

            DirectionsResponse startResponse = GoogleMapsApi.GoogleMaps.Directions.Query(startRequest);

            DirectionsResponse endResponse = GoogleMapsApi.GoogleMaps.Directions.Query(endRequest);

            double distanceStart = this.GetDistance(startResponse);
            double distanceEnd = this.GetDistance(endResponse);

            if ((distanceStart > distanceEnd) && this.IsLocationOnEdge(locations, from, to, tolerance))
            {
                return true;
            }

            return false;

            return true;
        }
コード例 #15
0
ファイル: DirectionsTests.cs プロジェクト: maximn/google-maps
        public void Directions_VerifyBounds()
        {
            var request = new DirectionsRequest
            {
                Origin = "Genk, Belgium",
                Destination = "Brussels, Belgium",
                TravelMode = TravelMode.Driving
            };

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

            var route = result.Routes.First();

            Assert.NotNull(route);
            Assert.NotNull(route.Bounds);
            Assert.Greater(route.Bounds.NorthEast.Latitude, 50);
            Assert.Greater(route.Bounds.NorthEast.Longitude, 3);
            Assert.Greater(route.Bounds.SouthWest.Latitude, 50);
            Assert.Greater(route.Bounds.SouthWest.Longitude, 3);
            Assert.Greater(route.Bounds.Center.Latitude, 50);
            Assert.Greater(route.Bounds.Center.Longitude, 3);
        }
コード例 #16
0
 public DirectionsResponse GetDirections(DirectionsRequest request)
 {
     return new DirectionsEngine().GetDirections(request);
 }
コード例 #17
0
ファイル: DirectionsTests.cs プロジェクト: maximn/google-maps
        public void Directions_WithRegionSearch()
        {
            var dep_time = DateTime.Today
                            .AddDays(1)
                            .AddHours(13);

            var request = new DirectionsRequest
            {
                Origin = "Mt Albert",
                Destination = "Parnell",
                TravelMode = TravelMode.Transit,
                DepartureTime = dep_time,
                Region = "nz"
            };

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

            Assert.IsNotEmpty(result.Routes);
            Assert.True(result.Status.Equals(DirectionsStatusCodes.OK));
        }
コード例 #18
0
        public void CreateDirectionsResponse()
        {
            List<String> wayPoints = new List<String>();
            for (int a = 1; a < this.WayPoints.Length - 1; a++)
            {
                if (!String.IsNullOrEmpty(this.WayPoints[a]) && !String.IsNullOrWhiteSpace(this.WayPoints[a]))
                    wayPoints.Add(this.WayPoints[a]);
            }

            DirectionsRequest directionsRequest = new DirectionsRequest()
            {
                Origin = this.WayPoints[0],
                Destination = this.WayPoints[this.WayPoints.Length - 1],
                Waypoints = wayPoints.ToArray(),
                TravelMode = TravelMode.Driving,
                ApiKey = WebConfigurationManager.AppSettings["GoogleMapsAPIKey"]
            };

            this.DirectionsResponse = GoogleMapsApi.GoogleMaps.Directions.Query(directionsRequest);
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: cristi-badila/google-maps
		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();
		}
コード例 #20
0
ファイル: Program.cs プロジェクト: GabrielCapano/transito-de-
        static void Main(string[] args)
        {
            //Business.SMS.Instance.SendSMS("Mensagem de teste!!", "+5511965579593");
            Console.WriteLine("Olá!! Vamos começar =)");

            Console.WriteLine("Começando pelo começo, importar o CSV? S/N");

            var csv = Console.ReadLine();

            #region importar dados
            if (csv != null && csv.ToLower() == "s")
            {
                var list = new List<Models.Lentidao>();
                var reader = new StreamReader(File.OpenRead(@"Content\Lentidao.csv"), Encoding.Default);
                reader.ReadLine();
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if (!String.IsNullOrWhiteSpace(line))
                    {
                        string[] values = line.Split(';');
                        if (values.Length >= 12)
                        {
                            list.Add(new Models.Lentidao
                            {
                                DataHora = Convert.ToDateTime(values[1]),
                                IdCorredor = Convert.ToInt32(values[2]),
                                Corredor = values[3],
                                Sentido = values[4],
                                Pista = values[5],
                                ExtensaoPista = Convert.ToInt32(values[6]),
                                InicioLentidao = values[7],
                                TerminoLentidao = values[8],
                                ReferenciaNumericaInicioLentidao = Convert.ToInt32(values[9]),
                                ExensaoLentidao = Convert.ToInt32(values[10]),
                                Regiao = values[11]
                            });
                        }
                    }
                }

                using (var context = new DatabaseContext())
                {
                    context.BulkInsert(list);
                }
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("Uffa!! Terminamos, vamos pro próximo =)");
                Console.ResetColor();
            }
            #endregion

            Console.WriteLine("Vamos fazer a query... (sem view, vai demorar)");

            using (var context = new DatabaseContext())
            {
                context.Database.Log = Console.WriteLine;
                Console.WriteLine("Inserir Lentidão Consolidada? S/N");
                var s = Console.ReadLine();

                var todos = new List<Models.LentidaoConsolidado>();
                if (s != null && s.ToLower() == "s")
                {

                    todos = context.Lentidoes
                        .GroupBy(a => new {
                            a.InicioLentidao,
                            a.TerminoLentidao,
                            a.ReferenciaNumericaInicioLentidao,
                            a.Regiao})
                        .Select(a=> new
                        {
                            Total = a.Count(),
                            TerminoLentidao = a.Key.TerminoLentidao,
                            InicioLentidao = a.Key.InicioLentidao,
                            ReferenciaNumericaInicioLentidao = a.Key.ReferenciaNumericaInicioLentidao,
                            Regiao = a.Key.Regiao
                        })
                        .OrderByDescending(a => a.Total).Skip(1).ToList().Select(a => new Models.LentidaoConsolidado
                        {
                            Total = a.Total,
                            TerminoLentidao = a.TerminoLentidao,
                            InicioLentidao = a.InicioLentidao,
                            ReferenciaNumericaInicioLentidao = a.ReferenciaNumericaInicioLentidao,
                            Regiao = a.Regiao
                        }).ToList();

                    context.BulkInsert(todos);
                }

                todos = context.LentidaoConsolidados.Where(a=>!a.Steps.Any()).ToList();

                var stps = new List<Models.Step>();

                var count = 0;
                foreach(var todo in todos)
                {

                    count++;
                    var directionsRequest = new DirectionsRequest()
                    {
                        Origin = String.Format("{0} {1}, São Paulo - SP, Brasil", TratarEndereco(todo.InicioLentidao), todo.ReferenciaNumericaInicioLentidao),
                        Destination = String.Format("{0}, São Paulo - SP, Brasil", todo.TerminoLentidao),
                        SigningKey = "AIzaSyAl8V3SnsqpCWA1SmyMH0g-PaOkfN5J5LA",
                    };

                    var directions = GoogleMaps.Directions.Query(directionsRequest);

                    if (directions.Status == DirectionsStatusCodes.OK)
                    {
                        var legs = directions.Routes.First().Legs;

                        foreach (var leg in legs)
                        {
                            if (leg.Distance.Value > 20000)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(
                                    String.Format("Xiiii, mais do que 20 quilômetros? Tá suspeito esse registro..."),
                                    new object {});
                                Console.WriteLine(todo);
                                Console.ResetColor();
                            }
                            else
                            {
                                var steps = leg.Steps;

                                stps.AddRange(steps.Select(step => new Models.Step
                                {
                                    PosicaoGeografica = DbGeography.FromText(Business.Ocorrencia.Instance.GetGeographyTextFromLatlng(step.StartLocation.Latitude, step.StartLocation.Longitude)),
                                    FkLentidaoConsolidado = todo.Id
                                }));

                                count = count + stps.Count;
                            }
                        }
                    }

                    if (count > 500)
                    {
                        if (count > 500)
                        {
                            using (var context2 = new DatabaseContext())
                            {
                                try
                                {
                                    context2.Steps.AddRange(stps.Where(a => a.PosicaoGeografica != null));
                                }
                                catch (Exception)
                                {
                                }
                                context2.SaveChanges();
                                stps = new List<Models.Step>();
                                count = 0;
                            }
                        }

                    }

                    Console.WriteLine(directions);
                };

                context.SaveChanges();

            }
        }
コード例 #21
0
ファイル: MapsAPI.cs プロジェクト: JasonBSteele/GoogleApi
		public static DirectionsResponse GetDirections(DirectionsRequest request)
		{
			return MapsAPIEngine.GetDirections(request);
		}
コード例 #22
0
ファイル: Program.cs プロジェクト: maximn/google-maps
        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();
        }
コード例 #23
0
ファイル: DirectionsTests.cs プロジェクト: maximn/google-maps
        public void Directions_WithLocalIcons()
        {
            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);

            var route = result.Routes.First();
            var leg = route.Legs.First();
            var steps = leg.Steps;

            Assert.IsNotEmpty(steps.Where(s =>
                s.TransitDetails?
                .Lines?
                .Vehicle?
                .LocalIcon != null));
        }