ani*_*k25 12 java eclipse android android-mapview google-maps-android-api-2
我一直在尝试对字符串进行地理编码以获取其坐标但我的程序总是崩溃,因为当我尝试使用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));
}
}
Run Code Online (Sandbox Code Playgroud)
Sho*_*uri 25
地理编码器并不总是返回值.您可以尝试在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;
}
Run Code Online (Sandbox Code Playgroud)
我这叫它如下:
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();
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.我也厌倦了依靠地理编码器.这对我有用.如果使用纬度和经度坐标替换URL,并在Web浏览器中查看返回的JSON对象.你会看到刚刚发生的事情.
| 归档时间: |
|
| 查看次数: |
22170 次 |
| 最近记录: |