我一直在尝试对字符串进行地理编码以获取其坐标,但我的程序总是崩溃,因为每当我尝试使用 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 doesn't always return a value 和 geocoder.getFromLocationName returns only null
更新:
我也有一个 while 循环,但我过去最多尝试 10 次。有时,即使连接到互联网,它也不会返回任何内容。然后,我每次都使用 this 更可靠的方法来获取地址:
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 对象。你会看到刚刚发生了什么。
关于java - Android Geocoder getFromLocationName 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15182853/