【发布时间】:2016-09-19 07:41:15
【问题描述】:
我尝试开发一个应用程序来跟踪用户的 GPS 数据。如果我有经度和纬度,我想在一个位置转换它们。 (正如您在我的代码中看到的那样,这是使用静态数据)
我的问题是将经度和纬度的变量放入 JSON 请求 - geocode/json?latlng=42.774955,18.955061",
最后应该留下 "...geocode/json?latlng"+lat+","+lng+...
每次我尝试这个我都会得到 NULL 值。请帮帮我。
public class MatchActivity extends AppCompatActivity {
private Button button;
private TextView textView;
private TextView textViewCity;
private LocationManager locationManager;
private LocationListener locationListener;
private RequestQueue requestQueue;
private double lat;
private double lng;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match);
button = (Button) findViewById(R.id.button_location);
textView = (TextView) findViewById(R.id.textView_Coordinates);
textViewCity = (TextView) findViewById(R.id.textCity);
requestQueue = Volley.newRequestQueue(this);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new myLocationlistener();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Location location = new Location("");
lng = location.getLongitude();
lat = location.getLatitude();
Log.e("Latitude", String.valueOf(lat));
Log.e("Longitude", String.valueOf(lng));
JsonObjectRequest request = new JsonObjectRequest("https://maps.googleapis.com/maps/api/geocode/json?latlng=42.774955,18.955061", new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String address = response.getJSONArray("results").getJSONObject(0).getString("formatted_address");
textViewCity.setText(address);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
}
});
}
private class myLocationlistener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
if(location != null){
lat = location.getLatitude();
lng = location.getLongitude();
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
}
【问题讨论】:
-
您正在创建一个新的
Location对象并使用它的坐标,而不是使用onLocationChanged(...)回调中设置的lat和lng值。 -
好的,但是我已经创建了一个新的 Location 对象
Location location = new Location("");@Titus -
是的,这就是问题所在,您应该使用更改位置时设置的值。
-
但是,如果我这样做,这是行不通的
lng = myLocationlistener(new myLocationlistener(lng)); -
如果位置发生变化,
lng和lat值将由onLocationChanged(...)方法设置。在onClick(...)中你不需要设置这个值,你只需要检查它们是否已经设置好了。