How to get Address from Lat Long - google-maps

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

Related

get Direction and get path android studio

i am trying to choose form the autocomplete a place and drew a path to it and when i pick a place from the autocomplete the app crashes.
please see the
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.saoutimohamed.tewsila, PID: 5924
java.lang.IllegalStateException: no included points
at com.google.android.gms.common.internal.Preconditions.checkState(Unknown
Source:8)
at com.google.android.gms.maps.model.LatLngBounds$Builder.build(Unknown
Source:10)
at com.saoutimohamed.tewsila.WelcomeDriver$4.onResponse(WelcomeDriver.java:271)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Application terminated.
logcat and tall me what is wrong with my code
and this is the code
private void getDirection() {
String requestApi;
try {
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_preference=less_driving&" +
"origin=" + Common.mLastLocation.getLatitude() + "," + Common.mLastLocation.getLongitude() + "&" +
"destination=" + lat+","+lng + "&" +
"key=" + getResources().getString(R.string.google_direction_api);
Log.d("SAOUTI", requestApi);
mService.getPath(requestApi)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray jsonArray = jsonObject.getJSONArray("routes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject route = jsonArray.getJSONObject(i);
JSONObject poly = route.getJSONObject("overview_polyline");
String polyline = poly.getString("points");
polyLineList = decodePoly(polyline);
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : polyLineList)
builder.include(latLng);
LatLngBounds bounds = builder.build();
CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 5);
mMap.animateCamera(mCameraUpdate);
polylineOptions = new PolylineOptions();
polylineOptions.color(Color.GRAY);
polylineOptions.width(5);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(JointType.ROUND);
polylineOptions.addAll(polyLineList);
greyPolyline = mMap.addPolyline(polylineOptions);
blackPolylineOptions = new PolylineOptions();
blackPolylineOptions.color(Color.BLACK);
blackPolylineOptions.width(5);
blackPolylineOptions.startCap(new SquareCap());
blackPolylineOptions.endCap(new SquareCap());
blackPolylineOptions.jointType(JointType.ROUND);
blackPolyline = mMap.addPolyline(blackPolylineOptions);
mMap.addMarker(new MarkerOptions()
.position(polyLineList.get(polyLineList.size() - 1))
.title("Pickup Location"));
ValueAnimator polyLineAnimator = ValueAnimator.ofInt(0, 100);
polyLineAnimator.setDuration(2000);
polyLineAnimator.setInterpolator(new LinearInterpolator());
polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyline.getPoints();
int percentValue = (int) valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int) (size * (percentValue / 100.0f));
List<LatLng> p = points.subList(0, newPoints);
blackPolyline.setPoints(p);
}
});
polyLineAnimator.start();
carMarker = mMap.addMarker(new MarkerOptions().position(currentPosition)
.flat(true)
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.tewsila_car)));
handler = new Handler();
} catch (JSONException e) {
e.printStackTrace();
index = -1;
next = 1;
handler.postDelayed(drawPathRunnable, 3000);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(WelcomeDriver.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
the line that not responding in the logcat is (LatLngBounds bounds = builder.build();)
I had this same issue and i removed
"+getResources().getString(R.string.google_direction_api)" part from the requestApi. Perfectlr worked for me. But i don't know the reason.
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_preference=less_driving&" +
"origin=" + Common.mLastLocation.getLatitude() + "," + Common.mLastLocation.getLongitude() + "&" +
"destination=" + lat+","+lng + "&" +
"key=";

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

Waiting and Return a result with DownloadStringAsync WP8

I do a webrequest with DownloadStringAsync() but I need to return the result only when the DownloadStringCompleted event has been called. After the downloadasync-method, I need to wait for the result and then I could return it in a string property. So I implemented a while(Result == "") but I don't know what to do there. I already tried Thread.sleep(500) but it seems the download never gets completed. And the code remains in the while forever.
string Result = "";
public String Query(DataRequestParam dataRequestParam)
{
try
{
WebClient web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += OnDownloadStringCompleted;
web.DownloadStringAsync(dataRequestParam.TargetUri);
while (Result == "")
{
//What am i supposed to do here ?
}
return Result;
}
catch(WebException we)
{
MessageBox.Show(we.Message);
return null;
}
}
private void OnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
//Error treating
}
else
{
Result = e.Result;
}
}
UI CODE
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.NavigationMode != NavigationMode.Back)
{
ServerFunctions.SetUserProfil(User.UserLogin,User.UserPassword);
this.listBoxGetDocsLibs.Clear();
List<BdeskDocLib> list = new List<BdeskDocLib>();
try
{
//HERE THE START OF THE DOWNLOAD
ServerFunctions.GetDocLibs(true);
}
catch (Exception ex)
{
//error
}
foreach (BdeskDocLib docLib in list)
{
this.listBoxGetDocsLibs.Add(docLib);
}
}
}
the ServerFunction static class
public static List<BdeskDocLib> GetDocLibs(bool onlyDocLibPerso)
{
string xmlContent = GetXml(URL_GETDOCLIBS);
List<BdeskDocLib> result = BdeskDocLib.GetListFromXml(xmlContent, onlyDocLibPerso);
return result;
}
private static String GetXml(string partialUrl)
{
string url = GenerateUrl(partialUrl);
DataRequestParam dataRequestParam = new DataRequestParam();
dataRequestParam.TargetUri = new Uri(url);
dataRequestParam.UserAgent = "BSynchro";
dataRequestParam.AuthentificationLogin = userLogin;
dataRequestParam.AuthentificationPassword = userPwd;
//HERE I START THE QUERY method
// NEED QUERY RETURNS A STRING or Task<String>
DataRequest requesteur = new DataRequest();
xmlResult=requesteur.Query(dataRequestParam);
if (CheckErrorConnexion(xmlResult) == false)
{
throw new Exception("Erreur du login ou mot de passe");
}
return xmlResult;
}
There is nothing good in blocking main UI (unless you really need to). But if you want to wait for your result you can make some use of async-await and TaskCompletitionSource - you can find more about on this blog and how to use TCS in this answer:
public static Task<string> myDownloadString(DataRequestParam dataRequestParam)
{
var tcs = new TaskCompletionSource<string>();
var web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += (s, e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
web.DownloadStringAsync(dataRequestParam.TargetUri);
return tcs.Task;
}
public async Task<string> Query(DataRequestParam dataRequestParam)
{
string Result = "";
try
{
Result = await myDownloadString(dataRequestParam);
}
catch (WebException we)
{
MessageBox.Show(we.Message);
return null;
}
return Result;
}
(I've not tried this code, there maight be some mistakes, but it should work)
Basing on this code you can also extend your WebClient with awaitable version of download string.

ReverseGeocodeQuery giving error

ReverseGeocodeQuery is giving error
1.in "GeoCoordinate(47.60887, -122.34094); " method must have a return type
2.in "reverseGeocode.GeoCoordinate line " reverseGeocode is a field but its used like a type..
ReverseGeocodeQuery reverseGeocode = new ReverseGeocodeQuery();
reverseGeocode.GeoCoordinate = new GeoCoordinate(47.60887, -122.34094);
reverseGeocode.QueryCompleted += reverseGeocode_QueryCompleted;
reverseGeocode.QueryAsync();
void reverseGeocode_QueryCompleted(objectsender,QueryCompletedEventArgs<IList<MapLocation>> e)
{
MapAddress geoAddress = e.Result[0].Information.Address;
}
i used namespace-- using Microsoft.Phone.Maps.Services;
how to rectify this errors..
GOT THE ANSWER
GeoCoordinateWatcher myLocationWatcher;
private GeoCoordinate MyCoordinate = null;
private async void GetCurrentCoordinate()
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
try
{
Geoposition currentPosition = await geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10));
_accuracy = currentPosition.Coordinate.Accuracy;
MyCoordinate = new GeoCoordinate(currentPosition.Coordinate.Latitude, currentPosition.Coordinate.Longitude);
if (MyReverseGeocodeQuery == null || !MyReverseGeocodeQuery.IsBusy)
{
MyReverseGeocodeQuery = new ReverseGeocodeQuery();
MyReverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(MyCoordinate.Latitude, MyCoordinate.Longitude);
LongitudeTextBlock.Text = MyCoordinate.Longitude.ToString();
LatitudeTextBlock.Text = MyCoordinate.Latitude.ToString();
MyReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted;
MyReverseGeocodeQuery.QueryAsync();
}
}
catch (Exception ex)
{
// ...
}
}
public void ReverseGeocodeQuery_QueryCompleted(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
labelResults.Text = "Current Location: " + address.City + ", " + address.State;
}
}
}
public void Button_Click(object sender, RoutedEventArgs e)
{
GetCurrentCoordinate();
}

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;
}
}