c# - How can I make my json query wait for phone's location? -
here trying send json query latitude , longitude these values going nan though call showmylocationonthemap retrieves phone location first. how can make showmylocation method finish first , call json query. can me out?
public partial class closestbusstops : phoneapplicationpage { webclient webclient; public closestbusstops() { initializecomponent(); showmylocationonthemap(geopositionaccuracy.default); webclient = new webclient(); webclient.downloadstringcompleted += webclient_downloadstringcompleted; string jsonquery= "www.blabla.com?lat="+app.lat+"&lng="+app.lng; webclient.downloadstringasync(new uri(jsonquery)); } private async void showmylocationonthemap(geopositionaccuracy accuracy) { geolocator mygeolocator = new geolocator(); geoposition mygeoposition = await mygeolocator.getgeopositionasync(); geocoordinate mygeocoordinate = mygeoposition.coordinate; geocoordinate mygeocoordinate = coordinateconverter.convertgeocoordinate(mygeocoordinate); app.lat = mygeocoordinate.latitude; app.lng = mygeocoordinate.longitude; this.pushpin(this.mapwithmylocation, mygeocoordinate); } }
updated
protected override void onnavigatedto(system.windows.navigation.navigationeventargs e) { await showmylocationonthemap(geopositionaccuracy.default); } private async task showmylocationonthemap(geopositionaccuracy accuracy) { geolocator mygeolocator = new geolocator(); geoposition mygeoposition = await mygeolocator.getgeopositionasync(); geocoordinate mygeocoordinate = mygeoposition.coordinate; geocoordinate mygeocoordinate = coordinateconverter.convertgeocoordinate(mygeocoordinate); app.lat = mygeocoordinate.latitude; app.lng = mygeocoordinate.longitude; this.pushpin(this.mapwithmylocation, mygeocoordinate); }
showmylocationonthemap
async method, if want wait completion of method, need use await
keyword, this:
await showmylocationonthemap(geopositionaccuracy.default);
since cannot use await in constructor, need move somewhere else, onnavigatedto
method or loaded
event handler.
also return type of showmylocationonthemap
should task
instead of void
.
update:
public closestbusstops() { initializecomponent(); } private async task showmylocationonthemap(geopositionaccuracy accuracy) { geolocator mygeolocator = new geolocator(); geoposition mygeoposition = await mygeolocator.getgeopositionasync(); geocoordinate mygeocoordinate = mygeoposition.coordinate; app.lat = mygeocoordinate.latitude; app.lng = mygeocoordinate.longitude; this.pushpin(this.mapwithmylocation, mygeocoordinate); } protected async override void onnavigatedto(navigationeventargs e) { await showmylocationonthemap(geopositionaccuracy.default); webclient = new webclient(); webclient.downloadstringcompleted += webclient_downloadstringcompleted; string jsonquery= "www.blabla.com?lat="+app.lat+"&lng="+app.lng; webclient.downloadstringasync(new uri(jsonquery)); }
hope helps.
Comments
Post a Comment