我想轉換一個文本字段中包含城市名稱的文本,並將其轉換爲經度和緯度。如何從城市名稱獲取經度,緯度android代碼
這是我做了什麼:
String location=city.getText().toString();
String inputLine = "";
String result = "";
location=location.replaceAll(" ", "%20");
String myUrl="http://maps.google.com/maps/geo?q="+location+"&output=csv";
try{
URL url=new URL(myUrl);
URLConnection urlConnection=url.openConnection();
BufferedReader in = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
while ((inputLine = in.readLine()) != null) {
result=inputLine;
}
lat = result.substring(6, result.lastIndexOf(","));
longi = result.substring(result.lastIndexOf(",") + 1);
}
catch(Exception e){
e.printStackTrace();
}
//////////////////////////////////
if (location=="")
{
latitude=loc.getLatitude();
longitude=loc.getLongitude();
}
else
{
latitude=Double.parseDouble(lat);
longitude=Double.parseDouble(longi);
}
但代碼不走else語句
我改變了URL這樣:
字符串myUrl =「HTTP:// maps.googleapis.com/maps/api/geocode/json?address="+location+「& sensor = true」;
,這是結果:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Nablus",
"short_name" : "Nablus",
"types" : [ "locality", "political" ]
}
],
"formatted_address" : "Nablus",
"geometry" : {
"location" : {
"lat" : 32.22504,
"lng" : 35.260971
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 32.2439165,
"lng" : 35.2929858
},
"southwest" : {
"lat" : 32.20615960000001,
"lng" : 35.2289562
}
}
},
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
我如何使用經度和緯度在我的代碼?
這是一個遠遠優於我提供的選項,如果Google更改JSON輸出的格式,OP將避免更新您的代碼 – mttdbrd
@mttdbrd我可以使用此代碼而不是 –
絕對是的 – mttdbrd