安卓地理编码器getFromLocationName总是返回null

14

我一直在尝试对一个字符串进行地理编码以获取其坐标,但我的程序总是崩溃,因为每当我尝试使用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));

        }
}

有人会回答这个问题吗? - anishk25
1个回答

27
Geocoder并不总是会返回值。您可以尝试在for循环中发送请求3次。至少应该能够返回一次。如果没有,则可能存在连接问题或其他问题,例如服务器未回复您的请求。请尝试查看以下线程:

Geocoder不总是返回值geocoder.getFromLocationName仅返回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对象,你就会明白发生了什么。

但是我有一个 while 循环来确保我得到 geocoder 的值,而它一直在无限循环。 - anishk25
请查看我的更新答案。希望它能解决你想要实现的问题。 - Shobhit Puri
1
我遇到了同样的问题。我发现设备上的NetworkLocator已经停止工作或因某些原因被终止(不在我们的控制范围内)。您可以通过重新启动设备来确认这一点。现在它应该可以工作了(因为NetworkLocator也会重新启动)。 - Archie.bpgc
1
有三种情况。 1.第一次获取位置信息失败,然后您尝试循环获取4th/5th等次数...2.无论循环多少次,都无法获取任何位置详细信息,因此您认为服务可能暂时关闭,并采用上述解决方案3.如我在上面的评论中所解释的那样,除非重新启动设备,否则它将永远不起作用,这意味着我将始终经历步骤1和步骤2,每次可能需要2-5秒钟。没有人想要等待这么长时间只为了获得像addressline这样的单个数据。对于情况3有更好的解决方案吗? - Archie.bpgc
1
@Ben 看看这个链接:https://dev59.com/MGUo5IYBdhLWcg3w3ygF - Shobhit Puri
显示剩余11条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接