【问题标题】:get latitude and longitude with geocoder and android Google Maps API v2使用地理编码器和 android Google Maps API v2 获取纬度和经度
【发布时间】:2013-03-20 15:24:13
【问题描述】:

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

它改变了 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 块时,打开地图但总是在同一个位置 使用互联网权限,我在项目中也包含了COARSE_LOCATION 我使用了这里和其他网站上的各种代码,但没有成功。

提前谢谢你。

【问题讨论】:

  • 你有android.permission.INTERNET权限集吗?
  • 你说日志什么都解决不了,也许你还是应该把它包括进去(我敢打赌它确实有一些关于什么是错误的线索)。
  • 我有互联网权限,日志,谢谢:03-29 22:25:10.922: E/AndroidRuntime(4359): java.lang.RuntimeException: Unable to start activity ComponentInfo{blue.ninja. master/blue.ninja.master.Hola}: java.lang.NullPointerException 03-29 22:25:10.922: E/AndroidRuntime(4359): at android.app.ActivityThread.access$600(ActivityThread.java:130) 03- 29 22:25:10.922:E/AndroidRuntime(4359):在 android.app.ActivityThread 03-29 22:25:10.922:E/AndroidRuntime(4359):原因:java.lang.NullPointerException 03-29 22:25 :10.922: E/AndroidRuntime(4359): 在 blue.ninja.master.Hola.onCreate(Hola.java:50)

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


【解决方案1】:

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

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

json 格式返回数据,其中lat/lngaddress

private class DataLongOperationAsynchTask extends AsyncTask<String, Void, String[]> {
   ProgressDialog dialog = new ProgressDialog(MainActivity.this);
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.setMessage("Please wait...");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @Override
    protected String[] doInBackground(String... params) {
        String response;
        try {
            response = getLatLongByURL("http://maps.google.com/maps/api/geocode/json?address=mumbai&sensor=false");
            Log.d("response",""+response);
            return new String[]{response};
        } catch (Exception e) {
            return new String[]{"error"};
        }
    }

    @Override
    protected void onPostExecute(String... result) {
        try {
            JSONObject jsonObject = new JSONObject(result[0]);

            double lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lng");

            double lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lat");

            Log.d("latitude", "" + lat);
            Log.d("longitude", "" + lng);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}


public String getLatLongByURL(String requestURL) {
    URL url;
    String response = "";
    try {
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        int responseCode = conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = br.readLine()) != null) {
                response += line;
            }
        } else {
            response = "";
        }

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

希望对你有帮助。

【讨论】:

  • @AmolSawant96Kuli 这个解决方案工作正常吗?我问你是因为我发现 Geocoder 不能很好地工作......
  • 是客户端地理编码还是服务器端?不幸的是,我找不到代码的区别,因为那里没有合适的例子。
  • 你能更新代码吗?似乎 HttpClient 已被弃用,并且不再在 Android 6 上可用。
  • @android 开发者,感谢更新。我根据新的新 Android 版本 6 更新了我的代码。
  • @AmolSawant96Kuli 谢谢。话说,这样用谷歌的网站真的可以吗?不需要注册他们什么的?
【解决方案2】:

试试这个。

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

【讨论】:

  • 看来问题是android的一个bug:code.google.com/p/android/issues/detail?id=8816 ...我不知道如何解决它:(((
  • @MiguelC : 你能用地址找到 LatLng 吗?我面临同样的问题。
  • 我发现对我来说结果总是在错误的国家(即使我在地址中包含了国家)。
【解决方案3】:

由于 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);
    }
}

【讨论】:

    【解决方案4】:

    对我有用的一个简单纠正方法是在设备上启用互联网连接。 Pxaml的建议。

    【讨论】:

      【解决方案5】:

      你可以通过这个简单的代码得到当前位置的经纬度

      GPS_Location mGPS = new GPS_Location(MyApplication.getAppContext());
      
          if (mGPS.canGetLocation) {
      
              mLat = mGPS.getLatitude();
              mLong = mGPS.getLongitude();
      
          } else {
              System.out.println("cannot find");
          }
      

      您必须为您的应用添加 GPS 和其他权限

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-16
        • 1970-01-01
        • 2011-07-11
        • 1970-01-01
        相关资源
        最近更新 更多