Add pin on click Xamarin.Forms.Maps - c#

I want to add a new pin on clicking on the map using Xamarin.Forms.Maps.
After searching , I found that I have to use TKCustomMap plugin .. but it didn't show on the map .. just empty area
and this is my code
double lit = 2.394;// double.Parse(Center.CenterLocationX);
double longt = 43.2352;// double.Parse(Center.CenterLocationY);
TK.CustomMap.Position position = new TK.CustomMap.Position(lit, longt);
TK.CustomMap.MapSpan span = TK.CustomMap.MapSpan.FromCenterAndRadius(position, TK.CustomMap.Distance.FromMiles(0.5));
TK.CustomMap.TKCustomMap map = new TK.CustomMap.TKCustomMap(span);
map.IsShowingUser = true;
map.MapType = TK.CustomMap.MapType.Street;
TK.CustomMap.TKCustomMapPin pin = new TK.CustomMap.TKCustomMapPin()
{
//Address = "Test",
//Label = "Test",
Position = position,
IsDraggable = true
//Type = PinType.SearchResult
};
map.MapClicked += (x, y) =>
{
SharedTools.MakeToast("Clicked");
};
//map.Pins.Add(pin);
map.Pins = new List<TK.CustomMap.TKCustomMapPin>() { pin };
map.MoveToMapRegion(span);
layout.Content = map;
I want to solve this, or any other idea to add pin on click

I used your code in my demo, i got the result like the following screenshot(If you cannot see the band of google, you should check the API_KEY, if it is correct.)
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="API_KEY" />
Then i changed the lit to 37, longt to -122 and add pin on click.I can see the map and get the following result. Please check your lit and longt, if the value is legal
There is my code.
public partial class MainPage : ContentPage
{
TK.CustomMap.TKCustomMap map;
TK.CustomMap.Position position;
public MainPage()
{
InitializeComponent();
//37,-122
double lit = 37;// double.Parse(Center.CenterLocationX);
double longt = -122;// double.Parse(Center.CenterLocationY);
position = new TK.CustomMap.Position(lit, longt);
TK.CustomMap.MapSpan span = TK.CustomMap.MapSpan.FromCenterAndRadius(position, TK.CustomMap.Distance.FromMiles(0.5));
map = new TK.CustomMap.TKCustomMap(span);
map.IsShowingUser = true;
map.MapType = TK.CustomMap.MapType.Street;
map.MapClicked += OnMapClicked;
Content = map;
}
private void OnMapClicked(object sender, TKGenericEventArgs<Position> e)
{
TK.CustomMap.TKCustomMapPin pin = new TK.CustomMap.TKCustomMapPin()
{
//Address = "Test",
//Label = "Test",
Position = position
,
IsDraggable = true
//Type = PinType.SearchResult
};
map.Pins = new List<TK.CustomMap.TKCustomMapPin>() { pin };
}
}
Here is my demo.Hope this can help you.
https://github.com/851265601/TKGoogleMapsDemo

Related

How to check if dynamic checkbox are checked

I've an application to import some pictures from a folder into another. I use picturebox to show my pictures and have a checkbox next to it. If it's unchecked i dont wanna import them.
So here is my code for creating a checkbox :
public void CreateCheckBox(Form formInstance,int yLocation, int xLocation, int iNumber)
{
CheckBox box = new CheckBox();
box.Name = "cbxName" + iNumber.ToString();
box.Location = new Point(xLocation+40,yLocation+90);
box.Visible = true;
box.Enabled = true;
box.Checked = true;
box.CheckedChanged += new EventHandler(cbx_CheckedChange);
formInstance.Controls.Add(box);
}
And my pictureBox :
public void CreatePictureBox(Form formInstance,int iNumber)
{
string[] tNomImage = RecupererNomImage();
PictureBox pbxImage = new PictureBox();
pbxImage.Name = "pbxName" + iNumber.ToString();
pbxImage.Image = Image.FromFile(tNomImage[iNumber]);
pbxImage.Width = 90;
pbxImage.Height = 90;
pbxImage.Location = new Point(iXLocation, iYLocation);
pbxImage.Visible = true;
pbxImage.BorderStyle = BorderStyle.FixedSingle;
pbxImage.SizeMode = PictureBoxSizeMode.Zoom;
formInstance.Controls.Add(pbxImage);
pbxImage.Enabled = false;
CreateCheckBox(this, iYLocation, iXLocation, iNumber);
if (iXLocation+iXSpacing*2 > this.Width)
{
iXLocation = XLOCATION;
iYLocation += iXSpacing;
}
else
{
iXLocation += iXSpacing;
}
And I wanna know which checkbox is checked so I can export the picture next to it.
I presume a picturebox will have a name like:
pbxName141
And its matching checkbox will have a name like:
cbxName141
You can ask the form for all the checked boxes:
var cbs = formInstance.Controls.OfType<CheckBox>().Where(cb => cb.Checked);
You can convert the checkbox name into the related picturebox name and look up the picturebox by name:
foreach(var cb in cbs){
var pbName = "p" + cb.Name.Substring(1);
var pb = formInstance.Controls[pbName];
}
So many ways to skin this cat..
Change your methods so that they RETURN the control that was created:
public CheckBox CreateCheckBox(Form formInstance,int yLocation, int xLocation, int iNumber)
{
// ... existing code ...
return box;
}
Now you can store a reference to that CheckBox in the Tag() property of the PictureBox:
public PictureBox CreatePictureBox(Form formInstance,int iNumber)
{
// ... existing code ...
CheckBox cb = CreateCheckBox(this, iYLocation, iXLocation, iNumber);
pbxImage.Tag = cb;
// ... existing code ...
return pbxImage;
}
Finally, add all of those returned PictureBoxes to a List<PictureBox> so you can easily reference and iterate over them. Simply cast the control stored in the Tag() property back to a CheckBox and you can determine if each PictureBox should be imported or not.
List<CheckBox> c = Controls.OfType<CheckBox>().Cast<CheckBox>().ToList();
forech(CheckBox item in c){
if(c.checked){
}
}

UISearchBar not resizing on phone rotation

I am having an issue where my UISearchBar does not resize on phone rotation unless I touch on the search bar so that it has focus (see images below).
The search bar is created and added to a UIMapView as a subview. See code.
Searchbar creation:
public UISearchController DefineSearchController()
{
_searchResultsController = new SearchResultsVC(_mapView);
_searchResultsController.searchItemSelected += PlaceSelect;
_searchUpdater = new SearchResultsUpdator();
_searchUpdater.UpdateSearchResults += _searchResultsController.Search;
//add the search controller
var searchController = new UISearchController(_searchResultsController)
{
SearchResultsUpdater = _searchUpdater
};
var scb = searchController.SearchBar;
scb.SizeToFit();
scb.SearchBarStyle = UISearchBarStyle.Minimal;
var img = UIImage.FromBundle("tabSpace");
scb.SetBackgroundImage(img, UIBarPosition.Top, UIBarMetrics.Default);
var textField = scb.ValueForKey(new NSString("searchField")) as UITextField;
if (textField != null)
{
var backgroundView = textField.Subviews[0];
if (backgroundView != null)
{
backgroundView.BackgroundColor = UIColor.White;
backgroundView.Layer.BorderColor = AppColour.PersianBlue.GetUIColour().CGColor;
backgroundView.Layer.BorderWidth = 1;
backgroundView.Layer.CornerRadius = 10;
backgroundView.ClipsToBounds = true;
}
}
var localEnterPoI = NSBundle.MainBundle.LocalizedString("placeHolderSearchForLocation", "Enter a PoI to search for");
scb.Placeholder = localEnterPoI;
searchController.Delegate = new SearchControllerDelegate();
searchController.HidesNavigationBarDuringPresentation = false;
return searchController;
}
Added to the subview:
//Define Search Controller
_mapSearchManager = new MapSearchManager(_mapView);
_searchController = _mapSearchManager.DefineSearchController();
var scb = _searchController.SearchBar;
_mapView.AddSubview(scb);
NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[]{
scb.TopAnchor.ConstraintEqualTo(_mapView.TopAnchor, 30),
scb.LeadingAnchor.ConstraintEqualTo(_mapView.LeadingAnchor, 10),
scb.TrailingAnchor.ConstraintEqualTo(_mapView.LeadingAnchor, -10),
});
I heave search extensively and was only able to find one similar issue:
UISearchBar doesn't resize when frame is resized in IOS 11
I implementing both of suggestion but it didn't make any difference.
Has anyone else encounted this or know what a possible solution might be.
Cheers

How to add multiple makers on Gmap in c#

I have a text file with a list of GPS coordinates. I am trying to place a marker on each of the coordinates from the document. The problem is that the lengths of the documents change and the way I have it, the marker gets replaced with every iteration. How do I add a marker for each lat/lon point?
Here's the relevant code:
private GMapOverlay gMapOverlay;
private GMapMarker marker;
gmap.MapProvider = GMap.NET.MapProviders.GoogleMapProvider.Instance;
gmap.MinZoom = 2;
gmap.MaxZoom = 25;
gmap.Zoom = 5;
gmap.ShowCenter = false;
gmap.DragButton = MouseButtons.Left;
//setup the map overlay for displaying routes/points
gMapOverlay = new GMapOverlay("Path");
gmap.Overlays.Add(gMapOverlay);
gMapOverlay.Markers.Clear();
gMapOverlay.Routes.Clear();
//GMarkerGoogle marker = new GMarkerGoogle(new PointLatLng(0, 0), GMarkerGoogleType.green);
marker = new GMarkerGoogle(new PointLatLng(0, 0), GMarkerGoogleType.green);
marker.IsVisible = false;
marker.ToolTipMode = MarkerTooltipMode.OnMouseOver;
marker.ToolTipText = "Starting Point";
gMapOverlay.Markers.Add(marker);
private void btn_KMLFile_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog4.ShowDialog();
if (result == DialogResult.OK)
{
string filename = openFileDialog4.FileName;
string[] lines = System.IO.File.ReadAllLines(filename);
foreach (string line in lines)
{
string[] Data_Array = line.Split(',');
Double londecimal = Convert.ToDouble(Data_Array[0]);
Double latdecimal = Convert.ToDouble(Data_Array[1]);
marker.Position = new PointLatLng(latdecimal, londecimal);
marker.IsVisible = true;
gmap.Update();
}
}
}
private void openFileDialog4_FileOk(object sender, CancelEventArgs e)
{
OpenFileDialog openFileDialog4 = new OpenFileDialog();
}
The markers can go into the Markers collection:
public readonly ObservableCollection<GMapMarker> Markers;
Just add the markers to the collection as you do with your single marker.
EDIT
I was assuming a WPF client, so there's no Observable Collection if you are using WinForms. Have you tried to add a new marker to the collection as you do with your original marker? So in your loop:
string[] Data_Array = line.Split(',');
Double londecimal = Convert.ToDouble(Data_Array[0]);
Double latdecimal = Convert.ToDouble(Data_Array[1]);
// add a new one here
var marker = new GMarkerGoogle(new PointLatLng(latdecimal, londecimal), GMarkerGoogleType.green);
marker.IsVisible = true;
gMapOverlay.Markers.Add(marker);
I can fix with using list
List<GMapMarker> lMarks = new List<GMapMarker>();
int[] SelectedRows = gvProjects.GetSelectedRows();
map.Overlays.Clear();
GMapOverlay markers = new GMapOverlay("markers");
for (int i = 0; i < SelectedRows.Length; i++)
{
if (SelectedRows[i] >= 0)
{
double lat = Convert.ToDouble(gvProjects.GetRowCellValue(i-2,"Altitude"));
double lng = Convert.ToDouble(gvProjects.GetRowCellValue(i-2, "Longitude"));
PointLatLng point = new PointLatLng(lat, lng);
GMapMarker marker = new GMarkerGoogle(new PointLatLng(lat,lng),GMarkerGoogleType.yellow_pushpin);
marker.ToolTipMode = MarkerTooltipMode.Always;
marker.Tag = gvProjects.GetRowCellValue(i-2, "ID").ToString();
marker.ToolTipText = gvProjects.GetRowCellValue(i-2, "ProjectName").ToString();
lMarks.Add(marker);
}
}
markers.Markers.AddRange(lMarks);
map.Overlays.Add(markers);

How do I make a pie-in-pie chart with MSChart?

I've downloaded MS Chart samples and in the gallery it shows a "3DPieInPie.png", which is what I want - but can't see any code to create it!!
Presumably it's ChartType = SeriesChartType.Pie ... but is there another setting that specifies I want the second pie? And how do enter the second set of data? - I've tried adding a new series, but it seems to be ignored.
This type of diagram is called nested pie chart, or multilevel pie chart.
It is done by creating two ChartArea - pie chart and donut chart,
which are correctly placed one relative to the other.Here is code below.
public partial class Form1 : Form
{
public class DataInt {
public string Label { get; set; }
public int Value { get; set; } }
public Form1()
{
InitializeComponent();
pieChart.Series.Clear();
pieChart.Legends.Clear();
float baseDoughnutWidth = 25;
float outerSize = 80;
ChartArea outerArea = new ChartArea("OUTER_AREA");
outerArea.Position = new ElementPosition(0, 10, 100, 100);
outerArea.InnerPlotPosition = new ElementPosition((100 - outerSize) / 2, (100 - outerSize) / 2, outerSize, outerSize);
outerArea.BackColor = Color.Transparent;
pieChart.ChartAreas.Add(outerArea);
float innerSize = 53;
ChartArea innerArea = new ChartArea("INNER_AREA");
innerArea.Position = new ElementPosition(0, 5, 100, 100);
ElementPosition innerPos = new ElementPosition((100 - innerSize) / 2, ((100 - innerSize) / 2), innerSize, innerSize+5);
innerArea.InnerPlotPosition = innerPos;
innerArea.BackColor = Color.Transparent;
pieChart.ChartAreas.Add(innerArea);
Series outerSeries = new Series("OUTER_SERIES");
outerSeries.ChartArea = "OUTER_AREA";
outerSeries.ChartType = SeriesChartType.Doughnut;
outerSeries["DoughnutRadius"] = Math.Min(baseDoughnutWidth * (100 / outerSize), 99).ToString().Replace(",", ".");
Series innerSeries = new Series("INNER_SERIES");
innerSeries.ChartArea = "INNER_AREA";
innerSeries.ChartType = SeriesChartType.Pie;
var innerData = new List<DataInt> { new DataInt { Label = "A", Value = 7 },
new DataInt { Label = "B", Value = 14 }, new DataInt{Label="C",Value=19},
new DataInt{Label="D",Value=12}, new DataInt{Label="E",Value=20},
new DataInt{Label="F",Value=28} };
var outerData = new List<DataInt> { new DataInt { Label = "Gold", Value = 21 },
new DataInt{Label="Red",Value=31}, new DataInt { Label = "Blue", Value = 48 } };
innerSeries.Points.DataBindXY(innerData, "Label", innerData, "Value");
outerSeries.Points.DataBindXY(outerData, "Label", outerData, "Value");
pieChart.Series.Add(innerSeries);
pieChart.Series.Add(outerSeries);
Legend legend = new Legend("pieChartLegend")
{
Font=new System.Drawing.Font("Arial",14.0f),
Alignment = StringAlignment.Center,
Docking = Docking.Top,
Enabled = true,
IsDockedInsideChartArea = false,
TableStyle = LegendTableStyle.Wide,
};
pieChart.Legends.Add(legend);
foreach (Series sr in pieChart.Series)
{
sr.Legend = "pieChartLegend";
}
var outerAreaColors = new List<Color>(){Color.Gold,Color.Red, Color.DeepSkyBlue };
var innerAreaColors = new List<Color>() {Color.Goldenrod,Color.DarkGoldenrod, Color.DarkRed, Color.Firebrick,Color.DodgerBlue, Color.SteelBlue };
for (int i = 0; i < outerSeries.Points.Count; i++)
{
outerSeries.Points[i].Color = outerAreaColors[i];
}
for (int i = 0; i < innerSeries.Points.Count; i++)
{
innerSeries.Points[i].Color = ChartColorPallets.Inner[i];
}
int inclination = 20;
int rotation = 45;
bool enable3d = true;
pieChart.ChartAreas["OUTER_AREA"].Area3DStyle.Enable3D = enable3d;
pieChart.ChartAreas["OUTER_AREA"].Area3DStyle.Inclination = inclination;
pieChart.ChartAreas["OUTER_AREA"].Area3DStyle.Rotation = rotation;
pieChart.ChartAreas["INNER_AREA"].Area3DStyle.Enable3D = enable3d;
pieChart.ChartAreas["INNER_AREA"].Area3DStyle.Inclination = inclination;
pieChart.ChartAreas["INNER_AREA"].Area3DStyle.Rotation = rotation;
}
}
Check out these answers. They also include some sample code:
http://social.msdn.microsoft.com/Forums/en-US/MSWinWebChart/thread/54b4dbb7-1622-4798-8b6a-ef4f01e48c31/
http://support2.dundas.com/default.aspx?article=1115
http://support2.dundas.com/Default.aspx?article=1114

How to Change Content of Button if it is a child of a grid?

I want to change content of button1 on click event of button2 . But not able to get the object of grid's child Button class which is in List<> UiList.
Please Guide me in getting the right approach to look it and solve it . And also guide that if the object is build in runtime then how to access it ?
public partial class MainPage : PhoneApplicationPage
{
List<Grid> UIList = new List<Grid>();
Grid objGrid1 = null;
Button objButton1 = null;
Button objButton2 = null;
// Constructor
public MainPage()
{
InitializeComponent();
createGrid1("grid1");
createButton2("Button2");
}
public void createGrid1(string x)
{
objGrid1 = new Grid();
objGrid1.Height = 100;
objGrid1.Name = x;
objGrid1.Width = 200;
objGrid1.Margin = new Thickness(100, 100, 0, 0);
objGrid1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
objGrid1.VerticalAlignment = System.Windows.VerticalAlignment.Top;
objGrid1.Background = new SolidColorBrush(Colors.Orange);
createButton1("changename");
}
public void createButton1(string _name)
{
objButton1 = new Button();
objButton1.Height = 90;
objButton1.Name = _name;
objButton1.Content="Button1";
objButton1.FontSize = 20;
objButton1.Width = 190;
objButton1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
objButton1.VerticalAlignment = System.Windows.VerticalAlignment.Top;
objButton1.Background = new SolidColorBrush(Colors.Blue);
objButton1.Foreground = new SolidColorBrush(Colors.White);
objGrid1.Children.Add(objButton1);
LayoutRoot.Children.Add(objGrid1);
UIList.Add(objGrid1);
}
public void createButton2(string _name)
{
objButton2 = new Button();
objButton2.Margin = new Thickness(240, 300, 0, 0);
objButton2.Name = _name;
objButton2.Height = 90;
objButton2.Content = "Button2";
objButton2.FontSize = 20;
objButton2.Width = 190;
objButton2.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
objButton2.VerticalAlignment = System.Windows.VerticalAlignment.Top;
objButton2.Background = new SolidColorBrush(Colors.Blue);
objButton2.Foreground = new SolidColorBrush(Colors.White);
LayoutRoot.Children.Add(objButton2);
objButton2.Click += (s, e) =>
{
int c = UIList.ElementAt(0).Children.Count;
if (c == 1)
{
//logic to change content of Button1 on click of Button2
}
};
}
}
Assuming you cannot just keep a reference to the created control, such as in a class field, you can iterate through the Children property of the Grid and find the desired Button. If there are multiple buttons, you can differentiate them using the Tag property.
Once you find it, change the contents of the button using the Content property, as discussed in the contents above.

Categories

Resources