![](/img/trans.png)
[英]getFromLocationName().size() returns always 0 - Android
[英]Android Geocoder getFromLocationName always returns null
我一直在嘗試對字符串進行地理編碼以獲取其坐標,但我的程序總是崩潰,因為當我嘗試使用getFromLocationName()
它返回null
。 我一直試圖解決這個問題幾個小時,但沒有任何工作。 這是我的代碼
public class MainActivity extends Activity {
private GoogleMap mMap;
List<Address> addresses;
MarkerOptions miami;
String myLocation = "Miami,Florida";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
}
if (mMap != null) {
Geocoder geocoder = new Geocoder(this);
double latitude = 0;
double longitude = 0;
while(addresses==null){
try {
addresses = geocoder.getFromLocationName(myLocation, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Address address = addresses.get(0);
if (addresses.size() > 0) {
latitude = address.getLatitude();
longitude = address.getLongitude();
}
LatLng City = new LatLng(latitude, longitude);
miami = new MarkerOptions().position(City).title("Miami");
mMap.addMarker(miami);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(City, 15));
}
}
地理編碼器並不總是返回值。 您可以嘗試在for循環中發送3次請求。 我應該能夠至少返回一次。 如果沒有,那么它們可能是連接問題,或者可能是其他問題,例如服務器拒絕回復您的請求。 試着看看這些主題:
Geocoder並不總是返回值 , geocoder.getFromLocationName僅返回null
更新:
我也有一個while循環,但我曾經嘗試過最多10次。 有時,它甚至沒有返回任何東西,即使它連接到互聯網。 然后,我使用這種更可靠的方式每次獲取地址:
public JSONObject getLocationInfo() {
HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
我這叫它如下:
JSONObject ret = getLocationInfo();
JSONObject location;
String location_string;
try {
location = ret.getJSONArray("results").getJSONObject(0);
location_string = location.getString("formatted_address");
Log.d("test", "formattted address:" + location_string);
} catch (JSONException e1) {
e1.printStackTrace();
}
希望這可以幫助。 我也厭倦了依靠地理編碼器。 這對我有用。 如果使用緯度和經度坐標替換URL,並在Web瀏覽器中查看返回的JSON對象。 你會看到剛剛發生的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.