Exemple #1
0
        private async void Map_MapClicked(object sender, MapClickedEventArgs e)
        {
            if (CrossGeolocator.Current.IsListening)
            {
                await CrossGeolocator.Current.StopListeningAsync();
            }
            Xamarin.Forms.GoogleMaps.Polyline polyline = null;
            await Task.Run(async() =>
            {
                Plugin.Geolocator.Abstractions.Position position = await CrossGeolocator.Current.GetLastKnownLocationAsync();
                List <Location> locations = Mapmanager.GetPoint(position.Latitude, position.Longitude, e.Point.Latitude, e.Point.Longitude);
                polyline = new Xamarin.Forms.GoogleMaps.Polyline();

                foreach (var location in locations)
                {
                    polyline.Positions.Add(new Position(location.Latitude, location.Longitude));
                }
                polyline.StrokeColor = Color.Blue;
                polyline.StrokeWidth = 5f;
                map.Polylines.Clear();
                Device.BeginInvokeOnMainThread(async() =>
                {
                    map.Polylines.Add(polyline);
                });
                if (!CrossGeolocator.Current.IsListening)
                {
                    isRefreshPolylines = true;
                    await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(1), 1, true);
                }
            });
        }
        void DrawRoute(List <Xamarin.Forms.GoogleMaps.Position> list)
        {
            map.Polylines.Clear();
            var polyline = new Xamarin.Forms.GoogleMaps.Polyline();

            polyline.StrokeColor = Color.Black;
            polyline.StrokeWidth = 3;

            foreach (var p in list)
            {
                polyline.Positions.Add(p);
            }
            map.Polylines.Add(polyline);
            map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(polyline.Positions[0].Latitude, polyline.Positions[0].Longitude), Xamarin.Forms.GoogleMaps.Distance.FromMiles(0.50f)));

            var pin = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.SearchResult,
                Position = new Position(polyline.Positions.First().Latitude, polyline.Positions.First().Longitude),
                Label    = "Pin",
                Address  = "Pin",
                Tag      = "CirclePoint",
                Icon     = (Device.RuntimePlatform == Device.Android)?BitmapDescriptorFactory.FromBundle("ic_circle_point.png") :  BitmapDescriptorFactory.FromView(new Image()
                {
                    Source = "ic_circle_point.png", WidthRequest = 25, HeightRequest = 25
                })
            };

            map.Pins.Add(pin);
        }
        private void CreatePolylinesOnMap(List <Position> directionPolylines)
        {
            Xamarin.Forms.GoogleMaps.Polyline polyline = new Xamarin.Forms.GoogleMaps.Polyline()
            {
                StrokeColor = Constants.mapShapeColor,
                StrokeWidth = 8,
            };

            for (int i = 0; i < directionPolylines.Count - 1; i++)
            {
                polyline.Positions.Add(directionPolylines[i]);
            }
            map.Polylines.Add(polyline);
        }
Exemple #4
0
        async private void updateRoute()
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en");

            HttpClient c = new HttpClient();

            string url = $"http://maps.googleapis.com/maps/api/directions/json?origin={voce.Position.Latitude},{voce.Position.Longitude}&destination={destino.Position.Latitude},{destino.Position.Longitude}&mode=walking";

            try
            {
                HttpResponseMessage response =
                    await c.GetAsync(url);

                var resp = JsonConvert.DeserializeObject <RouteObject>(await response.Content.ReadAsStringAsync());

                Xamarin.Forms.GoogleMaps.Polyline polyline = new Xamarin.Forms.GoogleMaps.Polyline();

                int distancia = 0;

                polyline.Positions.Add(new Position(voce.Position.Latitude, voce.Position.Longitude));

                if (resp.routes != null && resp.routes.Count > 0)
                {
                    foreach (var route in resp.routes[0].legs[0].steps)
                    {
                        polyline.Positions.Add(new Position(route.start_location.lat, route.start_location.lng));
                        polyline.Positions.Add(new Position(route.end_location.lat, route.end_location.lng));
                        distancia += route.distance.value;
                    }
                }

                polyline.Positions.Add(new Position(destino.Position.Latitude, destino.Position.Longitude));

                lblDistance.Text = $"Distância Entre Você e o Destino {distancia} metros";

                polyline.StrokeColor = Color.Aqua;
                polyline.StrokeWidth = 10f;

                map.Polylines.Clear();

                map.Polylines.Add(polyline);
            }
            catch (Exception e)
            {
                await DisplayAlert("Erro", e.Message, "OK");
            }

            updatePins();
        }
        void CalculateDistance(List <Xamarin.Forms.GoogleMaps.Position> list)
        {
            map.Polylines.Clear();
            var polyline = new Xamarin.Forms.GoogleMaps.Polyline();

            foreach (var p in list)
            {
                polyline.Positions.Add(p);
            }
            map.Polylines.Add(polyline);
            var position = new Position(polyline.Positions[0].Latitude, polyline.Positions[0].Longitude);

            map.MoveToRegion(MapSpan.FromCenterAndRadius(position, Xamarin.Forms.GoogleMaps.Distance.FromMiles(0.50f)));

            var pin = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.Place,
                Position = new Position(polyline.Positions.First().Latitude, polyline.Positions.First().Longitude),
                Label    = "Start and ",
                Address  = "running",
                Tag      = string.Empty,
                Icon     = (Device.RuntimePlatform == Device.iOS) ? BitmapDescriptorFactory.FromView(new Image()
                {
                    Source        = "car.png",
                    WidthRequest  = 25,
                    HeightRequest = 25
                }) : BitmapDescriptorFactory.DefaultMarker(Color.Purple)
            };

            map.Pins.Add(pin);
            var pin1 = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.Place,
                Position = new Position(polyline.Positions.Last().Latitude, polyline.Positions.Last().Longitude),
                Label    = "Target",
                Address  = "Place",
                Tag      = string.Empty
            };

            map.Pins.Add(pin1);
        }
Exemple #6
0
        private async void DrawRoute()
        {
            SetOneDirection();
            if (Start != null && End != null && Start != End)
            {
                Device.BeginInvokeOnMainThread(() => IsBusyOnMap = true);
                //IsBusy = true;
                var direction = await googleMapsApi.GetDirections(
                    Start.StringLat(), Start.StringLng(),
                    End.StringLat(), End.StringLng());

                if (direction.Success)
                {
                    plottedRoutes.Clear();
                    Map.Polylines.Clear();
                    ShowMeMyCameraUpdate(direction.Routes[0].Bounds);
                    Leg[] legs = null;
                    for (int index = 0; index < direction.Routes.Length; index++)
                    {
                        var route = direction.Routes[index];
                        legs = direction.Routes[0].Legs;
                        Polyline polyLineData = new Polyline
                        {
                            StrokeWidth = 5,
                            StrokeColor = Color.FromRgb(118, 170, 219)
                        };
                        foreach (var coord in route.OverviewPolylineCoords)
                        {
                            polyLineData.Positions.Add(new Position(coord.Lat, coord.Lng));
                        }
                        Map.Polylines.Add(polyLineData);
                        plottedRoutes.Add(polyLineData);
                    }
                    //FOR DISTANCE
                    ServiceInfo(legs[0]);
                }
                Device.BeginInvokeOnMainThread(() => IsBusyOnMap = false);
                //IsBusy = false;
            }
            ;
        }
        private void drawPolylines(GoogleRoute route)
        {
            Position start = viewModel.currentEvent.startPos, end = viewModel.currentEvent.endPos;
            var      polyLine = new Xamarin.Forms.GoogleMaps.Polyline();

            polyLine.StrokeColor = Color.Orange;
            polyLine.StrokeWidth = 10f;
            polyLine.Positions.Add(start);
            foreach (Step step in route.legs[0].steps)
            {
                string polyStr = step.polyline.points;
                List <Xamarin.Essentials.Location> polyPoints = Configs.DecodePolylinePoints(polyStr);
                foreach (var loc in polyPoints)
                {
                    polyLine.Positions.Add(new Position(loc.Latitude, loc.Longitude));
                }
            }
            polyLine.Positions.Add(end);
            Thread.Sleep(500);
            EventDetailMap.Polylines.Add(polyLine);
        }
        private async void TrackPath_Clicked(object sender, EventArgs e)
        {
            /* ////this code not work for that we test with a file json
             * HttpClient c;
             * c = new HttpClient();
             *
             * int id0;
             * var id = await SecureStorage.GetAsync("id_Mis");
             *
             * id0 = Convert.ToInt32(id);
             * String trackPathFile;
             * HttpResponseMessage r = await c.GetAsync("http://192.168.0.134/webApi/api/values/Geolocalisation/id=" + id0);
             *
             * trackPathFile = r.Content.ReadAsStringAsync().Result; */
            var    assembly = typeof(view.Maps).GetTypeInfo().Assembly;
            var    stream   = assembly.GetManifestResourceStream($"App3.MapResources.TrackPath.json");
            string trackPathFile;

            using (var reader = new System.IO.StreamReader(stream))
            {
                trackPathFile = reader.ReadToEnd();
            }
            var myJson = JsonConvert.DeserializeObject <List <Xamarin.Forms.GoogleMaps.Position> >(trackPathFile);


            map.Polylines.Clear();

            var polyline = new Xamarin.Forms.GoogleMaps.Polyline();

            polyline.StrokeColor = Color.Black;
            polyline.StrokeWidth = 3;

            foreach (var p in myJson)
            {
                polyline.Positions.Add(p);
            }
            map.Polylines.Add(polyline);

            map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.GoogleMaps.Position(polyline.Positions[0].Latitude, polyline.Positions[0].Longitude), Xamarin.Forms.GoogleMaps.Distance.FromMiles(0.50f)));
        }
Exemple #9
0
        async void DrawRoute(Position start, Position end)
        {
            GoogleDirection googleDirection = await googleMapsApi.GetDirections(start.Latitude + "", start.Longitude + "",
                                                                                end.Latitude + "", end.Longitude + "");

            if (googleDirection.Routes != null && googleDirection.Routes.Count > 0)
            {
                var positions = (Enumerable.ToList(PolylineHelper.Decode(googleDirection.Routes.First().OverviewPolyline.Points)));
                map.Polylines.Clear();
                var polyline = new Xamarin.Forms.GoogleMaps.Polyline();
                polyline.StrokeColor = Color.Black;
                polyline.StrokeWidth = 3;
                foreach (var p in positions)
                {
                    polyline.Positions.Add(p);
                }
                map.Polylines.Add(polyline);
                map.MoveToRegion(MapSpan.FromBounds(new Xamarin.Forms.GoogleMaps.Bounds(new Position(polyline.Positions[0].Latitude,
                                                                                                     polyline.Positions[0].Longitude - 0.008), new Position(polyline.Positions[polyline.Positions.Count - 1].Latitude,
                                                                                                                                                            polyline.Positions[polyline.Positions.Count - 1].Longitude + 0.008))), true);
            }
        }
Exemple #10
0
        void Calculate(List <Xamarin.Forms.GoogleMaps.Position> list)
        {
            searchLayout.IsVisible    = false;
            stopRouteButton.IsVisible = true;
            map.Polylines.Clear();
            var polyline = new Xamarin.Forms.GoogleMaps.Polyline();

            foreach (var p in list)
            {
                polyline.Positions.Add(p);
            }
            map.Polylines.Add(polyline);
            map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(polyline.Positions[0].Latitude, polyline.Positions[0].Longitude), Xamarin.Forms.GoogleMaps.Distance.FromMiles(0.50f)));

            var pin = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.Place,
                Position = new Position(polyline.Positions.First().Latitude, polyline.Positions.First().Longitude),
                Label    = "First",
                Address  = "First",
                Tag      = string.Empty,
                Icon     = BitmapDescriptorFactory.FromView(new Image()
                {
                    Source = "ic_taxi.png", WidthRequest = 25, HeightRequest = 25
                })
            };

            map.Pins.Add(pin);
            var pin1 = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.Place,
                Position = new Position(polyline.Positions.Last().Latitude, polyline.Positions.Last().Longitude),
                Label    = "Last",
                Address  = "Last",
                Tag      = string.Empty
            };

            map.Pins.Add(pin1);
        }
Exemple #11
0
        void Calculate(List <Xamarin.Forms.GoogleMaps.Position> list)
        {
            OnCalculate?.Invoke(this, default(EventArgs));
            Polylines.Clear();
            var polyline = new Xamarin.Forms.GoogleMaps.Polyline();

            foreach (var p in list)
            {
                polyline.Positions.Add(p);
            }
            Polylines.Add(polyline);
            MoveToRegion(MapSpan.FromCenterAndRadius(new Position(polyline.Positions[0].Latitude, polyline.Positions[0].Longitude), Xamarin.Forms.GoogleMaps.Distance.FromMiles(0.50f)));

            var pin = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.Place,
                Position = new Position(polyline.Positions.First().Latitude, polyline.Positions.First().Longitude),
                Label    = "First",
                Address  = "First",
                Tag      = string.Empty,
                Icon     = (Device.RuntimePlatform == Device.Android) ? BitmapDescriptorFactory.FromBundle("ic_taxi.png") : BitmapDescriptorFactory.FromView(new Image()
                {
                    Source = "ic_taxi.png", WidthRequest = 25, HeightRequest = 25
                })
            };

            Pins.Add(pin);
            var pin1 = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.Place,
                Position = new Position(polyline.Positions.Last().Latitude, polyline.Positions.Last().Longitude),
                Label    = "Last",
                Address  = "Last",
                Tag      = string.Empty
            };

            Pins.Add(pin1);
        }
        void TrackPath_Clicked(string trackPathFile)
        {
            //var assembly = typeof(MainPage).GetTypeInfo().Assembly;

            var myJson = JsonConvert.DeserializeObject <List <Xamarin.Forms.GoogleMaps.Position> >(trackPathFile);

            map.Polylines.Clear();

            var polyline = new Xamarin.Forms.GoogleMaps.Polyline();

            polyline.StrokeColor = Color.Black;
            polyline.StrokeWidth = 3;

            foreach (var p in myJson)
            {
                polyline.Positions.Add(p);
            }
            map.Polylines.Add(polyline);



            map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.GoogleMaps.Position(polyline.Positions[0].Latitude, polyline.Positions[0].Longitude), Xamarin.Forms.GoogleMaps.Distance.FromMiles(0.50f)));
        }
Exemple #13
0
        public static void SetRoutes(Xamarin.Forms.GoogleMaps.Map map, GoogleDirections googleDirections)
        {
            if (googleDirections.routes.Count > 0)
            {
                string encodedPoints = googleDirections.routes[0].overview_polyline.points;

                var lstDecodedPoints = GetPolylinePoints(encodedPoints);
                var latLngPoints     = new Position[lstDecodedPoints.Count];
                int index            = 0;

                var polylineoption = new Xamarin.Forms.GoogleMaps.Polyline();
                polylineoption.StrokeColor = Xamarin.Forms.Color.Red;

                foreach (Location loc in lstDecodedPoints)
                {
                    latLngPoints[index++] = new Position(loc.Latitude, loc.Longitude);
                    polylineoption.Positions.Add(new Position(loc.Latitude, loc.Longitude));
                }

                map.Polylines.Add(polylineoption);

                UpdateCamera(map, latLngPoints[0]);
            }
        }
Exemple #14
0
        private void CreatePolylinesOnMap(List <Position> directionPolylines)
        {
            try {
                Xamarin.Forms.GoogleMaps.Polyline polyline = new Xamarin.Forms.GoogleMaps.Polyline()
                {
                    StrokeColor = Constants.mapShapeColor,
                    StrokeWidth = 8,
                };

                for (int i = 0; i < directionPolylines.Count; i++)
                {
                    polyline.Positions.Add(directionPolylines[i]);
                }

                if (polyline.Positions.Count == 0)
                {
                    return;
                }
                map.Polylines.Add(polyline);
            } catch
            {
                Console.WriteLine("Error in polyline");
            }
        }
        async Task <bool> CalculateRoute()
        {
            buttonGrid.IsVisible = false;
            map.Polylines.Clear();
            RouteReset();
            var line1 = new Xamarin.Forms.GoogleMaps.Polyline();
            var line2 = new Xamarin.Forms.GoogleMaps.Polyline();

            fastest              = new Xamarin.Forms.GoogleMaps.Polyline();
            cleanest             = new Xamarin.Forms.GoogleMaps.Polyline();
            fastest.StrokeColor  = Color.Blue;
            fastest.StrokeWidth  = 7;
            cleanest.StrokeColor = Color.FromHex("00e36f");
            cleanest.StrokeWidth = 4;

            line1.StrokeColor = Color.Blue;
            line1.StrokeWidth = 7;
            line2.StrokeColor = Color.FromHex("00e36f");
            line2.StrokeWidth = 4;

            string originParam      = originPos.Latitude.ToString() + ',' + originPos.Longitude.ToString();
            string destinationParam = destinationPos.Latitude.ToString() + ',' + destinationPos.Longitude.ToString();

            line1.Positions.Clear();
            line2.Positions.Clear();
            fastest.Positions.Clear();
            cleanest.Positions.Clear();

            maxTime          = 0;
            fastestDistance  = 0;
            cleanestDistance = 0;
            fastestPollution = 0;
            cleanestTime     = 0;
            maxPollution     = 0;

            if (!string.IsNullOrEmpty(originParam) && !string.IsNullOrEmpty(destinationParam) && isHomeSet > 0 && isDestinationSet > 0)
            {
                Bounds bounds = new Bounds(originPos, destinationPos);
                map.MoveToRegion(MapSpan.FromBounds(bounds));
                blueDistanceLabel.Text    = "";
                magentaDistanceLabel.Text = "";

                await GetHeatMap(bounds);

                var mqResult = await rest.GetMQAlternativeDirection(originParam, destinationParam, mqModes[mode]);

                List <Position> pollutionPoints = new List <Position>();

                bool isRouteChosen = false;
                if (mqResult != null)
                {
                    if (mqResult.route != null)
                    {
                        if (mqResult.route.shape != null)
                        {
                            fastest.Positions.Clear();
                            cleanest.Positions.Clear();
                            if (!string.IsNullOrEmpty(mqResult.route.shape.shapePoints))
                            {
                                var points = DecodePolyline(mqResult.route.shape.shapePoints);
                                foreach (var point in points)
                                {
                                    fastest.Positions.Add(point);
                                    cleanest.Positions.Add(point);
                                    pollutionPoints.Add(point);
                                }
                                maxPollution = await CalculatePollution(pollutionPoints, true);

                                fastestPollution = maxPollution;
                                maxTime          = mqResult.route.time;
                                cleanestTime     = mqResult.route.time;
                                fastestDistance  = mqResult.route.distance;
                                cleanestDistance = mqResult.route.distance;
                            }
                        }
                    }
                    MQDirection fastestRoute  = new MQDirection();
                    MQDirection cleanestRoute = new MQDirection();

                    if (mqResult.route.alternateRoutes != null)
                    {
                        if (mqResult.route.alternateRoutes.Count > 0)
                        {
                            bool duplicated = false;
                            map.Polylines.Clear();
                            fastestRoute  = mqResult.route.alternateRoutes[0];
                            cleanestRoute = mqResult.route.alternateRoutes[0];
                            foreach (var item in mqResult.route.alternateRoutes)
                            {
                                line1.Positions.Clear();
                                line2.Positions.Clear();
                                pollutionPoints.Clear();
                                if (item.route.shape != null)
                                {
                                    if (!string.IsNullOrEmpty(item.route.shape.shapePoints))
                                    {
                                        var points = DecodePolyline(item.route.shape.shapePoints);
                                        foreach (var point in points)
                                        {
                                            line1.Positions.Add(point);
                                            line2.Positions.Add(point);
                                            pollutionPoints.Add(point);
                                            if (point.Latitude.Equals(hotspot.Latitude) && point.Longitude.Equals(hotspot.Longitude))
                                            {
                                                duplicated = true;
                                                break;
                                            }
                                        }
                                        if (!duplicated)
                                        {
                                            float pollutionValue = await CalculatePollution(pollutionPoints, true);

                                            if (item.route.time < maxTime)
                                            {
                                                fastest          = line1;
                                                fastestRoute     = item;
                                                maxTime          = item.route.time;
                                                fastestPollution = pollutionValue;
                                                fastestDistance  = item.route.distance;
                                                isRouteChosen    = true;
                                            }
                                            else if (pollutionValue < maxPollution)
                                            {
                                                cleanest         = line2;
                                                cleanestRoute    = item;
                                                maxPollution     = pollutionValue;
                                                cleanestTime     = item.route.time;
                                                cleanestDistance = item.route.distance;
                                                isRouteChosen    = true;
                                            }
                                        }
                                    }
                                }
                            }
                            if (isRouteChosen && fastestPollution > maxPollution)
                            {
                                map.Polylines.Clear();

                                if (fastest.Positions.Count >= 2)
                                {
                                    map.Polylines.Add(fastest);
                                }
                                if (cleanest.Positions.Count >= 2)
                                {
                                    map.Polylines.Add(cleanest);
                                }

                                blueDistanceLabel.Text    = $"{fastestDistance.ToString("F1")} miles {timeToMin(maxTime)} Pollution: {(int)fastestPollution}";
                                magentaDistanceLabel.Text = $"{cleanestDistance.ToString("F1")} miles {timeToMin(cleanestTime)} Pollution: {(int)maxPollution}";
                                buttonGrid.IsVisible      = true;
                                drawHotspot();
                                return(true);
                            }
                        }
                    }

                    buttonGrid.IsVisible = false;
                    map.Polylines.Clear();
                    Device.StartTimer(TimeSpan.FromMilliseconds(3000), () =>
                    {
                        if (fastest.Positions.Count >= 2)
                        {
                            fastest.StrokeColor = Color.FromHex("00e36f");
                            map.Polylines.Add(fastest);
                        }

                        magentaDistanceLabel.Text         = $"{mqResult.route.distance.ToString("F1")} miles {timeToMin(mqResult.route.time)} Pollution: {(int)fastestPollution}";
                        blueDistanceLabel.BackgroundColor = Color.Gray;
                        blueDistanceLabel.Text            = "No faster route available.";
                        drawHotspot();
                        return(false);
                    });
                }
            }
            else
            {
                await DisplayAlert("Warning", "Please fill all the fields", "OK");
            }
            return(false);
        }
        async Task <bool> CalculateRoute()
        {
            map.Polylines.Clear();
            var line1 = new Xamarin.Forms.GoogleMaps.Polyline();

            line1.StrokeColor = Color.Blue;
            line1.StrokeWidth = 7;
            var line2 = new Xamarin.Forms.GoogleMaps.Polyline();

            line2.StrokeColor = Color.Magenta;
            line2.StrokeWidth = 4;

            string originParam      = originPos.Latitude.ToString() + ',' + originPos.Longitude.ToString();
            string destinationParam = destinationPos.Latitude.ToString() + ',' + destinationPos.Longitude.ToString();

            if (isHomeSet == 1)
            {
                originParam = origin;
            }

            if (isDestinationSet == 1)
            {
                destinationParam = destination;
            }

            Bounds bounds = new Bounds(originPos, destinationPos);

            map.MoveToRegion(MapSpan.FromBounds(bounds));
            if (!string.IsNullOrEmpty(originParam) && !string.IsNullOrEmpty(destinationParam) && isHomeSet > 0 && isDestinationSet > 0)
            {
                //var distanceResult = await rest.GetDistance(originParam, destinationParam, modes[mode]);
                //if (distanceResult != null)
                //{
                //    if (distanceResult.rows[0].elements[0].distance != null)
                //    {
                //        string distance = distanceResult.rows[0].elements[0].distance.text;
                //        string duration = distanceResult.rows[0].elements[0].duration.text;
                //        distanceLabel.Text = $"Red Distance={distance}, Duration={duration}";
                //    }
                //}

                //var result = await rest.GetDirection(originParam, destinationParam, modes[mode]);

                //if (result != null)
                //{
                //    var line = new Xamarin.Forms.GoogleMaps.Polyline();
                //    line.StrokeColor = Color.Red;
                //    line.StrokeWidth = 10;
                //    foreach (var route in result.routes)
                //    {
                //        foreach (var leg in route.legs)
                //        {
                //            foreach (var step in leg.steps)
                //            {
                //                var points = DecodePolyline(step.polyline.points);
                //                foreach (var point in points)
                //                {
                //                    line.Positions.Add(point);
                //                }
                //            }
                //        }
                //    }
                //    if (line.Positions.Count >= 2)
                //        map.Polylines.Add(line);
                //}

                var mqResult = await rest.GetMQAlternativeDirection(originParam, destinationParam, mqModes[mode]);

                List <Position> pollutionPoints = new List <Position>();

                if (mqResult != null)
                {
                    if (mqResult.route != null)
                    {
                        if (mqResult.route.shape != null)
                        {
                            if (!string.IsNullOrEmpty(mqResult.route.shape.shapePoints))
                            {
                                var points = DecodePolyline(mqResult.route.shape.shapePoints);
                                foreach (var point in points)
                                {
                                    line1.Positions.Add(point);
                                    pollutionPoints.Add(point);
                                }

                                if (line1.Positions.Count >= 2)
                                {
                                    map.Polylines.Add(line1);
                                }
                                maxPollution = await CalculatePollution(pollutionPoints, true);

                                drawHotspot();
                            }
                        }
                    }

                    if (mqResult.route.alternateRoutes != null)
                    {
                        bool duplicated = false;
                        foreach (var item in mqResult.route.alternateRoutes)
                        {
                            line2.Positions.Clear();
                            pollutionPoints.Clear();
                            if (item.route.shape != null)
                            {
                                if (!string.IsNullOrEmpty(item.route.shape.shapePoints))
                                {
                                    var points = DecodePolyline(item.route.shape.shapePoints);
                                    foreach (var point in points)
                                    {
                                        line2.Positions.Add(point);
                                        pollutionPoints.Add(point);
                                        if (point.Latitude.Equals(hotspot.Latitude) && point.Longitude.Equals(hotspot.Longitude))
                                        {
                                            duplicated = true;
                                            break;
                                        }
                                    }
                                    if (!duplicated)
                                    {
                                        float pollutionValue = await CalculatePollution(pollutionPoints, true);

                                        if (pollutionValue > maxPollution)
                                        {
                                            continue;
                                        }
                                        else
                                        {
                                            if (line2.Positions.Count >= 2)
                                            {
                                                map.Polylines.Add(line2);
                                            }
                                            drawHotspot();
                                            return(true);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                await this.DisplayAlert("Warning", "Please fill all the fields", "OK");
            }
            return(false);
        }
Exemple #17
0
        async void Calculate(List <Xamarin.Forms.GoogleMaps.Position> list)
        {
            searchLayout.IsVisible    = true;
            stopRouteButton.IsVisible = false;
            Chamada.IsVisible         = true;

            map.Polylines.Clear();
            var polyline = new Xamarin.Forms.GoogleMaps.Polyline();


            polyline.StrokeColor = Color.Green;

            polyline.StrokeWidth = (float)5;



            foreach (var p in list)
            {
                polyline.Positions.Add(p);
            }
            map.Polylines.Add(polyline);


            var pin = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.Place,
                Position = new Xamarin.Forms.GoogleMaps.Position(polyline.Positions.First().Latitude, polyline.Positions.First().Longitude),
                Label    = "First",
                Address  = "First",
                Tag      = string.Empty,
                Icon     = BitmapDescriptorFactory.FromView(new Image()
                {
                    Source = "ic_taxi.png", WidthRequest = 25, HeightRequest = 25
                })
            };

            map.Pins.Add(pin);

            var pin1 = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.Place,
                Position = new Xamarin.Forms.GoogleMaps.Position(polyline.Positions.Last().Latitude, polyline.Positions.Last().Longitude),
                Label    = "Last",
                Address  = "Last",
                Tag      = string.Empty
            };

            map.Pins.Add(pin1);



            //var medio = polyline.Positions.Count/ 2;


            //var pinmedio = new Xamarin.Forms.GoogleMaps.Pin
            //{
            //Type = PinType.Place,

            //Position = new Position(polyline.Positions[medio].Latitude, polyline.Positions[medio].Longitude),

            //Label = "Medio",
            //Address = "Medio",
            //Tag = string.Empty,

            //};

            //map.Pins.Add(pinmedio);



            inicio = pin.Position;

            fim = pin1.Position;

            map.MoveToRegion(MapSpan.FromPositions(list).WithZoom(0.85));

            await StartListening();
        }
        void Calculate(List <Xamarin.Forms.GoogleMaps.Position> list)
        {
            mapn.Polylines.Clear();
            var polygon = new Xamarin.Forms.GoogleMaps.Polygon();

            polygon.Positions.Add(new Position(41.1389019841448d, -8.61560349288011d));
            polygon.Positions.Add(new Position(41.1434744495776d, -8.67074812896517d));
            polygon.Positions.Add(new Position(41.1449838609599d, -8.67905202242122d));
            polygon.Positions.Add(new Position(41.1451299199957d, -8.67927438576518d));
            polygon.Positions.Add(new Position(41.1667491884192d, -8.69051961393614d));
            polygon.Positions.Add(new Position(41.1687515832633d, -8.69128901091482d));
            polygon.Positions.Add(new Position(41.1687718202548d, -8.69129406942044d));
            polygon.Positions.Add(new Position(41.1733985483824d, -8.6901233398917d));
            polygon.Positions.Add(new Position(41.1791950462077d, -8.66638025932549d));
            polygon.Positions.Add(new Position(41.1843186499419d, -8.64263275539779d));
            polygon.Positions.Add(new Position(41.1859199810206d, -8.60475022412726d));
            polygon.Positions.Add(new Position(41.1859353051989d, -8.60415557268555d));
            polygon.Positions.Add(new Position(41.1858564905415d, -8.60352615847566d));
            polygon.Positions.Add(new Position(41.1809534888858d, -8.57618203495341d));
            polygon.Positions.Add(new Position(41.1808879776888d, -8.57596086663742d));
            polygon.Positions.Add(new Position(41.1782338392238d, -8.56918812805673d));
            polygon.Positions.Add(new Position(41.1781107344154d, -8.5690029395442d));
            polygon.Positions.Add(new Position(41.1778608190979d, -8.56863743584061d));
            polygon.Positions.Add(new Position(41.1776820677363d, -8.56838121049044d));
            polygon.Positions.Add(new Position(41.1772845426276d, -8.56783274898752d));
            polygon.Positions.Add(new Position(41.1761404097255d, -8.56630188826643d));
            polygon.Positions.Add(new Position(41.1760550093552d, -8.56619263815834d));
            polygon.Positions.Add(new Position(41.1759695143603d, -8.56610877045314d));
            polygon.Positions.Add(new Position(41.1600578943756d, -8.55337925107515d));
            polygon.Positions.Add(new Position(41.158207085713d, -8.55261345505833d));
            polygon.Positions.Add(new Position(41.1532077014578d, -8.55473745611279d));
            polygon.Positions.Add(new Position(41.1529458174769d, -8.55494508426352d));
            polygon.Positions.Add(new Position(41.1463677636723d, -8.56368877972558d));
            polygon.Positions.Add(new Position(41.1399578511665d, -8.57576315330342d));
            polygon.Positions.Add(new Position(41.1383506797128d, -8.59418349674972d));

            polygon.IsClickable = true;
            polygon.StrokeColor = Color.Black;
            polygon.StrokeWidth = 3f;
            polygon.FillColor   = Color.FromRgba(255, 0, 0, 64);
            polygon.Tag         = "POLYGON";

            mapn.Polygons.Add(polygon);

            var polyline = new Xamarin.Forms.GoogleMaps.Polyline();

            polyline.StrokeColor = Color.Blue;
            polyline.StrokeWidth = polyline.StrokeWidth * 4;
            var polylineinside = new Xamarin.Forms.GoogleMaps.Polyline();

            polylineinside.StrokeColor = Color.Red;
            polylineinside.StrokeWidth = polyline.StrokeWidth * 2;

            foreach (var p in list)
            {
                polyline.Positions.Add(p);
                if (Contains(p, polygon))
                {
                    // point is inside polygon
                    polylineinside.Positions.Add(p);
                }
            }
            mapn.Polylines.Add(polyline);
            if (polylineinside.Positions.Count > 2)
            {
                mapn.Polylines.Add(polylineinside);
            }

            var pin = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.Place,
                Position = new Position(polyline.Positions.First().Latitude, polyline.Positions.First().Longitude),
                Label    = vm.startLabel,
                Address  = vm.startAdd,
                Tag      = "First Point",
                Icon     = BitmapDescriptorFactory.FromView(new Image()
                {
                    Source = "ic_location.png", WidthRequest = 25, HeightRequest = 25
                })
            };

            mapn.Pins.Add(pin);
            var pin1 = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.Place,
                Position = new Position(polyline.Positions.Last().Latitude, polyline.Positions.Last().Longitude),
                Label    = vm.endLabel,
                Address  = vm.endAdd,
                Tag      = "Last Point",
                Icon     = BitmapDescriptorFactory.FromView(new Image()
                {
                    Source = "ic_location_red.png", WidthRequest = 25, HeightRequest = 25
                })
            };

            mapn.Pins.Add(pin1);
            int innerDist = 0;

            if (polylineinside.Positions.Count > 2)
            {
                var googleDirection = (vm.GetDistance(polylineinside.Positions.First(), polylineinside.Positions.Last()).Result);

                if (googleDirection.Routes != null && googleDirection.Routes.Count > 0)
                {
                    innerDist = googleDirection.Routes.FirstOrDefault().Legs.FirstOrDefault().Distance.Value;
                }
            }
            int     totalDist         = vm.CurrentGoogleDirection.Routes.FirstOrDefault().Legs.FirstOrDefault().Distance.Value;
            decimal totalfare         = 0;
            decimal distanceunit      = 0;
            decimal innerDistanceunit = 0;
            decimal outerDistanceunit = 0;
            int     outerDist         = totalDist - innerDist;
            decimal innerfare         = (47m / (1000m / 300m));
            decimal outerfare         = (94m / (1000m / 300m));

            if (innerDist > 0)
            {
                innerDistanceunit = (Convert.ToDecimal(innerDist) / 300m);
                outerDistanceunit = (Convert.ToDecimal(outerDist) / 300m);

                totalfare    = (innerfare * innerDistanceunit) + (outerfare * outerDistanceunit);
                distanceunit = innerDistanceunit + outerDistanceunit;
            }
            else
            {
                distanceunit = (totalDist / 300m);
                totalfare    = (outerfare * distanceunit);
            }


            mapn.MoveToRegion(MapSpan.FromPositions(list));

            App.Current.MainPage.DisplayAlert("Price", "Total Distance : " + totalDist + " & Total Price : " + totalfare.ToString("F2")
                                              + "\nOuter Distance : " + outerDist + " @ Price : 94 cents"
                                              + "\nInner Distance : " + innerDist + " @ Price : 47 cents", "Ok");
        }
Exemple #19
0
        //Request a Route using Google Directions API
        async private void requestRoute(Position startLocation, Position endLocation, Position waypoint1, Position waypoint2, Position waypoint3)
        {
            if (CrossConnectivity.Current.IsConnected)
            {
                Console.Out.WriteLine("Connection Valid");
            }
            else
            {
                Console.Out.WriteLine("Connection Invalid");
            }
            Console.Out.WriteLine("Try Requesting");
            string apiKey     = "AIzaSyBj3FmgND9IRoLFfh25eiE2x6Hg37uzDg4";
            string requesturl = "https://maps.googleapis.com/maps/api/directions/json?" + "mode=walking" + "&units=metric" + "&avoid=ferries"
                                + "&origin=" + startLocation.Latitude.ToString() + "," + startLocation.Longitude.ToString()
                                + "&destination=" + endLocation.Latitude.ToString() + "," + endLocation.Longitude.ToString()
                                + "&waypoints=optimize:true|" + waypoint1.Latitude.ToString() + "," + waypoint1.Longitude.ToString() + "|" + waypoint2.Latitude.ToString() + "," + waypoint2.Longitude.ToString() + "|" + waypoint3.Latitude.ToString() + "," + waypoint3.Longitude.ToString()
                                + "&key=" + apiKey;

            //Test for exceptions
            string strException = "-1";

            string strJSONDirectionResponse = await FnHttpRequest(requesturl);

            if (strJSONDirectionResponse == strException)
            {
                Console.Out.WriteLine("Error Returned");
                return;
            }

            //Convert Json to a class
            var objRoutes = JsonConvert.DeserializeObject <googledirectionclass>(strJSONDirectionResponse);

            // Check for error return case - Return to options screen if error returned
            if (objRoutes.status != "OK")
            {
                await DisplayAlert("Alert", "Problem with Directions Request: " + objRoutes.status, "OK");

                //Go back to options screen
                await Navigation.PopAsync();

                return;
            }
            else
            {
                //Decode The Returned points
                string encodedPoints    = objRoutes.routes[0].overview_polyline.points;
                var    lstDecodedPoints = FnDecodePolylinePoints(encodedPoints);

                Xamarin.Forms.GoogleMaps.Polyline polylineoption = new Xamarin.Forms.GoogleMaps.Polyline();

                polylineoption.StrokeWidth = 6f;
                polylineoption.StrokeColor = Color.White;

                double[] latList = new double[lstDecodedPoints.Count];
                double[] lngList = new double[lstDecodedPoints.Count];

                for (int i = 0; i < lstDecodedPoints.Count; i++)
                {
                    polylineoption.Positions.Add(lstDecodedPoints[i]);
                    latList[i] = lstDecodedPoints[i].Latitude;
                    lngList[i] = lstDecodedPoints[i].Longitude;
                }

                double latCentre, lngCentre;
                latCentre = (latList.Max() + latList.Min()) / 2;
                lngCentre = (lngList.Max() + lngList.Min()) / 2;
                Position routeCentrePos = new Position(latCentre, lngCentre);

                //Add polyline to map
                map.Polylines.Add(polylineoption);
                MapSpan routeSpan = new MapSpan(routeCentrePos, 0.02, 0.02);
                map.MoveToRegion(routeSpan);
            }


            //--TASKS--

            //Request String
            WebClient webclient;

            async Task <string> FnHttpRequest(string strUri)
            {
                webclient = new WebClient();
                string strResultData = "";

                try
                {
                    strResultData = await webclient.DownloadStringTaskAsync(new Uri(strUri));
                }
                catch (Exception ex)
                {
                    strResultData = strException;
                    Console.Out.WriteLine("Exception: " + ex);
                }
                finally
                {
                    //Clear resources used
                    if (webclient != null)
                    {
                        webclient.Dispose();
                        webclient = null;
                    }
                }

                return(strResultData);
            }

            //Function to decode encoded points
            List <Position> FnDecodePolylinePoints(string Points)
            {
                if (string.IsNullOrEmpty(Points))
                {
                    return(null);
                }
                var poly = new List <Position>();

                char[] polylinechars = Points.ToCharArray();
                int    ind           = 0;

                int currentLat = 0;
                int currentLng = 0;
                int next5bits;
                int sum;
                int shifter;

                while (ind < polylinechars.Length)
                {
                    //Calculate next latitude
                    sum     = 0;
                    shifter = 0;
                    do
                    {
                        next5bits = (int)polylinechars[ind++] - 63;
                        sum      |= (next5bits & 31) << shifter;
                        shifter  += 5;
                    }while (next5bits >= 32 && ind < polylinechars.Length);

                    if (ind >= polylinechars.Length)
                    {
                        break;
                    }

                    currentLat += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);

                    //calculate next longitude
                    sum     = 0;
                    shifter = 0;
                    do
                    {
                        next5bits = (int)polylinechars[ind++] - 63;
                        sum      |= (next5bits & 31) << shifter;
                        shifter  += 5;
                    }while (next5bits >= 32 && ind < polylinechars.Length);

                    if (ind >= polylinechars.Length && next5bits >= 32)
                    {
                        break;
                    }

                    currentLng += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);

                    Position p = new Position(Convert.ToDouble(currentLat) / 100000.0, Convert.ToDouble(currentLng) / 100000.0);
                    poly.Add(p);
                }
                return(poly);
            }
        }
        public ShapesPage()
        {
            InitializeComponent();

            Polyline polyline = null;
            Polygon polygon = null;
            Circle circle = null;

            // Polyline
            buttonAddPolyline.Clicked += (sender, e) => 
            {
                polyline = new Polyline();
                polyline.Positions.Add(new Position(40.77d, -73.93d));
                polyline.Positions.Add(new Position(40.81d, -73.91d));
                polyline.Positions.Add(new Position(40.83d, -73.87d));

                polyline.IsClickable = true;
                polyline.StrokeColor = Color.Blue;
                polyline.StrokeWidth = 5f;
                polyline.Tag = "POLYLINE"; // Can set any object

                polyline.Clicked += Polyline_Clicked;

                map.Polylines.Add(polyline);

                ((Button)sender).IsEnabled = false;
                buttonRemovePolyline.IsEnabled = true;
            };

            buttonRemovePolyline.Clicked += (sender, e) => 
            {
                map.Polylines.Remove(polyline);
                polyline.Clicked -= Polyline_Clicked;
                polyline = null;

                ((Button)sender).IsEnabled = false;
                buttonAddPolyline.IsEnabled = true;
            };
            buttonRemovePolyline.IsEnabled = false;

            // Polygon
            buttonAddPolygon.Clicked += (sender, e) =>
            {
                polygon = new Polygon();
                polygon.Positions.Add(new Position(40.85d, -73.96d));
                polygon.Positions.Add(new Position(40.87d, -74.00d));
                polygon.Positions.Add(new Position(40.78d, -74.06d));
                polygon.Positions.Add(new Position(40.77d, -74.02d));

                polygon.IsClickable = true;
                polygon.StrokeColor = Color.Green;
                polygon.StrokeWidth = 3f;
                polygon.FillColor = Color.FromRgba(255, 0, 0, 64);
                polygon.Tag = "POLYGON"; // Can set any object

                polygon.Clicked += Polygon_Clicked;;

                map.Polygons.Add(polygon);

                ((Button)sender).IsEnabled = false;
                buttonRemovePolygon.IsEnabled = true;
            };

            buttonRemovePolygon.Clicked += (sender, e) =>
            {
                map.Polygons.Remove(polygon);
                polygon.Clicked -= Polygon_Clicked;
                polygon = null;

                ((Button)sender).IsEnabled = false;
                buttonAddPolygon.IsEnabled = true;
            };
            buttonRemovePolygon.IsEnabled = false;

            // Circle
            buttonAddCircle.Clicked += (sender, e) =>
            {
                circle = new Circle();
                circle.Center = new Position(40.72d, -73.89d);
                circle.Radius = Distance.FromMeters(3000f);

                circle.StrokeColor = Color.Purple;
                circle.StrokeWidth = 6f;
                circle.FillColor = Color.FromRgba(0, 0, 255, 32);
                circle.Tag = "CIRCLE"; // Can set any object

                map.Circles.Add(circle);

                ((Button)sender).IsEnabled = false;
                buttonRemoveCircle.IsEnabled = true;
            };

            buttonRemoveCircle.Clicked += (sender, e) =>
            {
                map.Circles.Remove(circle);
                circle = null;

                ((Button)sender).IsEnabled = false;
                buttonAddCircle.IsEnabled = true;
            };
            buttonRemoveCircle.IsEnabled = false;
        }
Exemple #21
0
        void Calculate(List <Xamarin.Forms.GoogleMaps.Position> list)
        {
            mapn.Polylines.Clear();
            Polygon polygon = Getpolygondata();

            mapn.Polygons.Add(polygon);

            var polyline = new Xamarin.Forms.GoogleMaps.Polyline();

            polyline.StrokeColor = Color.Blue;
            polyline.StrokeWidth = polyline.StrokeWidth * 4;
            var polylineinside = new Xamarin.Forms.GoogleMaps.Polyline();

            polylineinside.StrokeColor = Color.Red;
            polylineinside.StrokeWidth = polyline.StrokeWidth * 2;

            foreach (var p in list)
            {
                polyline.Positions.Add(p);
                if (Contains(p, polygon))
                {
                    // point is inside polygon
                    polylineinside.Positions.Add(p);
                }
            }

            mapn.Polylines.Add(polyline);
            if (polylineinside.Positions.Count > 2)
            {
                mapn.Polylines.Add(polylineinside);
            }

            var pin = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.Place,
                Position = new Position(polyline.Positions.First().Latitude, polyline.Positions.First().Longitude),
                Label    = vm.StartLabel,
                Address  = vm.StartAdd,
                Tag      = "First Point",
                Icon     = BitmapDescriptorFactory.FromView(new Image()
                {
                    Source = "ic_location.png", WidthRequest = 25, HeightRequest = 25
                })
            };

            mapn.Pins.Add(pin);
            var pin1 = new Xamarin.Forms.GoogleMaps.Pin
            {
                Type     = PinType.Place,
                Position = new Position(polyline.Positions.Last().Latitude, polyline.Positions.Last().Longitude),
                Label    = vm.EndLabel,
                Address  = vm.EndAdd,
                Tag      = "Last Point",
                Icon     = BitmapDescriptorFactory.FromView(new Image()
                {
                    Source = "ic_location_red.png", WidthRequest = 25, HeightRequest = 25
                })
            };

            mapn.Pins.Add(pin1);
            int InnerDist = 0;

            if (polylineinside.Positions.Count > 2)
            {
                var googleDirection = (vm.GetDistance(polylineinside.Positions.First(), polylineinside.Positions.Last()).Result);

                if (googleDirection.Routes != null && googleDirection.Routes.Count > 0)
                {
                    InnerDist = googleDirection.Routes.FirstOrDefault().Legs.FirstOrDefault().Distance.Value;
                }
            }
            int     TotalDistance     = vm.CurrentGoogleDirection.Routes.FirstOrDefault().Legs.FirstOrDefault().Distance.Value;
            decimal TotalFare         = 0;
            decimal DistanceUnit      = 0;
            decimal InnerDistanceUnit = 0;
            decimal OuterDistanceUnit = 0;
            int     OuterDist         = TotalDistance - InnerDist;
            decimal InnerFare         = (Constants.InnerFareRate / (Constants.DistanceUnitKM / Constants.BillingUnit));
            decimal OuterFare         = (Constants.OuterFareRate / (Constants.DistanceUnitKM / Constants.BillingUnit));

            if (InnerDist > 0)
            {
                InnerDistanceUnit = (Convert.ToDecimal(InnerDist) / Constants.BillingUnit);
                OuterDistanceUnit = (Convert.ToDecimal(OuterDist) / Constants.BillingUnit);

                TotalFare    = (InnerFare * InnerDistanceUnit) + (OuterFare * OuterDistanceUnit);
                DistanceUnit = InnerDistanceUnit + OuterDistanceUnit;
            }
            else
            {
                DistanceUnit = (TotalDistance / Constants.BillingUnit);
                TotalFare    = (OuterFare * DistanceUnit);
            }


            mapn.MoveToRegion(MapSpan.FromPositions(list));

            App.Current.MainPage.DisplayAlert("Price", "Total Distance : " + TotalDistance + " & Total Price : " + TotalFare.ToString("F2")
                                              + "\nOuter Distance : " + OuterDist + " @ Price : " + Constants.OuterFareRate + " cents"
                                              + "\nInner Distance : " + InnerDist + " @ Price : " + Constants.InnerFareRate + " cents", "Ok");
        }