使用地理编码器和Android Google Maps API v2获取经度和纬度

时间:2013-03-29 21:13:32

标签: android google-maps maps android-maps-v2

我正在使用Google Maps API v2 for android并且正常运行。 但是,我正在尝试使用地理编码器来获取地址的经度和纬度,但没有成功。

它已经改变了从v2开始的方式吗?

我正在使用传统代码

Geocoder gc = new Geocoder(context);
//...
  List<Address> list = gc.getFromLocationName("1600 Amphitheatre Parkway, Mountain View, CA", 1);

  Address address = list.get(0);

  double lat = address.getLatitude();
  double lng = address.getLongitude();
//...

始终返回强制关闭,Log不解决任何问题。 使用try / catch块时,打开地图但始终使用相同的位置 使用Internet权限,我在项目中也包含了COARSE_LOCATION 我在这里和其他网站上使用过各种代码,但没有成功。

提前谢谢。

5 个答案:

答案 0 :(得分:53)

使用此示例url尝试此解决方案:

  

http://maps.google.com/maps/api/geocode/json?address=mumbai&sensor=false

以[{1}}格式返回json lat/lng的数据。

address

希望这会对你有所帮助。

答案 1 :(得分:8)

试试这个。

private void getLatLongFromAddress(String address)
{
    double lat= 0.0, lng= 0.0;

    Geocoder geoCoder = new Geocoder(this, Locale.getDefault());    
    try 
    {
        List<Address> addresses = geoCoder.getFromLocationName(address , 1);
        if (addresses.size() > 0) 
        {            
            GeoPoint p = new GeoPoint(
                    (int) (addresses.get(0).getLatitude() * 1E6), 
                    (int) (addresses.get(0).getLongitude() * 1E6));

            lat=p.getLatitudeE6()/1E6;
            lng=p.getLongitudeE6()/1E6;

            Log.d("Latitude", ""+lat);
            Log.d("Longitude", ""+lng);
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

答案 2 :(得分:2)

由于HttpClient已被折旧,您可以尝试使用Asynctask的以下代码(还要注意我们需要将地址编码为URL):

public class GeoCoding extends AsyncTask<Void, Void, Void> {
    private String address;
    private static final String TAG = GeoCoding.class.getSimpleName();
    JSONObject jsonObj;
    String URL;
    private String Address1 = "", Address2 = "", City = "", State = "", Country = "", County = "", PIN = "", Area="";
    private  double latitude, longitude;
    HttpURLConnection connection;
    BufferedReader br;
    StringBuilder sb ;

    public GeoCoding(String address){
        this.address = address;
    }

    public String getArea(){
        return Area;
    }

    public void getAddress() {
        Address1 = "";
        Address2 = "";
        City = "";
        State = "";
        Country = "";
        County = "";
        PIN = "";
        Area ="";

        try {

            String Status = jsonObj.getString("status");
            if (Status.equalsIgnoreCase("OK")) {
                JSONArray Results = jsonObj.getJSONArray("results");
                JSONObject zero = Results.getJSONObject(0);
                JSONArray address_components = zero.getJSONArray("address_components");

                for (int i = 0; i < address_components.length(); i++) {
                    JSONObject zero2 = address_components.getJSONObject(i);
                    String long_name = zero2.getString("long_name");
                    JSONArray mtypes = zero2.getJSONArray("types");
                    String Type = mtypes.getString(0);

                    if (! TextUtils.isEmpty(long_name) || !long_name.equals(null) || long_name.length() > 0 || !long_name.equals("")) {
                        if (Type.equalsIgnoreCase("street_number")) {
                            Address1 = long_name + " ";
                        } else if (Type.equalsIgnoreCase("route")) {
                            Address1 = Address1 + long_name;
                        } else if (Type.equalsIgnoreCase("sublocality")) {
                            Address2 = long_name;
                        } else if (Type.equalsIgnoreCase("locality")) {
                            City = long_name;
                        } else if (Type.equalsIgnoreCase("administrative_area_level_2")) {
                            County = long_name;
                        } else if (Type.equalsIgnoreCase("administrative_area_level_1")) {
                            State = long_name;
                        } else if (Type.equalsIgnoreCase("country")) {
                            Country = long_name;
                        } else if (Type.equalsIgnoreCase("postal_code")) {
                            PIN = long_name;
                        }else if( Type.equalsIgnoreCase("neighborhood")){
                            Area = long_name;
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public void getGeoPoint(){
        try{
             longitude = ((JSONArray)jsonObj.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lng");
            latitude = ((JSONArray)jsonObj.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lat");

        }catch (Exception e){
            e.printStackTrace();
        }

    }


    @Override
    protected Void doInBackground(Void... params)  {
        try {
            StringBuilder urlStringBuilder = new StringBuilder("http://maps.google.com/maps/api/geocode/json");
            urlStringBuilder.append("?address=" + URLEncoder.encode(address, "utf8"));
            urlStringBuilder.append("&sensor=false");
            URL = urlStringBuilder.toString();
            Log.d(TAG, "URL: " + URL);

            URL url = new URL(URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.connect();
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb = sb.append(line + "\n");
            }
        }catch (Exception e){e.printStackTrace(); }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        try {
            Log.d(TAG, "response code: " + connection.getResponseCode());
            jsonObj = new JSONObject(sb.toString());
            Log.d(TAG, "JSON obj: " + jsonObj);
            getAddress();
            Log.d(TAG, "area is: " + getArea());
            getGeoPoint();
            Log.d("latitude", "" + latitude);
            Log.d("longitude", "" + longitude);


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onPostExecute(aVoid);
    }
}

答案 3 :(得分:0)

对我有用的简单修正是在设备上启用互联网连接。建议Pxaml

答案 4 :(得分:-10)

您可以通过这个简单的代码

获取当前位置的纬度和经度
GPS_Location mGPS = new GPS_Location(MyApplication.getAppContext());

    if (mGPS.canGetLocation) {

        mLat = mGPS.getLatitude();
        mLong = mGPS.getLongitude();

    } else {
        System.out.println("cannot find");
    }

您必须向应用添加gps和其他权限