Unable to center map on a specific location - c#

I'm trying to center a map on a custom location with the following code:
mapView = new MapKit.MKMapView();
mapView.ZoomEnabled = true;
mapView.ScrollEnabled = true;
mapDelegate = new GeoFleet.iOS.MapDelegate();
mapView.Delegate = mapDelegate;
var region = new MapKit.MKCoordinateRegion(
new CLLocationCoordinate2D(latitude: 43.6114099, longitude: 7.0817283),
new MapKit.MKCoordinateSpan(0.00899321605918731, 0.0124209769840958)
);
this.mapView.Region = region;
Unfortunately, this displays me the map of France; not the country's south east location I'm requesting.
How can I debug this kind of problem?
EDIT:
You can go to the location with the following link.
I've tried this other call which does neither work:
MapKit.MKCoordinateRegion.FromDistance(new CLLocationCoordinate2D(latitude: 43.6114099, longitude: 7.0817283), 2000, 2000);

this works for me
public partial class ViewController : UIViewController
{
MKMapView map;
UIButton btn;
public ViewController(IntPtr handle) : base(handle)
{
map = new MKMapView(this.View.Bounds);
this.View.AddSubview(map);
btn = new UIButton(UIButtonType.RoundedRect);
btn.SetTitle("GO!!!",UIControlState.Normal);
btn.TouchDown += Btn_TouchDown;
btn.Frame = new CoreGraphics.CGRect(100,200,50,50);
this.View.AddSubview(btn);
}
private void Btn_TouchDown(object sender, EventArgs e)
{
this.map.Region = new MapKit.MKCoordinateRegion(
new CLLocationCoordinate2D(latitude: 43.6114099, longitude: 7.0817283),
new MapKit.MKCoordinateSpan(0.00899321605918731, 0.0124209769840958)
);
}
}

Related

How to display a pin on maps

I could display the map on my App interface , and now I'm trying to display a Pin of my current position .
I displayed in but with a button Click that shows me another Content Page . but I couldn't display it on the same page even after clicking that button .
If there's a way to show it , on the same page and without clicking any button , I'll be so thankful .
Here's the code of my Clicked_Button Event , This Code works and when I click it displays a new content page with my current position . but what I want it to to show it in my Map Module in the Main Page,
this is the XAML Code for my map (putting it in a grid):
<maps1:Map Grid.Column="1"
Grid.Row="2"
Grid.RowSpan="2"
Grid.ColumnSpan="3"
x:Name="myMap">
I tried to remove " Content = myMap; " from my back-end code to keep it on the main page , but the pin doesn't show up.
protected async void OnButtonClicked_speed(object sender, EventArgs args)
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
myMap = new Xamarin.Forms.Maps.Map(MapSpan.FromCenterAndRadius(
new Xamarin.Forms.Maps.Position(position.Latitude,position.Longitude),
Distance.FromMiles(0.5)))
{
IsShowingUser = true,
VerticalOptions = LayoutOptions.FillAndExpand
};
var position1 = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);
var pin1 = new Pin
{
Type = PinType.Place,
Position = position1,
Label = "Current Position",
Address = ""
};
myMap.Pins.Add(pin1);
Content = myMap;
}
Content = myMap
this is equivalent to repopulating your current page with a map
so you just move the code out of your OnButtonClicked_speed method.
like this:
in MainPage.xaml.cs
public partial class MainPage : ContentPage
{
private Map myMap;
public MainPage(Position position)
{
InitializeComponent();
myMap.MoveToRegion(MapSpan.FromCenterAndRadius(
new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude),
Distance.FromMiles(0.5)));
myMap.IsShowingUser = true;
myMap.VerticalOptions = LayoutOptions.FillAndExpand;
var position1 = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);
var pin1 = new Pin
{
Type = PinType.Place,
Position = position1,
Label = "Current Position",
Address = ""
};
myMap.Pins.Add(pin1);
}
public static async Task<MainPage> CreateMainPageAsync()
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
MainPage page = new MainPage(position );
return page;
}
}
in App.xaml.cs
public partial class App : Application
{
public App()
{
InitializeComponent();
}
protected override async void OnStart()
{
namespace.MainPage main = await namespace.MainPage.CreateMainPageAsync();
MainPage = main;
}
}

C# GTK# MenuBar isn't displaying

I am trying to learn GTK# (obviously in C#). I am using Ubuntu and I compile with mono. I want to create a MenuBar and add some Menu, and MenuItem to it.
When I compile, all is OK but my menu isn't displaying.
public MainWindow() : base("LayText")
{
SetDefaultSize(800, 600);
SetPosition(WindowPosition.Center);
DeleteEvent += delegate { Application.Quit(); };
this.InitializeComponent();
ShowAll();
}
private void InitializeComponent()
{
this.m_new = new MenuItem("Nouveau fichier");
this.m_open = new MenuItem("Ouvrir fichier");
this.m_exit = new MenuItem("Quitter");
this.file = new Menu();
this.file.Append(this.m_new);
this.file.Append(this.m_open);
this.file.Append(this.m_exit);
this.menu_file = new MenuItem("Fichier");
this.menu_file.Submenu = this.file;
this.menu_bar = new MenuBar();
this.menu_bar.Append(this.menu_file);
this.vbox_princ = new VBox(false, 2);
this.vbox_princ.PackStart(this.menu_bar, false, false, 0);
this.Add(this.vbox_princ);
}
When I compile this code I am getting the window but without the menu I've set.
Screenshot of the window
Thanks for helping me.
Layce17
The following code (just a modification/completion or yours) works perfectly. I see you are using Ubuntu. Though I don't use it, I think it shows the menu bar in the top status bar. Have you checked that out?
using Gtk;
namespace Kk
{
class MainWindow: Gtk.Window {
public MainWindow() : base("LayText")
{
SetDefaultSize(800, 600);
SetPosition(WindowPosition.Center);
DeleteEvent += delegate { Application.Quit(); };
this.InitializeComponent();
ShowAll();
}
private void InitializeComponent()
{
var m_new = new MenuItem("Nouveau fichier");
var m_open = new MenuItem("Ouvrir fichier");
var m_exit = new MenuItem("Quitter");
var file = new Menu();
file.Append(m_new);
file.Append(m_open);
file.Append(m_exit);
var menu_file = new MenuItem("Fichier");
menu_file.Submenu = file;
var menu_bar = new MenuBar();
menu_bar.Append(menu_file);
var vbox_princ = new VBox(false, 2);
vbox_princ.PackStart(menu_bar, false, false, 0);
this.Add(vbox_princ);
}
public static void Main()
{
Application.Init();
new MainWindow();
Application.Run();
}
}
}
Hope this helps.

'System.ArgumentException' occurred in Xamarin.Forms.Platform.UAP.dll

Hi I create xamarin form project and implement MasterDetailPage it was working well without any issues in both android and ios, but i run into UWP project for windows 10 it throw the exception and app crashed. Please find my stacktrace
'System.ArgumentException' occurred in Xamarin.Forms.Platform.UAP.dll
at Windows.Foundation.Size..ctor(Double width, Double height)
at Xamarin.Forms.Platform.UWP.MasterDetailControl.get_DetailSize()
at Xamarin.Forms.Platform.UWP.MasterDetailPageRenderer.UpdateBounds()
at Xamarin.Forms.Platform.UWP.MasterDetailPageRenderer.OnIsPaneOpenChanged(DependencyObject sender, DependencyProperty dp)
at Windows.UI.Xaml.DependencyObject.SetValue(DependencyProperty dp, Object value)
at Xamarin.Forms.Platform.UWP.MasterDetailPageRenderer.UpdateIsPresented()
at Xamarin.Forms.Platform.UWP.MasterDetailPageRenderer.OnElementPropertyChanged(Object sender, PropertyChangedEventArgs e)
at System.ComponentModel.PropertyChangedEventHandler.Invoke(Object sender, PropertyChangedEventArgs e)
at Xamarin.Forms.BindableObject.OnPropertyChanged(String propertyName)
at Xamarin.Forms.Element.OnPropertyChanged(String propertyName)
at Xamarin.Forms.BindableObject.SetValueActual(BindableProperty property, BindablePropertyContext context, Object value, Boolean currentlyApplying, SetValueFlags attributes, Boolean silent)
at Xamarin.Forms.BindableObject.SetValueCore(BindableProperty property, Object value, SetValueFlags attributes, SetValuePrivateFlags privateAttributes)
at Xamarin.Forms.MasterDetailPage.UpdateMasterBehavior(MasterDetailPage page)
My code
public class MasterHomePage : MasterDetailPage, MasterHomePageLisener
{
public MasterHomePage()
{
Title = AppRex.home;
Icon = "hamburger.png";
HomePageItem[] homePageItems =
{
new HomePageItem(AppRex.home, "home_icon.png", typeof(AfterLoginHomePage)),
new HomePageItem(AppRex.changePassword, "change_password_icon.png", typeof(ChangePassword)),
new HomePageItem("Set / Change PIN", "change_pin.png", typeof(LoginPinSetUpPage)),
new HomePageItem(AppRex.customerSuppoert, "support_icon.png", typeof(CustomerSupport)),
new HomePageItem(AppRex.about, "about_icon.png", typeof(AboutPage)),
new HomePageItem(AppRex.checkUpdate, "updates_icon.png", typeof(CheckUpdatedPage)),
new HomePageItem("Tutorial", "video_icon.png", typeof(TutorialVideoPage)),
new HomePageItem(AppRex.logout, "logout_icon.png", null),
};
this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
ListView list = new ListView
{
ItemsSource = homePageItems,
ItemTemplate = new DataTemplate(() =>
{
var imageCell = new LeftMenuCell();
imageCell.SetBinding(LeftMenuCell.TitleProperty, "Name");
imageCell.SetBinding(LeftMenuCell.ImageProperty, "IconSource");
return imageCell;
}),
VerticalOptions = LayoutOptions.FillAndExpand,
};
//Left menu
this.Master = new EgnatiumFull.Views.MyContentPage
{
Title = AppRex.home,
Content = new StackLayout { Children = { new Image() { Source = App.GetLogoImg()} ,
new MyLabel{Text = AppRex.version, HorizontalTextAlignment = TextAlignment.Center},
new MyLabel{Text = App.UserName, FontSize = 24, FontAttributes= FontAttributes.Bold},
new MyLabel{Text = App.UserEmailId},
new BoxView { BackgroundColor = Color.Gray, HeightRequest = 1}, list }
}
};
this.Detail = new AfterLoginHomePage(this);
if (Device.OS == TargetPlatform.WinPhone)
{
(this.Detail as EgnatiumFull.Views.MyContentPage).Content.GestureRecognizers.Add(
new TapGestureRecognizer((view) =>
{
this.IsPresented = true;
}));
}
// Define a selected handler for the ListView.
list.ItemTapped += async(sender, args) =>
{
var homePageItem = ((HomePageItem)args.Item);
var type = homePageItem.TargetType;
if (type == null)
{
if (homePageItem.Name.Equals(AppRex.logout))
{
list.SelectedItem = null;
var resp = await DisplayAlert("","Are you sure want to Logout?","Yes", "No");
if (resp)
{
await App.UpdateLoginStatus(true);
Application.Current.MainPage = App.GetPage();
}
}
}
else {
Page page = null;
if (type.Equals(typeof(AfterLoginHomePage)))
{
page = new AfterLoginHomePage(this);
}
else if (type.Equals(typeof(AboutPage)))
{
page = new AboutPage(this);
}
else if (type.Equals(typeof(ChangePassword)))
{
page = new ChangePassword(this);
}
else if (type.Equals(typeof(LoginPinSetUpPage)))
{
page = new LoginPinSetUpPage(App.UserId, App.UserEmailId, this);
}
else if (type.Equals(typeof(TutorialVideoPage)))
{
page = new TutorialVideoPage(this);
}
else if (type.Equals(typeof(CustomerSupport)))
{
page = new CustomerSupport(this);
}
else if (type.Equals(typeof(CheckUpdatedPage)))
{
page = new CheckUpdatedPage(this);
}
page.Title = ((HomePageItem)args.Item).Name;
Detail = page;
}
// Show the detail page.
this.IsPresented = false;
((ListView)sender).SelectedItem = null;
};
// Initialize the ListView selection.
//list.SelectedItem = homePageItems[0];
}
public void HomeIconClicked()
{
this.Detail = new AfterLoginHomePage(this);
}
public void MenuIconClicked()
{
this.IsPresented = !this.IsPresented;
}
}
public interface MasterHomePageLisener
{
void MenuIconClicked();
void HomeIconClicked();
}

Sharpmap - Print points over map

I've just started using Sharpmap but I have a problem. I'm not able to print points (not even one) over a map using this library.
I didn't find a good example to do it, and my code is not working. It draws a point way too far from where it should be (Madrid, Spain).
I would appreciate some help if someone knows how to use it.
Here is my code :
namespace TestsSharpmapForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
VectorLayer vlay = new VectorLayer("Spain");
vlay.DataSource = new SharpMap.Data.Providers.ShapeFile(#"ESP_adm_shp\ESP_adm2.shp", true);
VectorLayer vlay2 = new VectorLayer("Points");
Collection<GeoAPI.Geometries.IGeometry> geomColl = new Collection<GeoAPI.Geometries.IGeometry>();
//Get the default geometry factory
GeoAPI.GeometryServiceProvider.Instance = new NetTopologySuite.NtsGeometryServices();
GeoAPI.Geometries.IGeometryFactory gf =
GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory();
geomColl.Add(gf.CreatePoint(new GeoAPI.Geometries.Coordinate(40.4177623, -3.6690416)));
vlay2.DataSource = new SharpMap.Data.Providers.GeometryProvider(geomColl);
mapBox1.Map.Layers.Add(vlay);
mapBox1.Map.Layers.Add(vlay2);
//ProjNet.CoordinateSystems.Transformations.CoordinateTransformationFactory ctFact = new ProjNet.CoordinateSystems.Transformations.CoordinateTransformationFactory();
//vlay.CoordinateTransformation = ctFact.CreateFromCoordinateSystems(ProjNet.CoordinateSystems.GeographicCoordinateSystem.WGS84, ProjNet.CoordinateSystems.ProjectedCoordinateSystem.WebMercator);
//vlay.ReverseCoordinateTransformation = ctFact.CreateFromCoordinateSystems(ProjNet.CoordinateSystems.ProjectedCoordinateSystem.WebMercator, ProjNet.CoordinateSystems.GeographicCoordinateSystem.WGS84);
mapBox1.Map.ZoomToExtents();
mapBox1.Refresh();
mapBox1.ActiveTool = SharpMap.Forms.MapBox.Tools.Pan;
Image imgMap = mapBox1.Map.GetMap();
}
private void mapBox1_Click(object sender, EventArgs e)
{
}
}
}
X and Y should be the other way round:
geomColl.Add(gf.CreatePoint(new GeoAPI.Geometries.Coordinate(-3.6690416, 40.4177623)));

How to draw & save a map pushpin from current location to a map? Windows phone

I've started using maps in a Windows phone application and I have figured out how to get the current coordinates but I'm not sure how to draw it as a pushpin on the map.
This is what I have so far which calls a GetCoordinates method and navigates to the map on a button click.Does anyone know how I could pass the coordinates to the map and draw it as a pushpin?
private async Task GetCoordinates(string name = "My Car")
{
await Task.Run(async () =>
{
// Get the phone's current location.
Geolocator MyGeolocator = new Geolocator();
MyGeolocator.DesiredAccuracyInMeters = 5;
Geoposition MyGeoPosition = null;
try
{
MyGeoPosition = await MyGeolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10));
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Location is disabled in phone settings or capabilities are not checked.");
}
catch (Exception ex)
{
// Something else happened while acquiring the location.
MessageBox.Show(ex.Message);
}
});
}
//sets location of parking space using the GetCoordinates method
//opens map
private async void setLocationBtn_Click(object sender, RoutedEventArgs e)
{
await this.GetCoordinates();
NavigationService.Navigate(new Uri("/Maps.xaml", UriKind.Relative));
}
And this is the map class which doesn't do anyting yet, Is there a way I could pass the geocoordinates from the previous class to the map and draw a pushpin? I was thinking of doing this in the OnNavigatedTo method somehow :
public partial class Maps : PhoneApplicationPage
{
Geolocator geolocator = null;
bool tracking = false;
ProgressIndicator pi;
MapLayer PushpinMapLayer;
public Maps()
{
InitializeComponent();
pi = new ProgressIndicator();
pi.IsIndeterminate = true;
pi.IsVisible = false;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
}
}
To add a pin to the map:
var overlay = new MapOverlay
{
PositionOrigin = new Point(0.5, 0.5),
GeoCoordinate = location, // takes a GeoCoordinate instance. convert Geoposition to GeoCoordinate
Content = new TextBlock{Text = "hello"}; // you can use any UIElement as a pin
};
var ml = new MapLayer { overlay };
map.Layers.Add(ml);
You can append the latitude and longitude of your position as a query in the URI you pass to NavigationSerivce.Navigate, and extract it in the OnNavigatedTo event handler with e.Uri.Query.
A tip. Task.Run schedules your task to run on the thread-pool. Your task is not CPU-bound and therefore Task.Run will not give you any performance gains.
Edit:
Convert a Geoposition to GeoCoordinate with this:
var location = new GeoCoordinate(geoposition.Coordinate.Latitude, geoposition.Coordinate.Longitude);
A very useful resource is the Nokia WP8 Guide

Categories