示例#1
0
        public void OnMapReady(GoogleMap googleMap)
        {
            try
            {
                Map = googleMap;

                var makerOptions = new MarkerOptions();
                makerOptions.SetPosition(new LatLng(Lat, Lng));
                makerOptions.SetTitle(GetText(Resource.String.Lbl_Location));

                Map.AddMarker(makerOptions);
                Map.MapType = GoogleMap.MapTypeNormal;

                if (AppSettings.SetTabDarkTheme)
                {
                    MapStyleOptions style = MapStyleOptions.LoadRawResourceStyle(this, Resource.Raw.map_dark);
                    Map.SetMapStyle(style);
                }

                //Optional
                googleMap.UiSettings.ZoomControlsEnabled = true;
                googleMap.UiSettings.CompassEnabled      = true;

                OnLocationChanged();

                googleMap.MoveCamera(CameraUpdateFactory.ZoomIn());

                LatLng location = new LatLng(Lat, Lng);

                CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
                builder.Target(location);
                builder.Zoom(18);
                builder.Bearing(155);
                builder.Tilt(65);

                CameraPosition cameraPosition = builder.Build();

                CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);
                googleMap.MoveCamera(cameraUpdate);

                googleMap.MapClick += async(sender, e) =>
                {
                    try
                    {
                        LatLng latLng      = e.Point;
                        var    tapTextView = "Tapped: Point=" + e.Point;
                        Console.WriteLine(tapTextView);

                        Lat = latLng.Latitude;
                        Lng = latLng.Longitude;

                        // Creating a marker
                        MarkerOptions markerOptions = new MarkerOptions();

                        // Setting the position for the marker
                        markerOptions.SetPosition(e.Point);

                        var addresses = await ReverseGeocodeCurrentLocation(latLng);

                        if (addresses != null)
                        {
                            DeviceAddress = addresses.GetAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                            //string city = addresses.Locality;
                            //string state = addresses.AdminArea;
                            //string country = addresses.CountryName;
                            //string postalCode = addresses.PostalCode;
                            //string knownName = addresses.FeatureName; // Only if available else return NULL

                            // Setting the title for the marker.
                            // This will be displayed on taping the marker
                            markerOptions.SetTitle(DeviceAddress);
                        }

                        // Clears the previously touched position
                        googleMap.Clear();

                        // Animating to the touched position
                        googleMap.AnimateCamera(CameraUpdateFactory.NewLatLng(e.Point));

                        // Placing a marker on the touched position
                        googleMap.AddMarker(markerOptions);
                    }
                    catch (Exception exception)
                    {
                        Methods.DisplayReportResultTrack(exception);
                    }
                };

                googleMap.MapLongClick += (sender, e) =>
                {
                    try
                    {
                        var tapTextView = "Long Pressed: Point=" + e.Point;
                        Console.WriteLine(tapTextView);
                    }
                    catch (Exception exception)
                    {
                        Methods.DisplayReportResultTrack(exception);
                    }
                };

                googleMap.CameraChange += (sender, e) =>
                {
                    try
                    {
                        var cameraTextView = e.Position.ToString();
                        Console.WriteLine(cameraTextView);
                    }
                    catch (Exception exception)
                    {
                        Methods.DisplayReportResultTrack(exception);
                    }
                };
            }
            catch (Exception e)
            {
                Methods.DisplayReportResultTrack(e);
            }
        }
示例#2
0
        private async void SearchViewOnQueryTextSubmit(object sender, SearchView.QueryTextSubmitEventArgs e)
        {
            try
            {
                SearchText = e.NewText;

                if (string.IsNullOrEmpty(SearchText) || string.IsNullOrWhiteSpace(SearchText))
                {
                    return;
                }

                SearchView.ClearFocus();

                //Show a progress
                RunOnUiThread(() => { AndHUD.Shared.Show(this, GetText(Resource.String.Lbl_Loading)); });

                var latLng = await GetLocationFromAddress(SearchText.Replace(" ", ""));

                if (latLng != null)
                {
                    RunOnUiThread(() => { AndHUD.Shared.Dismiss(this); });

                    DeviceAddress = SearchText;

                    Lat = latLng.Latitude;
                    Lng = latLng.Longitude;

                    // Creating a marker
                    MarkerOptions markerOptions = new MarkerOptions();

                    // Setting the position for the marker
                    markerOptions.SetPosition(latLng);

                    var addresses = await ReverseGeocodeCurrentLocation(latLng);

                    if (addresses != null)
                    {
                        DeviceAddress = addresses.GetAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                        //string city = addresses.Locality;
                        //string state = addresses.AdminArea;
                        //string country = addresses.CountryName;
                        //string postalCode = addresses.PostalCode;
                        //string knownName = addresses.FeatureName; // Only if available else return NULL

                        // Setting the title for the marker.
                        // This will be displayed on taping the marker
                        markerOptions.SetTitle(DeviceAddress);
                    }

                    // Clears the previously touched position
                    Map.Clear();

                    // Animating to the touched position
                    Map.AnimateCamera(CameraUpdateFactory.NewLatLng(latLng));

                    // Placing a marker on the touched position
                    Map.AddMarker(markerOptions);

                    CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
                    builder.Target(latLng);
                    builder.Zoom(18);
                    builder.Bearing(155);
                    builder.Tilt(65);

                    CameraPosition cameraPosition = builder.Build();

                    CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);
                    Map.MoveCamera(cameraUpdate);
                }
                else
                {
                    RunOnUiThread(() => { AndHUD.Shared.Dismiss(this); });


                    //Error Message
                    Toast.MakeText(this, GetText(Resource.String.Lbl_Error_DisplayAddress), ToastLength.Short)?.Show();
                }
            }
            catch (Exception exception)
            {
                RunOnUiThread(() => { AndHUD.Shared.Dismiss(this); });
                Methods.DisplayReportResultTrack(exception);
            }
        }
 /// <summary>
 /// Map click handler.
 /// </summary>
 /// <param name="point"></param>
 public void OnMapClick(LatLng point)
 {
     _googleMap.AnimateCamera(CameraUpdateFactory.NewLatLng(point));
 }
示例#4
0
        private void UpdatePositions()
        {
            TimeStep[] currentTimeSteps;
            DateTime   now = DateTime.Now;

            // Take time steps snapshot
            lock (timeSteps)
                currentTimeSteps = timeSteps.ToArray();

            // Sort time steps by step
            Dictionary <Step, TimeStep> steps = currentTimeSteps.GroupBy(s => s.Step)
                                                .ToDictionary(g => g.Key, g => g.OrderBy(s => s.Date).First());

            // For each route, find transport positions
            List <Transport> transports = new List <Transport>();

            foreach (Line line in TramUrWayApplication.Lines)
            {
                foreach (Route route in line.Routes)
                {
                    for (int i = 0; i < route.Steps.Length - 1; i++)
                    {
                        Step step     = route.Steps[i];
                        Step nextStep = route.Steps[i + 1];

                        TimeStep timeStep, nextTimeStep;
                        if (!steps.TryGetValue(nextStep, out nextTimeStep))
                        {
                            continue;
                        }
                        steps.TryGetValue(step, out timeStep);

                        if (timeStep != null && timeStep.Date < nextTimeStep.Date)
                        {
                            continue;
                        }

                        TimeSpan diff     = nextTimeStep.Date - now;
                        TimeSpan duration = step.Duration ?? TimeSpan.Zero;

                        if (duration == TimeSpan.Zero)
                        {
                            duration = TimeSpan.FromMinutes(2);
                        }

                        float progress = (float)(1 - Math.Min(diff.TotalMinutes, duration.TotalMinutes) / duration.TotalMinutes);
                        if (progress < 0)
                        {
                            progress = 0;
                        }
                        if (progress > 1)
                        {
                            progress = 1;
                        }

                        float nextProgress = (float)(1 - Math.Min(diff.Subtract(TimeSpan.FromSeconds(1)).TotalMinutes, duration.TotalMinutes) / duration.TotalMinutes);
                        if (nextProgress < 0)
                        {
                            nextProgress = 0;
                        }
                        if (nextProgress > 1)
                        {
                            nextProgress = 1;
                        }

                        Transport transport = new Transport()
                        {
                            Route        = route,
                            Step         = step,
                            TimeStep     = nextTimeStep,
                            Progress     = step.Speed.Evaluate(progress),
                            NextProgress = step.Speed.Evaluate(nextProgress)
                        };

                        transports.Add(transport);
                    }
                }
            }

            // Sort markers
            Dictionary <Step, Marker> stepMarkers       = transportMarkers.ToDictionary(p => p.Key.Step, p => p.Value);
            List <Marker>             unusedMarkers     = stepMarkers.Where(p => !transports.Any(t => t.Step == p.Key)).Select(p => p.Value).ToList();
            List <Transport>          missingTransports = transports.Where(t => !stepMarkers.Keys.Contains(t.Step)).ToList();
            Dictionary <Step, Marker> reusableMarkers   = stepMarkers.Where(p => transports.Any(t => t.Step == p.Key) && !missingTransports.Any(t => t.Step == p.Key)).ToDictionary();

            // Adjust markers diff
            while (unusedMarkers.Count > missingTransports.Count)
            {
                Marker marker = unusedMarkers.Last();
                unusedMarkers.RemoveAt(unusedMarkers.Count - 1);
                Activity.RunOnUiThread(marker.Remove);
            }
            while (missingTransports.Count > unusedMarkers.Count)
            {
                ManualResetEvent resetEvent = new ManualResetEvent(false);

                Activity.RunOnUiThread(() =>
                {
                    MarkerOptions markerOptions = new MarkerOptions()
                                                  .Anchor(0.5f, 0.5f)
                                                  .SetPosition(new LatLng(0, 0));

                    Marker marker = googleMap.AddMarker(markerOptions);
                    unusedMarkers.Add(marker);

                    resetEvent.Set();
                });

                resetEvent.WaitOne();
            }

            // Use existing markers to match current transports
            transportMarkers = reusableMarkers.Select(p => new KeyValuePair <Transport, Marker>(transports.First(t => t.Step == p.Key), p.Value))
                               .Concat(missingTransports.Zip(unusedMarkers, (t, m) => new KeyValuePair <Transport, Marker>(t, m)))
                               .ToDictionary();

            foreach (var pair in transportMarkers)
            {
                Transport transport = pair.Key;
                Marker    marker    = pair.Value;

                // Compute quick position
                Position quickFrom     = transport.Step.Stop.Position;
                Position quickTo       = transport.TimeStep.Step.Stop.Position;
                LatLng   quickPosition = new LatLng(quickFrom.Latitude + (quickTo.Latitude - quickFrom.Latitude) * transport.Progress, quickFrom.Longitude + (quickTo.Longitude - quickFrom.Longitude) * transport.Progress);

                // Update marker
                Activity.RunOnUiThread(() => marker.SetIcon(lineIcons[transport.Route.Line]));
                bool visible;
                if (markersVisibility.TryGetValue(marker, out visible) && !visible)
                {
                    continue;
                }

                // Use animation only if zoomed enough
                if (cameraPosition.Zoom >= AnimationZoomLimit)
                {
                    ValueAnimator valueAnimator = new ValueAnimator();
                    valueAnimator.AddUpdateListener(new MarkerAnimator(Activity, marker, transport, p => SetMarkerPosition(transport, marker, p)));
                    valueAnimator.SetFloatValues(0, 1); // Ignored.
                    valueAnimator.SetInterpolator(new LinearInterpolator());
                    valueAnimator.SetDuration(1000);
                    Activity.RunOnUiThread(valueAnimator.Start);
                }
                else
                {
                    float progress = transport.Progress;
                    int   index    = transport.Step.Trajectory.TakeWhile(s => s.Index <= progress).Count();

                    bool           last = index >= transport.Step.Trajectory.Length;
                    TrajectoryStep from = transport.Step.Trajectory[index - 1];
                    TrajectoryStep to   = last ? transport.TimeStep.Step.Trajectory.First() : transport.Step.Trajectory[index];

                    progress = (progress - from.Index) / ((last ? 1 : to.Index) - from.Index);
                    LatLng position = new LatLng(from.Position.Latitude + (to.Position.Latitude - from.Position.Latitude) * transport.Progress, from.Position.Longitude + (to.Position.Longitude - from.Position.Longitude) * transport.Progress);

                    SetMarkerPosition(transport, marker, position);
                }

                // Follow selected transport
                Activity.RunOnUiThread(() =>
                {
                    if (marker.Id == selectedMarkerId)
                    {
                        googleMap.AnimateCamera(CameraUpdateFactory.NewLatLng(quickPosition));
                    }
                });
            }
        }
#pragma warning disable CS0809 // 旧形式のメンバーが、旧形式でないメンバーをオーバーライドします
        protected override void OnCreate(Bundle savedInstanceState)
#pragma warning restore CS0809 // 旧形式のメンバーが、旧形式でないメンバーをオーバーライドします
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.Main);

            var mapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.map);

            mapFragment.GetMapAsync(this);

            FindViewById <Button>(Resource.Id.buttonCenter).Click += (sender, e) =>
            {
                gMap.AnimateCamera(CameraUpdateFactory.NewLatLng(
                                       new LatLng(35.68d, 139.76d))); // 東京駅付近 <--2
            };

            FindViewById <Button>(Resource.Id.buttonBounds).Click += (sender, e) =>
            {
                var bounds = LatLngBounds.InvokeBuilder()
                             .Include(new LatLng(35.4661d, 139.6227d))                // 横浜駅
                             .Include(new LatLng(35.4713d, 139.6274d))                // 神奈川駅
                             .Build();                                                //<--1

                gMap.AnimateCamera(CameraUpdateFactory.NewLatLngBounds(bounds, 100)); //<--2
            };

            FindViewById <Button>(Resource.Id.buttonCamera).Click += (sender, e) =>
            {
                gMap.AnimateCamera(CameraUpdateFactory.NewCameraPosition(
                                       new CameraPosition(
                                           new LatLng(35.710063d, 139.8107d), // 東京スカイツリー(中心位置)
                                           17f,                               // ズームレベル
                                           45f,                               // 方位
                                           30f)));                            // 傾き
            };

            Marker marker1 = null;
            Marker marker2 = null;

            FindViewById <Button>(Resource.Id.buttonAddMarker).Click += (sender, e) =>
            {
                if (marker1 == null)
                {
                    marker1 = gMap.AddMarker(new MarkerOptions()
                                             .SetTitle("東京スカイツリー")
                                             .SetSnippet("東京都墨田区押上1−1−2")
                                             .SetPosition(new LatLng(35.710063d, 139.8107d))
                                             .InvokeIcon(BitmapDescriptorFactory.DefaultMarker(
                                                             BitmapDescriptorFactory.HueAzure)) //<--1
                                             );
                }

                if (marker2 == null)
                {
                    marker2 = gMap.AddMarker(new MarkerOptions()
                                             .SetTitle("東京タワー")
                                             .SetSnippet("東京都港区芝公園4−2−8")
                                             .SetPosition(new LatLng(35.65858, 139.745433))
                                             .InvokeIcon(BitmapDescriptorFactory.DefaultMarker(
                                                             BitmapDescriptorFactory.HueOrange)) //<--2
                                             );
                }
            };

            FindViewById <Button>(Resource.Id.buttonDeleteMarker).Click += (sender, e) =>
            {
                if (marker1 != null)
                {
                    marker1.Remove();
                    marker1 = null;
                }
            };
        }
        void SetupMap()
        {
            if (mapFrag.View.Width == 0)
            {
                mapFrag.View.PostDelayed(SetupMap, 500);
                return;
            }
            if (viewModel.Trip == null || viewModel.Trip.Points == null || viewModel.Trip.Points.Count == 0)
            {
                return;
            }

            var start = viewModel.Trip.Points[0];
            var end   = viewModel.Trip.Points[viewModel.Trip.Points.Count - 1];

            seekBar.Max              = viewModel.Trip.Points.Count - 1;
            seekBar.ProgressChanged += SeekBar_ProgressChanged;

            var logicalDensity  = Resources.DisplayMetrics.Density;
            var thicknessCar    = (int)Math.Ceiling(26 * logicalDensity + .5f);
            var thicknessPoints = (int)Math.Ceiling(20 * logicalDensity + .5f);

            var b         = ContextCompat.GetDrawable(this, Resource.Drawable.ic_car_blue) as BitmapDrawable;
            var finalIcon = Bitmap.CreateScaledBitmap(b.Bitmap, thicknessCar, thicknessCar, false);

            var car = new MarkerOptions();

            car.SetPosition(new LatLng(start.Latitude, start.Longitude));
            car.SetIcon(BitmapDescriptorFactory.FromBitmap(finalIcon));
            car.Anchor(.5f, .5f);

            b         = ContextCompat.GetDrawable(this, Resource.Drawable.ic_start_point) as BitmapDrawable;
            finalIcon = Bitmap.CreateScaledBitmap(b.Bitmap, thicknessPoints, thicknessPoints, false);

            var startMarker = new MarkerOptions();

            startMarker.SetPosition(new LatLng(start.Latitude, start.Longitude));
            startMarker.SetIcon(BitmapDescriptorFactory.FromBitmap(finalIcon));
            startMarker.Anchor(.5f, .5f);

            b         = ContextCompat.GetDrawable(this, Resource.Drawable.ic_end_point) as BitmapDrawable;
            finalIcon = Bitmap.CreateScaledBitmap(b.Bitmap, thicknessPoints, thicknessPoints, false);

            var endMarker = new MarkerOptions();

            endMarker.SetPosition(new LatLng(end.Latitude, end.Longitude));
            endMarker.SetIcon(BitmapDescriptorFactory.FromBitmap(finalIcon));
            endMarker.Anchor(.5f, .5f);

            b         = ContextCompat.GetDrawable(this, Resource.Drawable.ic_tip) as BitmapDrawable;
            finalIcon = Bitmap.CreateScaledBitmap(b.Bitmap, thicknessPoints, thicknessPoints, false);
            var poiIcon = BitmapDescriptorFactory.FromBitmap(finalIcon);

            foreach (var poi in viewModel.POIs)
            {
                var poiMarker = new MarkerOptions();
                poiMarker.SetPosition(new LatLng(poi.Latitude, poi.Longitude));
                poiMarker.SetIcon(poiIcon);
                poiMarker.Anchor(.5f, .5f);
                map.AddMarker(poiMarker);
            }


            var points      = viewModel.Trip.Points.Select(s => new LatLng(s.Latitude, s.Longitude)).ToArray();
            var rectOptions = new PolylineOptions();

            rectOptions.Add(points);
            rectOptions.InvokeColor(ContextCompat.GetColor(this, Resource.Color.primary_dark));
            map.AddPolyline(rectOptions);


            map.AddMarker(startMarker);
            map.AddMarker(endMarker);

            carMarker = map.AddMarker(car);

            var boundsPoints = new LatLngBounds.Builder();

            foreach (var point in points)
            {
                boundsPoints.Include(point);
            }

            var bounds = boundsPoints.Build();

            map.MoveCamera(CameraUpdateFactory.NewLatLngBounds(bounds, 64));

            map.MoveCamera(CameraUpdateFactory.NewLatLng(carMarker.Position));


            seekBar.Enabled = true;
        }