Pass Pins values to next page - google-maps

I am using map in my app and added some pins to it.
When I click on pin it display some info.
Now I want to pass the values/info of pins to next page after clicking on pin tooltip.
Here is what I am trying:
Pin pins;
protected async override void OnAppearing()
{
base.OnAppearing();
// workerListVM.DisplayMap();
var employeesDetail = await workerListVM.getdetail();
foreach (var employees in employeesDetail)
{
try
{
map1.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(employees.Latitude, employees.Longitude),Distance.FromMiles(.5)));
var position = new Position(employees.Latitude, employees.Longitude);
pins = new Pin()
{
Type = PinType.Place,
Position = position,
Label = employees.UserName,
Address = employees.City
};
map1.Pins.Add(pins);
pins.Clicked += Pins_Clicked;
}
catch (NullReferenceException) { }
catch (Exception) { }
}
}
private void Pins_Clicked(object sender, EventArgs e)
{
DisplayAlert($"{pins.Label}", $"{pins.Address}", "Ok");
}
But its not working.

Related

Xamarin Forms - custom map marker not visible

I am following article on MS page about Custom map renderer and I can not get it to work for android. Map shows but pins (Markers) are not there. I did not found what I did different from official documents (as in previous link). When I debug, there are 3 markers in customPins collection. And custom renderer works in UWP. So issue is only in Android code.
Here is my CustomRender code for Android which does not shows pins.
using System;
using System.Collections.Generic;
using Android.Content;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.Widget;
using iVanApp;
using iVanApp.Android.CustomMapRenderers;
using iVanApp.Droid;
using iVanApp.Model;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Maps.Android;
[assembly: ExportRenderer(typeof(NightMap), typeof(MapRenderers))]
namespace iVanApp.Android.CustomMapRenderers
{
public class MapRenderers : MapRenderer, GoogleMap.IInfoWindowAdapter
{
List<NightPin> customPins;
public MapRenderers(Context context) : base(context)
{
}
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
NativeMap.InfoWindowClick -= OnInfoWindowClick;
}
if (e.NewElement != null)
{
var formsMap = (NightMap)e.NewElement;
customPins = formsMap.NightPins;
}
}
protected override void OnMapReady(GoogleMap map)
{
base.OnMapReady(map);
NativeMap.InfoWindowClick += OnInfoWindowClick;
NativeMap.SetInfoWindowAdapter(this);
}
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
return marker;
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (!string.IsNullOrWhiteSpace(customPin.Name))
{
}
}
NightPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
return pin;
}
}
return null;
}
public global::Android.Views.View GetInfoContents(Marker marker)
{
var inflater = global::Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as global::Android.Views.LayoutInflater;
if (inflater != null)
{
global::Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
view = inflater.Inflate(Resource.Layout.mtrl_layout_snackbar_include, null);
if (customPin.Name.Equals("Xamarin"))
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
return view;
}
return null;
}
public global::Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
}
}
DOes anyone have idea why this would not work?
Note: I had to modify official MS code because I got errors. Wherever is Android.Views.View I had to modify it to global::Android.Views.View otherwise I got following error
"'MapRenderers' does not implement interface member
'GoogleMap.IInfoWindowAdapter.GetInfoContents(Marker)'.
'MapRenderers.GetInfoContents(Marker)' cannot implement
'GoogleMap.IInfoWindowAdapter.GetInfoContents(Marker)' because it does
not have the matching return type of 'View'.".
and
The type or namespace name 'Views' does not exist in the namespace
'iVanApp.Android' (are you missing an assembly reference?)
Hope this did not break my code.
After investigating and reading about custom map issues (and mostly solutions) from others I got a workaround solution how to get pins on map but does not show info window when I click on pin(marker). Here I found workaround. If I modify OnMapReday and call&add method SetMapMarkers then pins are visible but as I said no info window is shown when I click on pin
protected override void OnMapReady(GoogleMap map)
{
base.OnMapReady(map);
NativeMap.InfoWindowClick += OnInfoWindowClick;
NativeMap.SetInfoWindowAdapter(this);
SetMapMarkers();
}
private void SetMapMarkers()
{
NativeMap.Clear();
foreach (var pin in customPins)
{
NativeMap.AddMarker(CreateMarker(pin));
}
}
Although this is solution, I would prefer if I could get it to work without this workaround. Hence I did not put much effort why info window is not shown when you click on pin. In case there would be no solution without this workaround then I will be interested in solution with workaround but as I said I do not prefer to go this way.
As FreakyAli said that adding a custom pin and positions for CustomMap.
<local:CustomMap x:Name="customMap" MapType="Street" />
Adding a custom pin and positions the map's view with the MoveToRegion method
public MainPage()
{
InitializeComponent();
var pin = new CustomPin
{
Type = PinType.Place,
Position = new Position(37.79752, -122.40183),
Label = "Xamarin San Francisco Office",
Address = "394 Pacific Ave, San Francisco CA",
Id = "Xamarin",
Url = "http://xamarin.com/about/"
};
customMap.CustomPins = new List<CustomPin> { pin };
customMap.Pins.Add(pin);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
}
I can get InfoWindow by clicking map pin, having no problem.

How to get Address from Lat Long

Hello i am creating App for iOS and Android. The issue i want to fix that on the load on page i want to display the map with the address. I can get Lat Long successfully but i cannot getting address that i want to display on a label. Below is my code that i am using.
using Plugin.Geolocator;
using Xamarin.Forms.Maps;
private Position _position;
// Map map;
double Lat, Long;
string address = "";
public TestPage()
{
NavigationPage.SetHasNavigationBar(this, false);
InitializeComponent();
GetPosition();
if (_position != null)
{
Lat = _position.Latitude;
Long = _position.Longitude;
}
//Task<String> str = GetAddress();
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(Lat, Long), Distance.FromMiles(1)));
var position = new Position(Lat, Long);
var pin = new Pin
{
Type = PinType.Place,
Position = position,
Label = ""
};
map.Pins.Add(pin);
var zoomLevel = 17.83;
var latlongdegrees = 360 / (Math.Pow(2, zoomLevel));
map.MoveToRegion(new MapSpan(position, latlongdegrees, latlongdegrees));
LabelTime.Text = DateTime.Now.ToString("hh:mm tt") + " " + DateTime.Now.ToString("MM/dd/yyyy");
string recentAddress = address; // trying to get adderss for location
}
GetPosition()
public async void GetPosition()
{
Plugin.Geolocator.Abstractions.Position position = null;
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 100.0;
position = await locator.GetLastKnownLocationAsync();
if (position != null)
{
_position = new Position(position.Latitude, position.Longitude);
//got a cahched position, so let's use it.
return;
}
if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled)
{
//not available or enabled
return;
}
position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10), null, true);
}
catch (Exception ex)
{
// error(ex.Message, Convert.ToString(ex.InnerException), ex.Source, ex.StackTrace);
}
_position = new Position(position.Latitude, position.Longitude);
if (position == null)
return;
}
GetAddress()
public async Task<String> GetAddress()
{
// string Addrsss = "";
try
{
Geocoder geoCoder = new Geocoder();
if (_position != null)
{
var possibleAddresses = await geoCoder.GetAddressesForPositionAsync(_position);
await Task.Delay(2000);
foreach (var a in possibleAddresses)
{
address += a + "\n";
}
}
return address;
}
catch (Exception ex)
{
throw;
}
}
I also try to get the current address on OnAppearing()
protected override void OnAppearing()
{
this.Appearing += TestPage_Appearing; //Subscribe to event
base.OnAppearing();
}
protected async void TestPage_Appearing(object sender, EventArgs args)
{
GetPosition();
address= await GetAddress();
string a = address;
this.Appearing -= TestPage_Appearing; //Unsubscribe
}
You can get placemark address using Xamarin.Essentials as below,
protected async override void OnAppearing()
{
await GetAddress();
}
private async Task GetAddress()
{
var lat = 47.673988;
var lon = -122.121513;
var placemarks = await Geocoding.GetPlacemarksAsync(lat, lon);
var placemark = placemarks?.FirstOrDefault();
if (placemark != null)
{
var geocodeAddress =
$"AdminArea: {placemark.AdminArea}\n" +
$"CountryCode: {placemark.CountryCode}\n" +
$"CountryName: {placemark.CountryName}\n" +
$"FeatureName: {placemark.FeatureName}\n" +
$"Locality: {placemark.Locality}\n" +
$"PostalCode: {placemark.PostalCode}\n" +
$"SubAdminArea: {placemark.SubAdminArea}\n" +
$"SubLocality: {placemark.SubLocality}\n" +
$"SubThoroughfare: {placemark.SubThoroughfare}\n" +
$"Thoroughfare: {placemark.Thoroughfare}\n";
Console.WriteLine(geocodeAddress);
}
}
refer this link for in depth details
Also this one for detailed implementation

Bad location Google Maps Xamarin Forms (Middle of the ocean)

I'm using Xamarin.forms.Maps and ExtendedMap, I did make a custom control, here I can get the location when the user tap on map but by default the map position is in the middle of the occean, something like this 0.0756931, 0.0786793. I was seaching and trying for a while but I did not find the solution.
I did see that the map is loading the region.LatitudeDegrees and region.LongitudeDegrees but I really don't why is this happen.
Xamarin.Forms 3.0.0.482510
Xamarin.Forms.Maps 3.0.0.482510
Xamarin.Plugin.ExternalMaps 4.0.1
MapGoogleView.xaml
<local:ExtendedMap
WidthRequest="320" HeightRequest="200"
x:Name="MyMap" Tap="OnTap"
IsShowingUser="true"
MapType="Street"/>
MapGoogleView.xaml.cs
public MapGoogleView(double lat, double lon)
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
var map = new ExtendedMap(
MapSpan.FromCenterAndRadius(
new Position(lat, lon), Distance.FromMiles(0.3)))
{
IsShowingUser = true,
HeightRequest = 100,
WidthRequest = 900,
VerticalOptions = LayoutOptions.FillAndExpand,
MapType = MapType.Street
};
var stack = new StackLayout { Spacing = 0 };
stack.Children.Add(map);
Content = stack;
var position = new Position(lat, lon); // Latitude, Longitude
var pin = new Pin
{
Type = PinType.Generic,
Position = position,
Label = "UbicaciĆ³n",
Address = "Latitud: " + lat.ToString() + ", Longitud: " + lon.ToString(),
};
MyMap.Pins.Add(pin);
map.MoveToRegion(
MapSpan.FromCenterAndRadius(
new Position(lat, lon), Distance.FromMiles(1)));
}
ExtendedMap.cs
public class ExtendedMap : Map
{
public event EventHandler<TapEventArgs> Tap;
public ExtendedMap()
{
}
public ExtendedMap(MapSpan region) : base(region)
{
}
public void OnTap(Position coordinate)
{
OnTap(new TapEventArgs { Position = coordinate });
}
public async void OnTap(Position coordinate)
{
try
{
OnTap(new TapEventArgs { Position = coordinate });
}
catch (Exception error)
{
await Application.Current.MainPage.DisplayAlert(
"Error",
error.Message,
"Aceptar");
return;
}
}
protected virtual void OnTap(TapEventArgs e)
{
var handler = Tap;
if (handler != null) handler(this, e);
}
}
public class TapEventArgs : EventArgs
{
public Position Position { get; set; }
}
}
Droid
ExtendedMapRenderer.cs
public class ExtendedMapRenderer : MapRenderer, IOnMapReadyCallback
{
private GoogleMap _map;
public void OnMapReady(GoogleMap googleMap)
{
_map = googleMap;
if (_map != null)
//_map.GestureRecognizer.Add(new);
_map.MapClick += googleMap_MapClick;
}
public ExtendedMapRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Map> e) //cambiar a xamarin.forms.view
{
if (_map != null)
_map.MapClick -= googleMap_MapClick;
base.OnElementChanged(e);
if (Control != null)
((MapView)Control).GetMapAsync(this);
}
private void googleMap_MapClick(object sender, GoogleMap.MapClickEventArgs e)
{
((ExtendedMap)Element).OnTap(new Position(e.Point.Latitude, e.Point.Longitude));
}
}
If you're struggling to obtain the Latitude and Longitude coordinates using the plugins described above, you could obtain your devices lon/lat by doing the following:
Download and install into your application the Geolocator Plugin. Made by the man the myth the legend James Montemagno.
Following that, you can follow this guide to obtain your devices longitude and latitude coordinates.
On doing that you can assign your global lat and lon variables to the values retrieved using that plugin. I don't know if you did this prior to instantiating your maps or have used a different method but this is how I get my devices Lat & Lon.
As a fallback if a device has location disabled or does not have the ability to retrieve its GPS data I always set my default lat & lon to the capital city of the devices country region.
RegionInfo.CurrentRegion
then if UK set the lat & lon to london city center for example.

Gibberish in Google Maps in Codename One

Gibberish in Google Maps
I am working on an IOS app in Codenameone (in Intellij), and programed an interface for users to use google maps within my app. However, when they start to search for places or navigate in street view, I receive a ton of gibberish on my iOS simulator (See screenshot below). Has anyone run into this issue and if so, have you found as shown?
public class PetBnBApp {
private static final String HTML_API_KEY = "AIzaSyBWeRU02YUYPdwRuMFyTKIXUbHjq6e35Gw";
private Form current;
private Resources theme;
private Form home;
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
// Pro only feature
try {
Resources theme = Resources.openLayered("/theme");
UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
Display.getInstance().setCommandBehavior(Display.COMMAND_BEHAVIOR_SIDE_NAVIGATION);
UIManager.getInstance().getLookAndFeel().setMenuBarClass(SideMenuBar.class);
} catch (IOException e) {
e.printStackTrace();
}
}
MapContainer.MapObject sydney;
public void start() {
if (current != null) {
current.show();
return;
}
Form maps = new Form("Native Maps Test");
maps.setLayout(new BorderLayout());
final MapContainer cnt = new MapContainer(HTML_API_KEY);
//final MapContainer cnt = new MapContainer();
//42.3040009,-71.5040407
cnt.setCameraPosition(new Coord(42.3040009, -71.5040407));//this breaks the code //because the Google map is not loaded yet
cnt.addMapListener(new MapListener() {
#Override
public void mapPositionUpdated(Component source, int zoom, Coord center) {
System.out.println("Map position updated: zoom="+zoom+", Center="+center);
}
});
cnt.addLongPressListener(e->{
System.out.println("Long press");
ToastBar.showMessage("Received longPress at "+e.getX()+", "+e.getY(), FontImage.MATERIAL_3D_ROTATION);
});
cnt.addTapListener(e->{
ToastBar.showMessage("Received tap at "+e.getX()+", "+e.getY(), FontImage.MATERIAL_3D_ROTATION);
});
int maxZoom = cnt.getMaxZoom();
System.out.println("Max zoom is "+maxZoom);
Button btnMoveCamera = new Button("Move Camera");
btnMoveCamera.addActionListener(e->{
cnt.setCameraPosition(new Coord(-33.867, 151.206));
});
Style s = new Style();
s.setFgColor(0xff0000);
s.setBgTransparency(0);
FontImage markerImg = FontImage.createMaterial(FontImage.MATERIAL_PLACE, s, 3);
Button btnAddMarker = new Button("Add Marker");
btnAddMarker.addActionListener(e->{
cnt.setCameraPosition(new Coord(41.889, -87.622));
cnt.addMarker(EncodedImage.createFromImage(markerImg, false), cnt.getCameraPosition(), "Hi marker", "Optional long description", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Bounding box is "+cnt.getBoundingBox());
ToastBar.showMessage("You clicked the marker", FontImage.MATERIAL_PLACE);
}
});
});
Button btnAddPath = new Button("Add Path");
btnAddPath.addActionListener(e->{
cnt.addPath(
cnt.getCameraPosition(),
new Coord(-33.866, 151.195), // Sydney
new Coord(-18.142, 178.431), // Fiji
new Coord(21.291, -157.821), // Hawaii
new Coord(37.423, -122.091) // Mountain View
);
});
Button panTo = new Button("Pan To");
panTo.addActionListener(e->{
//bounds.extend(new google.maps.LatLng('66.057878', '-22.579047')); // Iceland
//bounds.extend(new google.maps.LatLng('37.961952', '43.878878')); // Turkey
Coord c1 = new Coord(42.3040432, -71.5045936);
Coord c2 = new Coord(49.2577142, -123.1941149);
//Coord center = new Coord(c1.getLatitude()/2 + c2.getLatitude() / 2, c1.getLongitude()/2 + c2.getLongitude()/2 );
Coord center = new Coord(49.1110928, -122.9414646);
float zoom = cnt.getZoom();
boolean[] finished = new boolean[1];
cnt.addMapListener(new MapListener() {
#Override
public void mapPositionUpdated(Component source, int zoom, Coord c) {
if (Math.abs(c.getLatitude() - center.getLatitude()) > .001 || Math.abs(c.getLongitude() - center.getLongitude()) > .001) {
return;
}
finished[0] = true;
synchronized(finished) {
final MapListener fthis = this;
Display.getInstance().callSerially(()->{
cnt.removeMapListener(fthis);
});
finished.notify();
}
}
});
cnt.zoom(center, (int)zoom);
while (!finished[0]) {
Display.getInstance().invokeAndBlock(()->{
while (!finished[0]) {
Util.wait(finished, 100);
}
});
}
BoundingBox box = cnt.getBoundingBox();
if (!box.contains(c1) || !box.contains(c2)) {
while (!box.contains(c1) || !box.contains(c2)) {
if (!box.contains(c1)) {
System.out.println("Box "+box+" doesn't contain "+c1);
}
if (!box.contains(c1)) {
System.out.println("Box "+box+" doesn't contain "+c2);
}
zoom -= 1;
final boolean[] done = new boolean[1];
final int fzoom = (int)zoom;
cnt.addMapListener(new MapListener() {
#Override
public void mapPositionUpdated(Component source, int zm, Coord center) {
if (zm == fzoom) {
final MapListener fthis = this;
Display.getInstance().callSerially(()->{
cnt.removeMapListener(fthis);
});
done[0] = true;
synchronized(done) {
done.notify();
}
}
}
});
cnt.zoom(center, (int)zoom);
while (!done[0]) {
Display.getInstance().invokeAndBlock(()->{
while (!done[0]) {
Util.wait(done, 100);
}
});
}
box = cnt.getBoundingBox();
System.out.println("Zoom now "+zoom);
}
} else if (box.contains(c1) && box.contains(c2)) {
while (box.contains(c1) && box.contains(c2)) {
zoom += 1;
final boolean[] done = new boolean[1];
final int fzoom = (int)zoom;
cnt.addMapListener(new MapListener() {
public void mapPositionUpdated(Component source, int zm, Coord center) {
if (zm == fzoom) {
final MapListener fthis = this;
Display.getInstance().callSerially(()->{
cnt.removeMapListener(fthis);
});
done[0] = true;
synchronized(done) {
done.notify();
}
}
}
});
cnt.zoom(center, (int)zoom);
while (!done[0]) {
Display.getInstance().invokeAndBlock(()->{
while (!done[0]) {
Util.wait(done, 100);
}
});
}
box = cnt.getBoundingBox();
}
zoom -= 1;
cnt.zoom(center, (int)zoom);
cnt.addTapListener(null);
}
});
Button testCoordPositions = $(new Button("Test Coords"))
.addActionListener(e->{
Coord topLeft = cnt.getCoordAtPosition(0, 0);
System.out.println("Top Left is "+topLeft+" -> "+cnt.getScreenCoordinate(topLeft) +" Should be (0,0)");
Coord bottomRight = cnt.getCoordAtPosition(cnt.getWidth(), cnt.getHeight());
System.out.println("Bottom right is "+bottomRight+" -> "+cnt.getScreenCoordinate(bottomRight) + " Should be "+cnt.getWidth()+", "+cnt.getHeight());
Coord bottomLeft = cnt.getCoordAtPosition(0, cnt.getHeight());
System.out.println("Bottom Left is "+bottomLeft+" -> "+cnt.getScreenCoordinate(bottomLeft) + " Should be 0, "+cnt.getHeight());
Coord topRight = cnt.getCoordAtPosition(cnt.getWidth(), 0);
System.out.println("Top right is "+topRight + " -> "+cnt.getScreenCoordinate(topRight)+ " Should be "+cnt.getWidth()+", 0");
Coord center = cnt.getCoordAtPosition(cnt.getWidth()/2, cnt.getHeight()/2);
System.out.println("Center is "+center+" -> "+cnt.getScreenCoordinate(center)+", should be "+(cnt.getWidth()/2)+", "+(cnt.getHeight()/2));
EncodedImage encImg = EncodedImage.createFromImage(markerImg, false);
cnt.addMarker(encImg, topLeft,"Top Left", "Top Left", null);
cnt.addMarker(encImg, topRight, "Top Right", "Top Right", null);
cnt.addMarker(encImg, bottomRight, "Bottom Right", "Bottom Right", null);
cnt.addMarker(encImg, bottomLeft, "Bottom Left", "Bottom Left", null);
cnt.addMarker(encImg, center, "Center", "Center", null);
})
.asComponent(Button.class);
Button toggleTopMargin = $(new Button("Toggle Margin"))
.addActionListener(e->{
int marginTop = $(cnt).getStyle().getMarginTop();
if (marginTop < Display.getInstance().getDisplayHeight() / 3) {
$(cnt).selectAllStyles().setMargin(Display.getInstance().getDisplayHeight() / 3, 0, 0, 0);
} else {
$(cnt).selectAllStyles().setMargin(0,0,0,0);
}
$(cnt).getComponentForm().revalidate();
})
.asComponent(Button.class);
Button btnClearAll = new Button("Clear All");
btnClearAll.addActionListener(e->{
cnt.clearMapLayers();
});
MapContainer.MapObject mo = cnt.addMarker(EncodedImage.createFromImage(markerImg, false), new Coord(-33.866, 151.195), "test", "test", e->{
System.out.println("Marker clicked");
cnt.removeMapObject(sydney);
});
sydney = mo;
System.out.println("MO is "+mo);
mo = cnt.addMarker(EncodedImage.createFromImage(markerImg, false), new Coord(-18.142, 178.431), "test", "test",e->{
System.out.println("Marker clicked");
});
System.out.println("MO is "+mo);
cnt.addTapListener(e->{
if (tapDisabled) {
return;
}
tapDisabled = true;
TextField enterName = new TextField();
Container wrapper = BoxLayout.encloseY(new Label("Name:"), enterName);
InteractionDialog dlg = new InteractionDialog("Add Marker");
dlg.getContentPane().add(wrapper);
enterName.setDoneListener(e2->{
String txt = enterName.getText();
cnt.addMarker(EncodedImage.createFromImage(markerImg, false), cnt.getCoordAtPosition(e.getX(), e.getY()), enterName.getText(), "", e3->{
ToastBar.showMessage("You clicked "+txt, FontImage.MATERIAL_PLACE);
});
dlg.dispose();
tapDisabled = false;
});
dlg.showPopupDialog(new Rectangle(e.getX(), e.getY(), 10, 100));
enterName.startEditingAsync();
});
Button showNextForm = $(new Button("Next Form"))
.addActionListener(e->{
Form form = new Form("Hello World");
Button b1 = $(new Button("B1"))
.addActionListener(e2->{
ToastBar.showMessage("B1 was pressed", FontImage.MATERIAL_3D_ROTATION);
})
.asComponent(Button.class);
Button back = $(new Button("Back to Home"))
.addActionListener(e2->{
home.showBack();
})
.asComponent(Button.class);
form.add(b1);
})
.asComponent(Button.class);
FloatingActionButton nextForm = FloatingActionButton.createFAB(FontImage.MATERIAL_ACCESS_ALARM);
nextForm.addActionListener(e->{
Form form = new Form("Hello World");
Button b1 = $(new Button("B1"))
.addActionListener(e2->{
ToastBar.showMessage("B1 was pressed", FontImage.MATERIAL_3D_ROTATION);
})
.asComponent(Button.class);
Button back = $(new Button("Back to Home"))
.addActionListener(e2->{
home.showBack();
})
.asComponent(Button.class);
form.add(b1).add(back);
form.show();
});
Container root = LayeredLayout.encloseIn(
BorderLayout.center(nextForm.bindFabToContainer(cnt)),
BorderLayout.south(
FlowLayout.encloseBottom(panTo, testCoordPositions, toggleTopMargin, btnMoveCamera, btnAddMarker, btnAddPath, btnClearAll )
)
);
maps.add(BorderLayout.CENTER, root);
maps.show();
Form hi = new Form("Native Maps Test");
hi.setLayout(new BorderLayout());
System.out.println("Read...");
ReadParseJson x = new ReadParseJson();
GoogleMapsTestApp e = new GoogleMapsTestApp();
System.out.println(Arrays.toString(x.getArray()));
//create and build the home Form
home = new Form("Home", BoxLayout.y());
home.add(new Label("PetBnB: AirBnB for Pets!"));
home.add(new Button("Search for Local Stay"));
home.add(new Button("Payment"));
TextField txt = new TextField("", "Enter Pet Animal here:");
home.add(txt)
.add(new CheckBox("New Users in Your Area!"));
RadioButton rb1 = new RadioButton("Bnb Area 2");
RadioButton rb2 = new RadioButton("Bnb Area 3");
rb1.setGroup("group");
rb2.setGroup("group");
home.addAll(rb1, rb2);
final Slider a = new Slider();
a.setText("50$");
a.setProgress(50);
a.setEditable(true);
a.setRenderPercentageOnTop(true);
home.add(a);
Button b1 = new Button("WARNING: MUST READ");
b1.addActionListener(evt -> Dialog.show("Warning!", "If Pet dies, it is not Bnb owner's responsibility", "Ok", "Cancel"));
home.add(b1);
//Create Form1 and Form2 and set a Back Command to navigate back to the home Form
Form form1 = new Form("Search For Stay");
setBackCommand(form1);
Form form2 = new Form("Help");
setBackCommand(form2);
//Add navigation commands to the home Form
NavigationCommand homeCommand = new NavigationCommand("Home");
homeCommand.setNextForm(home);
home.getToolbar().addCommandToSideMenu(homeCommand);
NavigationCommand cmd1 = new NavigationCommand("Search For Stay");
cmd1.setNextForm(maps);
home.getToolbar().addCommandToSideMenu(cmd1);
NavigationCommand cmd2 = new NavigationCommand("Help");
cmd2.setNextForm(form2);
home.getToolbar().addCommandToSideMenu(cmd2);
//Add Edit, Add and Delete Commands to the home Form context Menu
Image im = FontImage.createMaterial(FontImage.MATERIAL_MODE_EDIT, UIManager.getInstance().getComponentStyle("Command"));
Command edit = new Command("Edit", im) {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Editing");
}
};
home.getToolbar().addCommandToOverflowMenu(edit);
im = FontImage.createMaterial(FontImage.MATERIAL_LIBRARY_ADD, UIManager.getInstance().getComponentStyle("Command"));
Command add = new Command("Add", im) {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Adding");
}
};
home.getToolbar().addCommandToOverflowMenu(add);
im = FontImage.createMaterial(FontImage.MATERIAL_DELETE, UIManager.getInstance().getComponentStyle("Command"));
Command delete = new Command("Delete", im) {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Deleting");
}
};
home.getToolbar().addCommandToOverflowMenu(delete);
home.show();
}
protected void setBackCommand(Form f) {
Command back = new Command("") {
#Override
public void actionPerformed(ActionEvent evt) {
home.showBack();
}
};
Image img = FontImage.createMaterial(FontImage.MATERIAL_ARROW_BACK, UIManager.getInstance().getComponentStyle("TitleCommand"));
back.setIcon(img);
f.getToolbar().addCommandToLeftBar(back);
f.getToolbar().setTitleCentered(true);
f.setBackCommand(back);
}
boolean tapDisabled = false;
public void stop() {
current = Display.getInstance().getCurrent();
}
public void destroy() {
}
}

Toggle Button Checked Property Windows Phone 8

I add a toggle button on Windows Phone 8 . When i checked (on), its save a value in Isolated storage and I check that value in constructor whatever it has a toggle value or null. If there is a toggle value I want to display toggle button checked . But I dont know the property to how to checked it when application is run .
Toggle Button XAML :
<toolkit:ToggleSwitch x:Name="toggle" Content="On" Width="165" FontSize="28" VerticalAlignment="Center" HorizontalAlignment="Right"/>
C# :
public Subscription()
{
InitializeComponent();
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
var appSettings = IsolatedStorageSettings.ApplicationSettings;
if (HasSValue() == "NoValue")
{
// Here i want to Display toggle button unchecked
}
else
{
// Here i want to Display toggle button checked
}
}
void toggle_Unchecked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "Off";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Red);
var appSettings = IsolatedStorageSettings.ApplicationSettings;
appSettings.Remove("toggleValue");
appSettings.Save();
}
void toggle_Checked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "On";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Green);
MessageBox.Show("R U Sure ?");
var appSettings = IsolatedStorageSettings.ApplicationSettings;
appSettings.Add("toggleValue", "MAHIN");
appSettings.Save();
}
public string HasSValue()
{
var appSettings = IsolatedStorageSettings.ApplicationSettings;
if (appSettings.Contains("toggleValue"))
{
return (string) appSettings["toggleValue"];
}
else
{
return "NoValue";
}
}
Try this
if (HasSValue() == "NoValue")
{
this.toggle.IsChecked = false;
}
else
{
this.toggle.IsChecked = true;
}
Hope this helps
Update your Constructor as follows
public Subscription()
{
InitializeComponent();
var appSettings = IsolatedStorageSettings.ApplicationSettings;
if (HasSValue() == "NoValue")
{
// Here i want to Display toggle button unchecked
}
else
{
// Here i want to Display toggle button checked
}
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
}