在Android中使用Geocoder和GPS无法获得Locality

时间:2014-12-12 09:39:49

标签: android geocoding google-geocoder

您好我正在尝试使用geoCoder位置和gps获取城市,地区,纬度,经度

它正在使用最大的设备但不能处理galaxy s4,索尼或三星平板电脑

更具体一点是它不适用于xperia z1(android 4.1.1。,型号C1505)

以下是地理编码器的代码段

Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
     List<Address> addresses;
    try {
        addresses = geocoder.getFromLocation(lat, longi, 1);
        Log.e("geocoder size", addresses.get(0).getLocality()+"");


        //setCityName(addresses.get(0).getLocality());
        //setStateName(addresses.get(0).getAdminArea());
        //setCountryName(addresses.get(0).getCountryName());

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    }

1 个答案:

答案 0 :(得分:1)

实际上,兄弟有时GEOCoder不会完美运作所以你必须这样使用:

JSONObject ret = getLocationInfo(latlng_Source.latitude, latlng_Source.longitude);
                Log.e("address string", ret.toString());

                JSONObject location;

                try
                {
                    location = ret.getJSONArray("results").getJSONObject(0);
                    mCuurentAddress = location.getString("formatted_address");
                    Log.d("test", "formattted address:" + mCuurentAddress);
                }
                catch (JSONException e1)
                {
                    e1.printStackTrace();

                }



public  JSONObject getLocationInfo(double lat, double lng)
    {

        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;
    }

我希望这会对你有所帮助。这是永久的解决方案。