Gibberish in Google Maps in Codename One - google-maps

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() {
}
}

Related

BlazorGoogleMaps - Get a location from user

With this component, how can I let the user to select a location (a point)?
I have a form that user needs to feel the address and also I need to send the latitude and longitude to the server.
This is what I have so far and it just shows a map that I can navigate:
<GoogleMap Options="mapOptions" />
#code {
MapOptions mapOptions = new MapOptions()
{
Zoom = 13,
Center = new LatLngLiteral()
{
Lat = ...,
Lng = ...
},
MapTypeId = MapTypeId.Roadmap
};
}
You can use the MapEventList component:
<GoogleMap #ref="#map1" Id="map1" Options="#mapOptions" OnAfterInit="#(async () => await OnAfterInitAsync())">
</GoogleMap>
<input type="checkbox" bind="#DisablePoiInfoWindow" />Disable POI's popup info window
<br>
<MapEventList #ref="#eventList" Events="#_events"></MapEventList>
#code {
private GoogleMap map1;
private MapEventList eventList;
private MapOptions mapOptions;
private List<String> _events = new List<String>();
private bool DisablePoiInfoWindow { get; set; } = false;
protected override void OnInitialized()
{
mapOptions = new MapOptions()
{
Zoom = 13,
Center = new LatLngLiteral()
{
Lat = 13.505892,
Lng = 100.8162
},
MapTypeId = MapTypeId.Roadmap
};
}
private async Task OnAfterInitAsync()
{
await map1.InteropObject.AddListener<MouseEvent>("click", async (e) => await OnClick(e));
}
private async Task OnClick(MouseEvent e)
{
_events.Insert(0, $"Click {e.LatLng}.");
_events = _events.Take(100).ToList();
StateHasChanged();
if (DisablePoiInfoWindow)
{
await e.Stop();
}
}
}
Check the demo https://github.com/rungwiroon/BlazorGoogleMaps/blob/master/ClientSideDemo/Pages/MapEvents.razor

Pass Pins values to next page

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.

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

Facebook SDK Integration - LoadPicture Method ERROR

So hi to #ll this is my fist post/question on stackoverflow :D
I need help # following :
So i integrated the Facebook SDk sucessfully in my game but i´dont get the profile picture working ...
So i tryied it oldshool on Facebooks "Tutotial" Way and followed all steps to implement login functions and so on ...
I´ve downloaded the "friendsmash_start" Sample and implemented that Stuff ...
My Main Problem is i don´t get ahead with this problem and can´t figure out what i´m doing wrong so i´m hoping for help.
Here´s the complete Code from the MainMenu Script from the sample which is the only i´ve changed ... like in the tutorial ...
Unity shows me this Error -> "The name 'LoadPicture' does not exist in the current context ... so the errors are on these two parts of code :
"LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);" in the "OnLoggedIn" function
"LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);" in the "MyPictureCallback" function
I don´t understand it cause i searched myself in the script for this function "LoadPicture" and find nothing that was ... according to the "Tutorial" of facebook here :
https://developers.facebook.com/docs/games/unity/unity-tutorial?locale=de_DE
the function should be there cause they wrote there :
"Take a look at the LoadPicture method also in MainMenu.cs to see how we use the Unity WWW class to load the image returned by the graph API."
But i can´t find it :(
HOPE SOMEONE CAN HELP ME I DON´T GET IT ...
Have that problem unfortunately very long time ... thats enoying. :(
HERE`S THE FULL CODE OF MAINMENU.CS :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Facebook.MiniJSON;
using System;
public class MainMenu : MonoBehaviour
{
// Inspector tunable members //
public Texture ButtonTexture;
public Texture PlayTexture; // Texture for main menu button icons
public Texture BragTexture;
public Texture ChallengeTexture;
public Texture StoreTexture;
public Texture FullScreenTexture;
public Texture FullScreenActiveTexture;
public Texture ResourcesTexture;
public Vector2 CanvasSize; // size of window on canvas
public Rect LoginButtonRect; // Position of login button
public Vector2 ResourcePos; // position of resource indicators (not used yet)
public Vector2 ButtonStartPos; // position of first button in main menu
public float ButtonScale; // size of main menu buttons
public float ButtonYGap; // gap between buttons in main menu
public float ChallengeDisplayTime; // Number of seconds the request sent message is displayed for
public Vector2 ButtonLogoOffset; // Offset determining positioning of logo on buttons
public float TournamentStep; // Spacing between tournament entries
public float MouseScrollStep = 40; // Amount score table moves with each step of the mouse wheel
public PaymentDialog paymentDialog;
public GUISkin MenuSkin;
public int CoinBalance;
public int NumLives;
public int NumBombs;
public Texture[] CelebTextures;
public string [] CelebNames;
// Private members //
private static MainMenu instance;
private static List<object> friends = null;
private static Dictionary<string, string> profile = null;
private static List<object> scores = null;
private static Dictionary<string, Texture> friendImages = new Dictionary<string, Texture>();
private Vector2 scrollPosition = Vector2.zero;
private bool haveUserPicture = false;
private float tournamentLength = 0;
private int tournamentWidth = 512;
private int mainMenuLevel = 0; // Level index of main menu
private string popupMessage;
private float popupTime;
private float popupDuration;
void Awake()
{
Util.Log("Awake");
paymentDialog = ((PaymentDialog)(GetComponent("PaymentDialog")));
// allow only one instance of the Main Menu
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
#if UNITY_WEBPLAYER
// Execute javascript in iframe to keep the player centred
string javaScript = #"
window.onresize = function() {
var unity = UnityObject2.instances[0].getUnity();
var unityDiv = document.getElementById(""unityPlayerEmbed"");
var width = window.innerWidth;
var height = window.innerHeight;
var appWidth = " + CanvasSize.x + #";
var appHeight = " + CanvasSize.y + #";
unity.style.width = appWidth + ""px"";
unity.style.height = appHeight + ""px"";
unityDiv.style.marginLeft = (width - appWidth)/2 + ""px"";
unityDiv.style.marginTop = (height - appHeight)/2 + ""px"";
unityDiv.style.marginRight = (width - appWidth)/2 + ""px"";
unityDiv.style.marginBottom = (height - appHeight)/2 + ""px"";
}
window.onresize(); // force it to resize now";
Application.ExternalCall(javaScript);
#endif
DontDestroyOnLoad(gameObject);
instance = this;
// Initialize FB SDK
FB.Init(SetInit, OnHideUnity);
}
private void SetInit()
{
Util.Log("SetInit");
enabled = true; // "enabled" is a property inherited from MonoBehaviour
if (FB.IsLoggedIn)
{
Util.Log("Already logged in");
OnLoggedIn();
}
}
private void OnHideUnity(bool isGameShown)
{
Util.Log("OnHideUnity");
if (!isGameShown)
{
// pause the game - we will need to hide
Time.timeScale = 0;
}
else
{
// start the game back up - we're getting focus again
Time.timeScale = 1;
}
}
private void QueryScores()
{
FB.API("/app/scores?fields=score,user.limit(20)", Facebook.HttpMethod.GET, ScoresCallback);
}
private int getScoreFromEntry(object obj)
{
Dictionary<string,object> entry = (Dictionary<string,object>) obj;
return Convert.ToInt32(entry["score"]);
}
void ScoresCallback(FBResult result)
{
Util.Log("ScoresCallback");
if (result.Error != null)
{
Util.LogError(result.Error);
return;
}
scores = new List<object>();
List<object> scoresList = Util.DeserializeScores(result.Text);
foreach(object score in scoresList)
{
var entry = (Dictionary<string,object>) score;
var user = (Dictionary<string,object>) entry["user"];
string userId = (string)user["id"];
if (string.Equals(userId,FB.UserId))
{
// This entry is the current player
int playerHighScore = getScoreFromEntry(entry);
Util.Log("Local players score on server is " + playerHighScore);
if (playerHighScore < GameStateManager.Score)
{
Util.Log("Locally overriding with just acquired score: " + GameStateManager.Score);
playerHighScore = GameStateManager.Score;
}
entry["score"] = playerHighScore.ToString();
GameStateManager.HighScore = playerHighScore;
}
scores.Add(entry);
if (!friendImages.ContainsKey(userId))
{
// We don't have this players image yet, request it now
LoadPictureAPI(Util.GetPictureURL(userId, 128, 128),pictureTexture =>
{
if (pictureTexture != null)
{
friendImages.Add(userId, pictureTexture);
}
});
}
}
// Now sort the entries based on score
scores.Sort(delegate(object firstObj,
object secondObj)
{
return -getScoreFromEntry(firstObj).CompareTo(getScoreFromEntry(secondObj));
}
);
}
void OnApplicationFocus( bool hasFocus )
{
Util.Log ("hasFocus " + (hasFocus ? "Y" : "N"));
}
// Convenience function to check if mouse/touch is the tournament area
private bool IsInTournamentArea (Vector2 p)
{
return p.x > Screen.width-tournamentWidth;
}
// Scroll the tournament view by some delta
private void ScrollTournament(float delta)
{
scrollPosition.y += delta;
if (scrollPosition.y > tournamentLength - Screen.height)
scrollPosition.y = tournamentLength - Screen.height;
if (scrollPosition.y < 0)
scrollPosition.y = 0;
}
// variables for keeping track of scrolling
private Vector2 mouseLastPos;
private bool mouseDragging = false;
void Update()
{
if(Input.touches.Length > 0)
{
Touch touch = Input.touches[0];
if (IsInTournamentArea (touch.position) && touch.phase == TouchPhase.Moved)
{
// dragging
ScrollTournament (touch.deltaPosition.y*3);
}
}
if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
ScrollTournament (MouseScrollStep);
}
else if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
ScrollTournament (-MouseScrollStep);
}
if (Input.GetMouseButton(0) && IsInTournamentArea(Input.mousePosition))
{
if (mouseDragging)
{
ScrollTournament (Input.mousePosition.y - mouseLastPos.y);
}
mouseLastPos = Input.mousePosition;
mouseDragging = true;
}
else
mouseDragging = false;
}
// Button drawing logic //
private Vector2 buttonPos; // Keeps track of where we've got to on the screen as we draw buttons
private void BeginButtons()
{
// start drawing buttons at the chosen start position
buttonPos = ButtonStartPos;
}
private bool DrawButton(string text, Texture texture)
{
// draw a single button and update our position
bool result = GUI.Button(new Rect (buttonPos.x,buttonPos.y, ButtonTexture.width * ButtonScale, ButtonTexture.height * ButtonScale),text,MenuSkin.GetStyle("menu_button"));
Util.DrawActualSizeTexture(ButtonLogoOffset*ButtonScale+buttonPos,texture,ButtonScale);
buttonPos.y += ButtonTexture.height*ButtonScale + ButtonYGap;
if (paymentDialog.DialogEnabled)
result = false;
return result;
}
void OnGUI()
{
GUI.skin = MenuSkin;
if (Application.loadedLevel != mainMenuLevel) return; // don't display anything except when in main menu
GUILayout.Box("", MenuSkin.GetStyle("panel_welcome"));
if (!FB.IsLoggedIn)
{
GUI.Label((new Rect(179, 11, 287, 160)), "Login to Facebook", MenuSkin.GetStyle("text_only"));
if (GUI.Button(LoginButtonRect, "", MenuSkin.GetStyle("button_login")))
{
FB.Login("email,publish_actions", LoginCallback);
}
}
if (FB.IsLoggedIn)
{
string panelText = "Welcome ";
panelText += (!string.IsNullOrEmpty(GameStateManager.Username)) ? string.Format("{0}!", GameStateManager.Username) : "Smasher!";
if (GameStateManager.UserTexture != null)
GUI.DrawTexture( (new Rect(8,10, 150, 150)), GameStateManager.UserTexture);
GUI.Label( (new Rect(179 , 11, 287, 160)), panelText, MenuSkin.GetStyle("text_only"));
}
string subTitle = "Let's smash some friends!";
if (GameStateManager.Score > 0)
{
subTitle = "Score: " + GameStateManager.Score.ToString();
}
if (!string.IsNullOrEmpty(subTitle))
{
GUI.Label( (new Rect(132, 28, 400, 160)), subTitle, MenuSkin.GetStyle("sub_title"));
}
BeginButtons();
if (DrawButton("Play",PlayTexture))
{
onPlayClicked();
}
if (FB.IsLoggedIn)
{
// Draw resources bar
Util.DrawActualSizeTexture(ResourcePos,ResourcesTexture);
Util.DrawSimpleText(ResourcePos + new Vector2(47,5) ,MenuSkin.GetStyle("resources_text"),string.Format("{0}",CoinBalance));
Util.DrawSimpleText(ResourcePos + new Vector2(137,5) ,MenuSkin.GetStyle("resources_text"),string.Format("{0}",NumBombs));
Util.DrawSimpleText(ResourcePos + new Vector2(227,5) ,MenuSkin.GetStyle("resources_text"),string.Format("{0}",NumLives));
}
#if UNITY_WEBPLAYER
if (Screen.fullScreen)
{
if (DrawButton("Full Screen",FullScreenActiveTexture))
SetFullscreenMode(false);
}
else
{
if (DrawButton("Full Screen",FullScreenTexture))
SetFullscreenMode(true);
}
#endif
DrawPopupMessage();
}
public void AddPopupMessage(string message, float duration)
{
popupMessage = message;
popupTime = Time.realtimeSinceStartup;
popupDuration = duration;
}
public void DrawPopupMessage()
{
if (popupTime != 0 && popupTime + popupDuration > Time.realtimeSinceStartup)
{
// Show message that we sent a request
Rect PopupRect = new Rect();
PopupRect.width = 800;
PopupRect.height = 100;
PopupRect.x = Screen.width / 2 - PopupRect.width / 2;
PopupRect.y = Screen.height / 2 - PopupRect.height / 2;
GUI.Box(PopupRect,"",MenuSkin.GetStyle("box"));
GUI.Label(PopupRect, popupMessage, MenuSkin.GetStyle("centred_text"));
}
}
void TournamentGui()
{
GUILayout.BeginArea(new Rect((Screen.width - 450),0,450,Screen.height));
// Title box
GUI.Box (new Rect(0, - scrollPosition.y, 100,200), "", MenuSkin.GetStyle("tournament_bar"));
GUI.Label (new Rect(121 , - scrollPosition.y, 100,200), "Tournament", MenuSkin.GetStyle("heading"));
Rect boxRect = new Rect();
if(scores != null)
{
var x = 0;
foreach(object scoreEntry in scores)
{
Dictionary<string,object> entry = (Dictionary<string,object>) scoreEntry;
Dictionary<string,object> user = (Dictionary<string,object>) entry["user"];
string name = ((string) user["name"]).Split(new char[]{' '})[0] + "\n";
string score = "Smashed: " + entry["score"];
boxRect = new Rect(0, 121+(TournamentStep*x)-scrollPosition.y , 100,128);
// Background box
GUI.Box(boxRect,"",MenuSkin.GetStyle("tournament_entry"));
// Text
GUI.Label (new Rect(24, 136 + (TournamentStep * x) - scrollPosition.y, 100,128), (x+1)+".", MenuSkin.GetStyle("tournament_position")); // Rank e.g. "1.""
GUI.Label (new Rect(250,145 + (TournamentStep * x) - scrollPosition.y, 300,100), name, MenuSkin.GetStyle("tournament_name")); // name
GUI.Label (new Rect(250,193 + (TournamentStep * x) - scrollPosition.y, 300,50), score, MenuSkin.GetStyle("tournament_score")); // score
Texture picture;
if (friendImages.TryGetValue((string) user["id"], out picture))
{
GUI.DrawTexture(new Rect(118,128+(TournamentStep*x)-scrollPosition.y,115,115), picture); // Profile picture
}
x++;
}
}
else GUI.Label (new Rect(180,270,512,200), "Loading...", MenuSkin.GetStyle("text_only"));
// Record length so we know how far we can scroll to
tournamentLength = boxRect.y + boxRect.height + scrollPosition.y;
GUILayout.EndArea();
}
// React to menu buttons //
private void onPlayClicked()
{
Util.Log("onPlayClicked");
if (friends != null && friends.Count > 0)
{
// Select a random friend and get their picture
Dictionary<string, string> friend = Util.RandomFriend(friends);
GameStateManager.FriendName = friend["first_name"];
GameStateManager.FriendID = friend["id"];
GameStateManager.CelebFriend = -1;
LoadPictureURL(friend["image_url"],FriendPictureCallback);
}
else
{
//We can't access friends
GameStateManager.CelebFriend = UnityEngine.Random.Range(0,CelebTextures.Length - 1);
GameStateManager.FriendName = CelebNames[GameStateManager.CelebFriend];
}
// Start the main game
Application.LoadLevel("GameStage");
GameStateManager.Instance.StartGame();
}
public void SetFullscreenMode (bool on)
{
if (on)
{
Screen.SetResolution (Screen.currentResolution.width, Screen.currentResolution.height, true);
}
else
{
Screen.SetResolution ((int)CanvasSize.x, (int)CanvasSize.y, false);
}
}
public static void FriendPictureCallback(Texture texture)
{
GameStateManager.FriendTexture = texture;
}
delegate void LoadPictureCallback (Texture texture);
IEnumerator LoadPictureEnumerator(string url, LoadPictureCallback callback)
{
WWW www = new WWW(url);
yield return www;
callback(www.texture);
}
void LoadPictureAPI (string url, LoadPictureCallback callback)
{
FB.API(url,Facebook.HttpMethod.GET,result =>
{
if (result.Error != null)
{
Util.LogError(result.Error);
return;
}
var imageUrl = Util.DeserializePictureURLString(result.Text);
StartCoroutine(LoadPictureEnumerator(imageUrl,callback));
});
}
void LoadPictureURL (string url, LoadPictureCallback callback)
{
StartCoroutine(LoadPictureEnumerator(url,callback));
}
void LoginCallback(FBResult result)
{
Util.Log("LoginCallback");
if (FB.IsLoggedIn)
{
OnLoggedIn();
}
}
void OnLoggedIn()
{
Util.Log("Logged in. ID: " + FB.UserId);
// Reqest player info and profile picture
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, APICallback);
LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);
}
void APICallback(FBResult result)
{
Util.Log("APICallback");
if (result.Error != null)
{
Util.LogError(result.Error);
// Let's just try again
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, APICallback);
return;
}
profile = Util.DeserializeJSONProfile(result.Text);
GameStateManager.Username = profile["first_name"];
friends = Util.DeserializeJSONFriends(result.Text);
}
void MyPictureCallback(Texture texture)
{
Util.Log("MyPictureCallback");
if (texture == null)
{
// Let's just try again
LoadPicture(Util.GetPictureURL("me", 128, 128), MyPictureCallback);
return;`
}
GameStateManager.UserTexture = texture;
}
}
change the word "LoadPicture" for "LoadPictureAPI".
For reference see:
https://github.com/fbsamples/friendsmash-unity/blob/master/friendsmash_payments_start/Assets/Scripts/MainMenu.cs

draw a short path betweent 2 point in map

I'm doing app Google Map android.
I want draw a short path betweent 2 point in map.
But I don't know How do i need?
Please help me .Thank you very much.
new class util.java
public class Util {
private DataBaseHelper dbHelper;
private GeoFencApplicationDataset Dataset;
private int getId;
public static boolean checkConnection(Context mContext) {
NetworkInfo info = ((ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
return true;
}
return true;
}
public void DrawPath(Context c, GeoPoint src, GeoPoint dest, int color,
MapView mMapView01) {
Dataset = (GeoFencApplicationDataset) c.getApplicationContext();
dbHelper = Dataset.getDbHelper();
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString((double) src.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString
.append(Double.toString((double) src.getLongitudeE6() / 1.0E6));
urlString.append("&daddr=");// to
urlString
.append(Double.toString((double) dest.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString
.append(Double.toString((double) dest.getLongitudeE6() / 1.0E6));
urlString.append("&ie=UTF8&0&om=0&output=kml");
Log.d("xxx", "URL=" + urlString.toString());
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) {
final String path = doc.getElementsByTagName("GeometryCollection")
.item(0).getFirstChild().getFirstChild()
.getFirstChild().getNodeValue();
final String[] pairs = path.split(" ");
String[] lngLat = pairs[0].split(",");
final GeoPoint startGP = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays().add(
new PathOverLay(startGP, startGP, 1));
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) {
lngLat = pairs[i].split(",");
gp1 = gp2;
gp2 = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays().add(
new PathOverLay(gp1, gp2, 2, color));
if (getId != 0) {
dbHelper.insertTempLatLong(lngLat[1], lngLat[0], getId);
}
Log.d("xxx", "pair:" + pairs[i]);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
public double[] getLocation(Context c) {
Criteria criteria;
String provider;
LocationManager locManager = (LocationManager) c
.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
provider = locManager.getBestProvider(criteria, true);
double[] loca = new double[2];
// For Latitude & Longitude
Location location = locManager.getLastKnownLocation(provider);
if (location != null) {
loca[0] = location.getLatitude();
loca[1] = location.getLongitude();
} else {
loca[0] = 0.0;
loca[1] = 0.0;
}
return loca;
}
public void setId(int id) {
// TODO Auto-generated method stub
getId = id;
}
}
new class PathOverLay.java
public class PathOverLay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
private int mRadius = 6;
private int mode = 0;
private int defaultColor;
private String text = "";
private Bitmap img = null;
public PathOverLay(GeoPoint gp1, GeoPoint gp2, int mode) // GeoPoint is a
// int. (6E)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
defaultColor = 999; // no defaultColor
}
public PathOverLay(GeoPoint gp1, GeoPoint gp2, int mode, int defaultColor) {
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.defaultColor = defaultColor;
}
public void setText(String t) {
this.text = t;
}
public void setBitmap(Bitmap bitmap) {
this.img = bitmap;
}
public int getMode() {
return mode;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
Projection projection = mapView.getProjection();
if (shadow == false) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
// mode=1:start
if (mode == 1) {
if (defaultColor == 999)
paint.setColor(Color.BLUE);
else
paint.setColor(defaultColor);
// RectF oval = new RectF(point.x - mRadius, point.y - mRadius,
// point.x + mRadius, point.y + mRadius);
RectF oval = new RectF(point.x - mRadius, point.y - mRadius,
point.x + mRadius, point.y + mRadius);
// start point
canvas.drawOval(oval, paint);
}
// mode=2:path
else if (mode == 2) {
if (defaultColor == 999)
paint.setColor(Color.RED);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(70);
canvas.drawLine(point.x, point.y, point2.x, point2.y, paint);
}
/* mode=3:end */
else if (mode == 3) {
/* the last path */
if (defaultColor == 999)
paint.setColor(Color.GREEN);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(120);
canvas.drawLine(point.x, point.y, point2.x, point2.y, paint);
RectF oval = new RectF(point2.x - mRadius, point2.y - mRadius,
point2.x + mRadius, point2.y + mRadius);
/* end point */
paint.setAlpha(120);
canvas.drawOval(oval, paint);
}
}
return super.draw(canvas, mapView, shadow, when);
}
// Read more:
// http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html#ixzz1hte9kGoi
}
final call method ...
util = new Util();
mapOverlays = mapView.getOverlays();
util = new Util();
util.setId(id);
GeoPoint srcGeoPoint = new GeoPoint((int) (destLat * 1E6),
(int) (destLong * 1E6));
GeoPoint destGeoPoint = new GeoPoint((int) (srcLat * 1E6),
(int) (srcLong * 1E6));
progrDialog = ProgressDialog.show(AddFenceActivity.this,
"", "Please Wait..", true);
mapView.getOverlays().add(
new PathOverLay(srcGeoPoint,destGeoPoint, 2,Color.RED));
util.DrawPath(AddFenceActivity.this, srcGeoPoint,
destGeoPoint, Color.RED, mapView);
mapView.getController().animateTo(srcGeoPoint);
public class MapOverLayItem extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;
public MapOverLayItem(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return mOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return mOverlays.size();
}
public MapOverLayItem(Drawable defaultMarker, Context context) {
super(defaultMarker);
mContext = context;
}
}