I have a template that I use for a button. I placed four of these buttons on a page like this:
<template:Button Meta="gst" Grid.Column="1" Selected="{Binding Mode[0].Selected}" Text="{Binding Mode[0].Name}" TapCommand="{Binding ModeBtnCmd }" />
<template:Button Meta="gst" Grid.Column="2" Selected="{Binding Mode[1].Selected}" Text="{Binding Mode[1].Name}" TapCommand="{Binding ModeBtnCmd }" />
<template:Button Meta="gst" Grid.Column="3" Selected="{Binding Mode[2].Selected}" Text="{Binding Mode[2].Name}" TapCommand="{Binding ModeBtnCmd }" />
<template:Button Meta="gst" Grid.Column="4" Selected="{Binding Mode[3].Selected}" Text="{Binding Mode[3].Name}" TapCommand="{Binding ModeBtnCmd }" />
I declare an array called Mode that I use to store some values for the Selected parameter in an array declared like this:
public partial class HomePageViewModel : ObservableObject
{
ParamViewModel[] _mode;
public ParamViewModel[] Mode { get => _mode; set => SetProperty(ref _mode, value); }
In the OnAppearing I set the value of Selected for each element in the array:
protected async override void OnAppearing()
{
base.OnAppearing();
vm.Mode[0].Selected = false;
vm.Mode[1].Selected = false;
vm.Mode[2].Selected = true;
vm.Mode[3].Selected = false;
However I do not see the HandleSelectedPropertyChanged called for each of the Buttons. If I set a debug point in the HandleSelectedPropertyChanged event, I only see it being called once.
I expect only the 3rd button to be selected but when the code runs the buttons appear as:
Selected Selected Selected Selected
Can someone give me advice on this. The code works when I click on the buttons one by one and the back-end changes the selected and then the above SetButtons is called. But it doesn't work initially and all buttons appear as selected.
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Japanese.Templates
{
public partial class Button : Frame
{
public static readonly BindableProperty TapCommandProperty = BindableProperty.Create("TapCommand", typeof(Command), typeof(Button), defaultBindingMode: BindingMode.TwoWay, defaultValue: default(Command));
public static readonly BindableProperty TapCommandParamProperty = BindableProperty.Create(nameof(TapCommandParam), typeof(object), typeof(Button), default(object));
public static readonly BindableProperty
SelectedProperty = BindableProperty.Create(nameof(Selected),
typeof(bool),
typeof(Button),
false,
propertyChanged: HandleSelectedPropertyChanged);
public static readonly BindableProperty
TextProperty = BindableProperty.Create(nameof(Text),
typeof(string),
typeof(Button),
default(string));
public static readonly BindableProperty
MetaProperty = BindableProperty.Create("Meta",
typeof(string),
typeof(Button),
default(string),
propertyChanged: HandleMetaPropertyChanged);
public static readonly BindableProperty VisibleProperty = BindableProperty.Create(nameof(Visible), typeof(bool), typeof(Button), true);
public string Text { get => (string)GetValue(TextProperty); set => SetValue(TextProperty, value); }
public string Meta { get => (string)GetValue(MetaProperty); set => SetValue(MetaProperty, value); }
public Command TapCommand { get => (Command)GetValue(TapCommandProperty); set => SetValue(TapCommandProperty, value); }
public object TapCommandParam { get => (object)GetValue(TapCommandParamProperty); set => SetValue(TapCommandParamProperty, value); }
public bool Selected { get => (bool)GetValue(SelectedProperty); set => SetValue(SelectedProperty, value); }
public bool Visible { get => (bool)GetValue(VisibleProperty); set => SetValue(VisibleProperty, value); }
string b;
string s;
string f;
public Button()
{
InitializeComponent();
HasShadow = false;
HorizontalOptions = LayoutOptions.Center;
VerticalOptions = LayoutOptions.Center;
}
private static void HandleMetaPropertyChanged(BindableObject bindable, object oldValue, object meta)
{
var control = (Button)bindable;
if (control != null) {
control.b = ((string)meta).Substring(0, 1); // background surface
control.s = ((string)meta).Substring(1, 1); // shape
control.f = ((string)meta).Substring(2, 1); // font
control.BackgroundColor = control.b == "g" ?
(Color)Application.Current.Resources["GridButtonBackgroundColor"] :
(Color)Application.Current.Resources["PageButtonBackgroundColor"];
control.BorderColor = control.b == "g" ?
(Color)Application.Current.Resources["GridButtonBorderColor"] :
(Color)Application.Current.Resources["PageButtonBorderColor"];
if (control.s == "s")
{
control.CornerRadius = 5;
control.Padding = new Thickness(10, 5);
}
else
{
control.WidthRequest = 50;
control.HeightRequest = 50;
control.CornerRadius = 25;
control.Padding = new Thickness(0);
}
Application.Current.Resources.TryGetValue("TextButtonsLabelRes", out object textRes);
Application.Current.Resources.TryGetValue("IconButtonsLabelRes", out object iconRes);
control.ButtonLabel.Style = (control.f == "t") ?
(Style)textRes :
(Style)iconRes;
}
}
private static void HandleSelectedPropertyChanged(BindableObject bindable, object oldValue, object selected)
{
var control = (Button)bindable;
if (control != null)
control.ButtonLabel.TextColor =
((bool)selected) ?
(control.b == "g" ?
(Color)Application.Current.Resources["GridEButtonTextColor"] :
(Color)Application.Current.Resources["PageEButtonTextColor"]) :
(control.b == "g" ?
(Color)Application.Current.Resources["GridButtonTextColor"] :
(Color)Application.Current.Resources["PageButtonTextColor"]);
}
private async void ChangeTheColours(Object sender, EventArgs e)
{
if ((string)this.ButtonLabel.Text.Substring(0, 1) != " ")
{
BackgroundColor = this.b == "g" ?
(Color)Application.Current.Resources["GridCButtonBackgroundColor"] :
(Color)Application.Current.Resources["PageCButtonBackgroundColor"];
BorderColor = this.b == "g" ?
(Color)Application.Current.Resources["GridCButtonBorderColor"] :
(Color)Application.Current.Resources["PageCButtonBorderColor"];
await Task.Delay(500);
BackgroundColor = this.b == "g" ?
(Color)Application.Current.Resources["GridButtonBackgroundColor"] :
(Color)Application.Current.Resources["PageButtonBackgroundColor"];
BorderColor = this.b == "g" ?
(Color)Application.Current.Resources["GridButtonBorderColor"] :
(Color)Application.Current.Resources["PageButtonBorderColor"];
}
}
}
}
For reference here's the SetProperty function:
public class ObservableObject : INotifyPropertyChanged
{
protected virtual bool SetProperty<T>(
ref T backingStore, T value,
[CallerMemberName]string propertyName = "",
Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;
backingStore = value;
onChanged?.Invoke();
OnPropertyChanged(propertyName);
return true;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
Just as a reminder the code and method here is working good except for the initial set up where it does not seem to call the propertyChanged event as expected.
The default value on your SelectedProperty is false, OnPropertyChanged is only fired when the current value differs from the new value. Hence only the 3rd button, whose value is being set to true is being fired.
You have to define your initial state of the control in its constructor. Upon any property changes the subsequent changes will be handled in the PropertyChanged handler
I am applying gesture feature to my Label control. I have used this link- http://arteksoftware.com/gesture-recognizers-with-xamarin-forms/
I was able to get the LongPressGestureRecognizer event when i performed long press on label control.This event is getting called in renderer file.
I want to perform some operation in my shared code on LongPressGestureRecognizer event. so how can I detect this event in my shared code ? How to handle event handler to get this longpress event in my shared code ?
In your custom control declare command:
public class TappedGrid : Grid
{
public static readonly BindableProperty TappedCommandProperty =
BindableProperty.Create(nameof(TappedCommand),
typeof(ICommand),
typeof(TappedGrid),
default(ICommand));
public ICommand TappedCommand
{
get { return (ICommand)GetValue(TappedCommandProperty); }
set { SetValue(TappedCommandProperty, value); }
}
public static readonly BindableProperty LongPressCommandProperty =
BindableProperty.Create(nameof(LongPressCommand),
typeof(ICommand),
typeof(TappedGrid),
default(ICommand));
public ICommand LongPressCommand
{
get { return (ICommand)GetValue(LongPressCommandProperty); }
set { SetValue(LongPressCommandProperty, value); }
}
}
And then raise this command from renderer:
public class TappedGridRenderer : ViewRenderer
{
UITapGestureRecognizer tapGesturesRecognizer;
UILongPressGestureRecognizer longPressGesturesRecognizer;
protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
base.OnElementChanged(e);
tapGesturesRecognizer = new UITapGestureRecognizer(() =>
{
var grid = (TappedGrid)Element;
if (grid.TappedCommand.CanExecute(Element.BindingContext))
{
grid.TappedCommand.Execute(Element.BindingContext);
}
});
longPressGesturesRecognizer = new UILongPressGestureRecognizer(() =>
{
var grid = (TappedGrid)Element;
if (longPressGesturesRecognizer.State == UIGestureRecognizerState.Ended &&
grid.LongPressCommand.CanExecute(Element.BindingContext))
{
grid.LongPressCommand.Execute(Element.BindingContext);
}
});
this.RemoveGestureRecognizer(tapGesturesRecognizer);
this.RemoveGestureRecognizer(longPressGesturesRecognizer);
this.AddGestureRecognizer(tapGesturesRecognizer);
this.AddGestureRecognizer(longPressGesturesRecognizer);
}
}
If you are searching for a full polylines, pins, tiles, UIOptions (and 3D effects soon) renderings/implementations, you should take a loot at the public github I made at XamarinByEmixam23/..../Map.
I search a lot but I still have the same problem:
How can I update, refresh or reload the Xamarin.Forms.Maps?
In the class definition (class CustomMap : Map), there is no method to update the maps.. Maybe a MVVM logic can solves the problem, but I can't find it on the Web..
I followed this tutorial for the maps : Working with maps
To customise it, I followed this tutorial : Highlight a Route on a Map
So, after these tutorials (I made the same things, no changes), I tried with 2 RouteCoordinates which gave me a straight line... I then made an algorithm which works perfectly.
DirectionMap
public class DirectionMap
{
public Distance distance { get; set; }
public Duration duration { get; set; }
public Address address_start { get; set; }
public Address address_end { get; set; }
public List<Step> steps { get; set; }
public class Distance
{
public string text { get; set; }
public int value { get; set; }
}
public class Duration
{
public string text { get; set; }
public int value { get; set; }
}
public class Address
{
public string text { get; set; }
public Position position { get; set; }
}
public class Step
{
public Position start { get; set; }
public Position end { get; set; }
}
}
ResponseHttpParser
public static void parseDirectionGoogleMapsResponse(HttpStatusCode httpStatusCode, JObject json, Action<DirectionMap, string> callback)
{
switch (httpStatusCode)
{
case HttpStatusCode.OK:
DirectionMap directionMap = null;
string strException = null;
try
{
directionMap = new DirectionMap()
{
distance = new DirectionMap.Distance()
{
text = (json["routes"][0]["legs"][0]["distance"]["text"]).ToString(),
value = Int32.Parse((json["routes"][0]["legs"][0]["distance"]["value"]).ToString())
},
duration = new DirectionMap.Duration()
{
text = (json["routes"][0]["legs"][0]["duration"]["text"]).ToString(),
value = Int32.Parse((json["routes"][0]["legs"][0]["duration"]["value"]).ToString())
},
address_start = new DirectionMap.Address()
{
text = (json["routes"][0]["legs"][0]["start_address"]).ToString(),
position = new Position(Double.Parse((json["routes"][0]["legs"][0]["start_location"]["lat"]).ToString()), Double.Parse((json["routes"][0]["legs"][0]["start_location"]["lng"]).ToString()))
},
address_end = new DirectionMap.Address()
{
text = (json["routes"][0]["legs"][0]["end_address"]).ToString(),
position = new Position(Double.Parse((json["routes"][0]["legs"][0]["end_location"]["lat"]).ToString()), Double.Parse((json["routes"][0]["legs"][0]["end_location"]["lng"]).ToString()))
}
};
bool finished = false;
directionMap.steps = new List<Step>();
int index = 0;
while (!finished)
{
try
{
Step step = new Step()
{
start = new Position(Double.Parse((json["routes"][0]["legs"][0]["steps"][index]["start_location"]["lat"]).ToString()), Double.Parse((json["routes"][0]["legs"][0]["steps"][index]["start_location"]["lng"]).ToString())),
end = new Position(Double.Parse((json["routes"][0]["legs"][0]["steps"][index]["end_location"]["lat"]).ToString()), Double.Parse((json["routes"][0]["legs"][0]["steps"][index]["end_location"]["lng"]).ToString()))
};
directionMap.steps.Add(step);
index++;
}
catch (Exception e)
{
finished = true;
}
}
}
catch (Exception e)
{
directionMap = null;
strException = e.ToString();
}
finally
{
callback(directionMap, strException);
}
break;
default:
switch (httpStatusCode)
{
}
callback(null, json.ToString());
break;
}
}
I just get the distance and duration for some private calculs and get each step that I put into a List<>;
When everything is finished, I use my callback which bring us back to the controller (MapPage.xaml.cs the XAML Form Page (Xamarin Portable))
Now, everything becomes weird. It's like the map doesn't get that changes are made
public partial class MapPage : ContentPage
{
public MapPage()
{
InitializeComponent();
setupMap();
setupMapCustom();
}
public void setupMapCustom()
{
customMap.RouteCoordinates.Add(new Position(37.785559, -122.396728));
customMap.RouteCoordinates.Add(new Position(37.780624, -122.390541));
customMap.RouteCoordinates.Add(new Position(37.777113, -122.394983));
customMap.RouteCoordinates.Add(new Position(37.776831, -122.394627));
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Xamarin.Forms.Maps.Distance.FromMiles(1.0)));
}
public async void setupMap()
{
customMap.MapType = MapType.Satellite;
string origin = "72100 Le Mans";
string destination = "75000 Paris";
HttpRequest.getDirections(origin, destination, callbackDirections);
customMap.RouteCoordinates.Add(await MapUtilities.GetMapPointOfStreetAddress(origin));
Position position = await MapUtilities.GetMapPointOfStreetAddress(destination);
//customMap.RouteCoordinates.Add(position);
var pin = new Pin
{
Type = PinType.Place,
Position = position,
Label = "Destination !!",
};
customMap.Pins.Add(pin);
}
private async void callbackDirections(Object obj, string str)
{
if (obj != null)
{
DirectionMap directionMap = obj as DirectionMap;
foreach (Step step in directionMap.steps)
{
customMap.RouteCoordinates.Add(step.start);
System.Diagnostics.Debug.WriteLine("add step");
}
customMap.RouteCoordinates.Add(directionMap.address_end.position);
System.Diagnostics.Debug.WriteLine("add last step");
}
else
{
System.Diagnostics.Debug.WriteLine(str);
}
}
}
I run my app, everything works until it's something fast, because of the time spent by my algorithm etc, the callback is coming too late and then I need to refresh, reload or update my map... Anyway, I need to update my map in the future, so... If anyone can help, this one is welcome !
EDIT 1
I took a look at your answer ( thank a lot ! ;) ) but it doesn't works :/
I updated CustomMap as you did
public class CustomMap : Map
{
public static readonly BindableProperty RouteCoordinatesProperty =
BindableProperty.Create<CustomMap, List<Position>>(p => p.RouteCoordinates, new List<Position>());
public List<Position> RouteCoordinates
{
get { return (List<Position>)GetValue(RouteCoordinatesProperty); }
set { SetValue(RouteCoordinatesProperty, value); }
}
public CustomMap()
{
RouteCoordinates = new List<Position>();
}
}
Same for CustomMapRenderer (Droid)
public class CustomMapRenderer : MapRenderer, IOnMapReadyCallback
{
GoogleMap map;
Polyline polyline;
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Xamarin.Forms.View> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
// Unsubscribe
}
if (e.NewElement != null)
{
((MapView)Control).GetMapAsync(this);
}
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (this.Element == null || this.Control == null)
return;
if (e.PropertyName == CustomMap.RouteCoordinatesProperty.PropertyName)
{
UpdatePolyLine();
}
}
private void UpdatePolyLine()
{
if (polyline != null)
{
polyline.Remove();
polyline.Dispose();
}
var polylineOptions = new PolylineOptions();
polylineOptions.InvokeColor(0x66FF0000);
foreach (var position in ((CustomMap)this.Element).RouteCoordinates)
{
polylineOptions.Add(new LatLng(position.Latitude, position.Longitude));
}
polyline = map.AddPolyline(polylineOptions);
}
public void OnMapReady(GoogleMap googleMap)
{
map = googleMap;
UpdatePolyLine();
}
}
So, for the last change, in my MapPage.xaml.cs I made changes in the callbackDirections as you explained (I hope I did good)
private async void callbackDirections(Object obj, string str)
{
if (obj != null)
{
Device.BeginInvokeOnMainThread(() =>
{
DirectionMap directionMap = obj as DirectionMap;
var list = new List<Position>(customMap.RouteCoordinates);
foreach (Step step in directionMap.steps)
{
list.Add(directionMap.address_end.position);
System.Diagnostics.Debug.WriteLine("add step");
}
System.Diagnostics.Debug.WriteLine("last step");
customMap.RouteCoordinates = list;
System.Diagnostics.Debug.WriteLine("finished?");
});
}
else
{
System.Diagnostics.Debug.WriteLine(str);
}
}
The map is still doesn't display the polyline :/ I only made these changes, I didn't change anything else from my previous code.
I didn't tell you, but I'm not an expert in MVVM binding, so if I forget something, I'm sorry :/
EDIT 2
So after your answer and some read, read and re-read of your answer, there is my "test code" in MapPage.xaml.cs
public MapPage()
{
InitializeComponent();
//HttpRequest.getDirections(origin, destination, callbackDirections);
Device.BeginInvokeOnMainThread(() =>
{
customMap.RouteCoordinates = new List<Position>
{
new Position (37.797534, -122.401827),
new Position (37.776831, -122.394627)
};
});
//setupMap();
//setupMapCustom();
}
Because it doesn't works (for me), I took a look at my code and then, I saw that public static readonly BindableProperty RouteCoordinatesProperty =
BindableProperty.Create<CustomMap, List<Position>>(
p => p.RouteCoordinates, new List<Position>()); was deprecated..
So I red on this post a different way to implement this binding, but it also said that this way is deprecated SEE HERE... I also saw some tutorials about binding which says that they put some code into their xaml, let me remember you mine
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:NAMESPACE;assembly=NAMESPACE"
x:Class="NAMESPACE.Controlers.MapPage">
<ContentPage.Content>
<local:CustomMap x:Name="customMap"/>
</ContentPage.Content>
</ContentPage>
I'm not using something as ItemSource="{PolylineBindable}"
The custom renderer from the example is not made for dynamic updating the path. It is just implemented for the case, where all points of the paths are known before initializing the map / drawing the path the first time. So you have this race condition, you ran into, because you are loading the directions from a web service.
So you have to do some changes:
RouteCoordinates must be a BindableProperty
public class CustomMap : Map
{
public static readonly BindableProperty RouteCoordinatesProperty =
BindableProperty.Create<CustomMap, List<Position>>(p => p.RouteCoordinates, new List<Position>());
public List<Position> RouteCoordinates
{
get { return (List<Position>)GetValue(RouteCoordinatesProperty); }
set { SetValue(RouteCoordinatesProperty, value); }
}
public CustomMap ()
{
RouteCoordinates = new List<Position>();
}
}
Update the Polyline whenever the coordinates change
Move the creation of the polyline from OnMapReady to UpdatePolyLine
call UpdatePolyLine from OnMapReady and OnElementPropertyChanged
public class CustomMapRenderer : MapRenderer, IOnMapReadyCallback
{
GoogleMap map;
Polyline polyline;
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<View> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
// Unsubscribe
}
if (e.NewElement != null)
{
((MapView)Control).GetMapAsync(this);
}
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (this.Element == null || this.Control == null)
return;
if (e.PropertyName == CustomMap.RouteCoordinatesProperty.PropertyName)
{
UpdatePolyLine();
}
}
private void UpdatePolyLine()
{
if (polyline != null)
{
polyline.Remove();
polyline.Dispose();
}
var polylineOptions = new PolylineOptions();
polylineOptions.InvokeColor(0x66FF0000);
foreach (var position in ((CustomMap)this.Element).RouteCoordinates)
{
polylineOptions.Add(new LatLng(position.Latitude, position.Longitude));
}
polyline = map.AddPolyline(polylineOptions);
}
public void OnMapReady(GoogleMap googleMap)
{
map = googleMap;
UpdatePolyLine();
}
}
Setting the data
Updating the positions changes a bit. Instead of adding the positions to the existing list, you have to (create a new list) and set it to RouteCoordinates. You can use Device.BeginInvokeOnMainThread to ensure, that the operation is performed on the UI thread. Else the polyline will not update.
Device.BeginInvokeOnMainThread(() =>
{
customMap.RouteCoordinates = new List<Position>
{
new Position (37.797534, -122.401827),
new Position (37.776831, -122.394627)
};
})
In your case it's something like
var list = new List<Position>(customMap.RouteCoordinates);
list.Add(directionMap.address_end.position);
customMap.RouteCoordinates = list;
Todo
On iOS you have now to implement a similar behavior (like UpdatePolyLine)
Note
That might not the most performant implementation, because you redraw everything instead of adding one point. But it's fine as long as you have no performance issues :)
I followed the tutorial available on Xamarin Docs and it worked for me with some changes based on #Sven-Michael Stübe answer
I load the coordinates from a WebService and then I create a separate List, and after this, I set the new list to the RouteCoordinates property on Custom Map.
Some changes are made on Android Renderer
I'm using MVVM.
CustomMap Class:
public static readonly BindableProperty RouteCoordinatesProperty =
BindableProperty.Create(nameof(RouteCoordinates), typeof(List<Position>), typeof(CustomMap), new List<Position>(), BindingMode.TwoWay);
public List<Position> RouteCoordinates
{
get { return (List<Position>)GetValue(RouteCoordinatesProperty); }
set { SetValue(RouteCoordinatesProperty, value); }
}
public CustomMap()
{
RouteCoordinates = new List<Position>();
}
ViewModel (Codebehind, in your case):
private async void LoadCoordinates(string oidAula, CustomMap mapa)
{
IsBusy = true;
var percurso = await ComunicacaoServidor.GetPercurso(oidAula); // Get coordinates from WebService
var pontos = percurso.Select(p => new Position(p.Latitude, p.Longitude)).ToList(); // Create coordinates list from webservice result
var latitudeMedia = percurso[percurso.Count / 2].Latitude;
var longitudeMedia = percurso[percurso.Count / 2].Longitude;
mapa.RouteCoordinates = pontos;
mapa.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(latitudeMedia, longitudeMedia), Distance.FromMiles(1.0)));
IsBusy = false;
}
XAML:
<maps:CustomMap
AbsoluteLayout.LayoutFlags = "All"
AbsoluteLayout.LayoutBounds = "0, 0, 1, 1"
VerticalOptions = "FillAndExpand"
HorizontalOptions = "FillAndExpand"
x:Name = "PercursoMapa" />
Android Renderer:
public class CustomMapRenderer : MapRenderer
{
bool isDrawn;
protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
// Unsubscribe
}
if (e.NewElement != null)
Control.GetMapAsync(this);
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if ((e.PropertyName == "RouteCoordinates" || e.PropertyName == "VisibleRegion") && !isDrawn)
{
var polylineOptions = new PolylineOptions();
polylineOptions.InvokeColor(0x66FF0000);
var coordinates = ((CustomMap)Element).RouteCoordinates;
foreach (var position in coordinates)
polylineOptions.Add(new LatLng(position.Latitude, position.Longitude));
NativeMap.AddPolyline(polylineOptions);
isDrawn = coordinates.Count > 0;
}
}
}
This example have more than 3600 points of location and the polyline shows correctly on device:
Screenshot
Building on these answers, here is what I did to get it to work on iOS. This allows changing the route even after the map is loaded, unlike the Xamarin sample.
Firstly, custom map class as per #Sven-Michael Stübe with the update from #Emixam23:
public class CustomMap : Map
{
public static readonly BindableProperty RouteCoordinatesProperty =
BindableProperty.Create(nameof(RouteCoordinates), typeof(List<Position>), typeof(CustomMap), new List<Position>(), BindingMode.TwoWay);
public List<Position> RouteCoordinates
{
get { return (List<Position>)GetValue(RouteCoordinatesProperty); }
set { SetValue(RouteCoordinatesProperty, value); }
}
public CustomMap()
{
RouteCoordinates = new List<Position>();
}
}
Next, the iOS custom renderer:
[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace KZNTR.iOS
{
public class CustomMapRenderer : MapRenderer
{
MKPolylineRenderer polylineRenderer;
CustomMap map;
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if ((this.Element == null) || (this.Control == null))
return;
if (e.PropertyName == CustomMap.RouteCoordinatesProperty.PropertyName)
{
map = (CustomMap)sender;
UpdatePolyLine();
}
}
[Foundation.Export("mapView:rendererForOverlay:")]
MKOverlayRenderer GetOverlayRenderer(MKMapView mapView, IMKOverlay overlay)
{
if (polylineRenderer == null)
{
var o = ObjCRuntime.Runtime.GetNSObject(overlay.Handle) as MKPolyline;
polylineRenderer = new MKPolylineRenderer(o);
//polylineRenderer = new MKPolylineRenderer(overlay as MKPolyline);
polylineRenderer.FillColor = UIColor.Blue;
polylineRenderer.StrokeColor = UIColor.Red;
polylineRenderer.LineWidth = 3;
polylineRenderer.Alpha = 0.4f;
}
return polylineRenderer;
}
private void UpdatePolyLine()
{
var nativeMap = Control as MKMapView;
nativeMap.OverlayRenderer = GetOverlayRenderer;
CLLocationCoordinate2D[] coords = new CLLocationCoordinate2D[map.RouteCoordinates.Count];
int index = 0;
foreach (var position in map.RouteCoordinates)
{
coords[index] = new CLLocationCoordinate2D(position.Latitude, position.Longitude);
index++;
}
var routeOverlay = MKPolyline.FromCoordinates(coords);
nativeMap.AddOverlay(routeOverlay);
}
}
}
And finally, adding a polyline to the map:
Device.BeginInvokeOnMainThread(() =>
{
customMap.RouteCoordinates.Clear();
var plist = new List<Position>(customMap.RouteCoordinates);
foreach (var point in track.TrackPoints)
{
plist.Add(new Position(double.Parse(point.Latitude, CultureInfo.InvariantCulture), double.Parse(point.Longitude, CultureInfo.InvariantCulture)));
}
customMap.RouteCoordinates = plist;
var firstpoint = (from pt in track.TrackPoints select pt).FirstOrDefault();
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(double.Parse(firstpoint.Latitude, CultureInfo.InvariantCulture), double.Parse(firstpoint.Longitude, CultureInfo.InvariantCulture)), Distance.FromMiles(3.0)));
});
Not sure if this is the best way to do it, or the most efficient, I don't know much about renderers, but it does seem to work.
So after lot of searches and, of course, the answer of #Sven-Michael Stübe, you can have your proper maps which works on each platform "Android, iOS, WinPhone". Follow my code, then edit it following the #Sven-Michael Stübe's answer.
Once you finished everything, it could works (like for #Sven-Michael Stübe), but it also couldn't work (like for me). If it doesn't works, try to change the following code:
public static readonly BindableProperty RouteCoordinatesProperty =
BindableProperty.Create<CustomMap, List<Position>>(
p => p.RouteCoordinates, new List<Position>());
by
public static readonly BindableProperty RouteCoordinatesProperty =
BindableProperty.Create(nameof(RouteCoordinates), typeof(List<Position>), typeof(CustomMap), new List<Position>(), BindingMode.TwoWay);
See the documentation for more information about it. (Deprecated implementation)
Then the code works !
PS: You can have some troubles with the polyline at the end, which not following the road right, I'm working on it.
PS2: I'll also make a video to explain how to code your customMap to don't have to install a NuGet package, to be able to edit everything at the end ! (The first one will be in French, the second in English, this post will be edited when the video will be made)
Thank angain to #Sven-Michael Stübe !! Thank to up his answer as well :)
I'm using Prism 6. I have a custom RegionAdapter for (AvalonDock) LayoutDocumentPane. I'm using it like this:
<!-- relevant lines from Shell.xaml. These regions are autoWired -->
<ad:LayoutDocumentPaneGroup>
<ad:LayoutDocumentPane prism:RegionManager.RegionName="{x:Static inf:RegionNames.ContentRegion}">
</ad:LayoutDocumentPane>
</ad:LayoutDocumentPaneGroup>
...
<ContentControl prism:RegionManager.RegionName={x:Static inf:RegionNames.TestRegion}">
...
My RegionAdapter:
public class AvalonDockLayoutDocumentRegionAdapter : RegionAdapterBase<LayoutDocumentPane>
{
public AvalonDockLayoutDocumentRegionAdapter(IRegionBehaviorFactory factory) : base(factory)
{
}
protected override void Adapt(IRegion region, LayoutDocumentPane regionTarget)
{
region.Views.CollectionChanged += (sender, e) =>
{
OnRegionViewsCollectionChanged(sender, e, region, regionTarget);
};
}
private void OnRegionViewsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e, IRegion region, LayoutDocumentPane regionTarget)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (var item in e.NewItems)
{
var view = item as FrameworkElement;
if (view != null)
{
var layoutDocument = new LayoutDocument();
layoutDocument.Content = view;
var vm = view.DataContext as ILayoutPaneAware;
if (vm != null)
{
//todo bind to vm.Title instead
layoutDocument.Title = vm.Title;
}
regionTarget.Children.Add(layoutDocument);
layoutDocument.IsActive = true;
}
}
} else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (var item in e.OldItems)
{
var frameworkElement = item as FrameworkElement;
var childToRemove = frameworkElement.Parent as ILayoutElement;
regionTarget.RemoveChild(childToRemove);
}
}
}
protected override IRegion CreateRegion()
{
return new Region();
}
}
And of course I register it with the Bootstrapper
...
protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
{
var mappings = base.ConfigureRegionAdapterMappings();
mappings.RegisterMapping(typeof(LayoutDocumentPane), Container.Resolve<AvalonDockLayoutDocumentRegionAdapter>());
return mappings;
}
protected override void InitializeShell()
{
var regionManager = RegionManager.GetRegionManager(Shell);
// Here, regionManager.Regions only contains 1 Region - "TestRegion".
// Where is my region from the custom RegionAdapter?
Application.Current.MainWindow.Show();
}
protected override DependencyObject CreateShell()
{
return Container.Resolve<Shell>();
}
protected override void ConfigureModuleCatalog()
{
ModuleCatalog moduleCatalog = (ModuleCatalog)ModuleCatalog;
moduleCatalog.AddModule(typeof(HelloWorldModule.HelloWorldModule));
}
...
And my Module
...
public HelloWorldModule(IRegionManager regionManager, IUnityContainer container)
{
_regionManager = regionManager;
_container = container;
}
public void Initialize()
{
_container.RegisterTypeForNavigation<HelloWorldView>("HelloWorldView");
// When uncommented, this next line works even though the region
// with this name doesn't appear in the list of regions in _regionManager
//_regionManager.RegisterViewWithRegion(RegionNames.ContentRegion, typeof(HelloWorldView));
}
...
Now, see that in the Bootstrapper.InitializeShell call, and the HelloWorldModule.Initialize call, I only have 1 region in the RegionManager - "TestRegion". If I registerViewWithRegion to my "ContentRegion" it puts an instance of the view in that region even though it's not listed in the Regions.
If I attempt to navigate from an ICommand function in my ShellViewModel (on a button click for instance) I can navigate to something in the TestRegion but not the ContentRegion. It seems I cannot navigate to any region created by my custom RegionAdapter. What am I missing?
most probably your code below is causing you the issue.
protected override IRegion CreateRegion()
{
return new Region();
}
Try changing to return a region which can host multiple active views
protected override IRegion CreateRegion()
{
return new AllActiveRegion();
}
I saw this in your issue on GitHub.
Depending on how the control is created, you may have to set the Prism RegionManager on the control yourself via something like:
private readonly IRegionManager _regionManager;
public AvalonDockLayoutDocumentRegionAdapter(
IRegionBehaviorFactory regionBehaviorFactory,
IRegionManager regionManager
) : base( regionBehaviorFactory ) {
this._regionManager = regionManager;
}
protected override void Adapt( IRegion region, LayoutDocumentPane target ) {
RegionManager.SetRegionManager( target, this._regionManager );
// continue with Adapt
}