我可以使用langitude和latitude从google transit api中检索数据,但不能使用directions
属性。这是我到目前为止所做的事情
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try
{
String Lat=Double.toString(22.508507985602836);
String Long=Double.toString(73.474991977022533);
String Address = ReadAddressFromWebService(Lat,Long);
Toast.makeText(this,Address, Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Log.e("error","Json parsing error :"+ e.toString());
Toast.makeText(this,e.toString(), Toast.LENGTH_LONG).show();
}
}
public String ReadAddressFromWebService(String latitude, String longitude) {
String Address="";
StringBuffer sb=new StringBuffer();
sb.append("http://maps.googleapis.com/maps/api/geocode/json?latlng="+
latitude +","+longitude +"&sensor=false");
String url=sb.toString();
HttpClient httpClient=new DefaultHttpClient();
Log.i("","HTTP client created");
String responseData="";
try {
HttpResponse response=httpClient.execute(new HttpGet(url));
response.addHeader("Accept-Language", "it-IT");
HttpEntity entity=response.getEntity();
Log.i("", "HTTP Response arrived");
BufferedReader bf=new BufferedReader(new
InputStreamReader((entity.getContent()),"UTF-8"));
String line="";
Log.i("","Start buffre reading");
while((line=bf.readLine())!=null){
responseData=responseData+line;
}
JSONObject jsonObj = new JSONObject(responseData);
JSONArray resultArry = jsonObj.getJSONArray("results");
Address = resultArry.getJSONObject(0).getString("formatted_address").toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Address;
}
}
我尝试以这种方式更改StringBuffer
:sb.append("http://maps.googleapis.com/maps/api/directions/json?origin="+
latitude +"&destination="+longitude +"&sensor=false");
但我用to to看到结果没有显示任何东西..是空的,我在行中得到一个JSONObject错误:地址= resultArry.getJSONObject(0).getString("formatted_address").toString();
所以,这是我要解析的json:http://maps.googleapis.com/maps/api/directions/json?origin=vicenza&destination=costabissara&sensor=false
我将显示路线..当然我改变了:
`JSONArray resultArry = jsonObj.getJSONArray(“results”);
Address = resultArry.getJSONObject(0).getString("formatted_address").toString();`
到
`JSONArray resultArry = jsonObj.getJSONArray(“routes”);
Address = resultArry.getJSONObject(0).getString("legs").toString();`
但没有成功..
答案 0 :(得分:1)
我已经尝试过你的例子,但它确实奏效了。我必须做的唯一改变是将坐标传递给ReadAddressFromWebService
我传递了原点和目标字符串:
String from = "vicenza";
String to = "costabissara";
String Address = ReadAddressFromWebService(from,to);
origin
和destination
适用于位置名称而不是坐标。