Googleマップへのhttpリクエストを使用して高度の取得を試みます。残念ながら、私は応答を受け取りますが、私はそれを使用することはできません。このコードでは、場所の高度を設定しようとしましたが、機能しません。高度は、私のOnResponseメソッドでは正しいですが、それは他の場所では間違っています。理由は何ですか?httpリクエストからの返却値(Volleyを使用)
あなたがそうのようなコールバック・インターフェースを使用したいpublic class MainActivity extends AppCompatActivity {
Location location = new Location("");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
location.setLatitude(39.7391536);
location.setLongitude(-104.9847034);
getElevation();
Log.d("OnCreate", ""+location.getAltitude()); //print OnCreate: 0.0
}
public void getElevation(){
String urlName = "https://maps.googleapis.com/maps/api/elevation/json?locations="
+location.getLatitude()+","+location.getLongitude()
+"&key=mykey";
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest requester = new JsonObjectRequest(urlName, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
TextView mTxtDisplay = (TextView) findViewById(R.id.elevation);
double altitude;
try {
altitude = response.getJSONArray("results").getJSONObject(0).getDouble("elevation");
mTxtDisplay.setText("Elevation : " + altitude);
location.setAltitude(altitude);
Log.d("OnResponse", ""+location.getAltitude()); //print OnResponse: 1608.637939453125
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//TODO
}
});
queue.add(requester);
}
}
要求が非同期になるまでonResponse以内にその値を取得し、その値に依存しているものの実行を遅らせる、あなた要求が完了した後、 'location.getAltitude()'の結果を取得します。 –
他のすべての場所で間違っているとはどういう意味ですか?あなたはVolleyリクエストのみを表示しました。なぜあなたはその反応を使用できないのですか?あなたは明示的にonResponse内の値を取得していると言っていますので、あなたはそれを "使用しています" –
そして、Android用のGoogle Maps APIがあります。なぜあなたはVolleyを使う必要があるのかよく分かりません。 –