2013-05-13 2 views
5

알아 두어야 할 것은 현재 위치의 주소를받을 수있는 곳에서 API가 있는지 알아야합니다. 현재 위치의 위도와 경도를받은 위치 관리자를 사용하지만 위치가 필요합니다. 주소.위도와 경도를 사용하여 특정 주소 가져 오기

아래의 API를 사용해 보았습니다.

http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat + "," + lon + &sensor=true" 

그러나 누군가 .Can 정확한 장소는 나에게 도움이 표시되지 않습니다. @ 감사

Geocoder 객체에서
+0

http://developer.android.com/reference/android/location/Geocoder.html – Selvin

+0

수 dublicate HTTP : // 유래이 사용할 수 있습니다 .com/questions/2296377/위도 및 경도 좌표에서 Google지도/2296416 # 2296416 – MBH

답변

15

, 당신은 getFromLocation(double, double, int) 메서드를 호출 할 수 있습니다.

같은 : -

private String getAddress(double latitude, double longitude) { 
     StringBuilder result = new StringBuilder(); 
     try { 
      Geocoder geocoder = new Geocoder(this, Locale.getDefault()); 
      List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); 
      if (addresses.size() > 0) { 
       Address address = addresses.get(0); 
       result.append(address.getLocality()).append("\n"); 
       result.append(address.getCountryName()); 
      } 
     } catch (IOException e) { 
      Log.e("tag", e.getMessage()); 
     } 

     return result.toString(); 
    } 

또 다른 좋은 대답이 여기 How to get city name from latitude and longitude coordinates in Google Maps?

+0

위의 코드를 사용해 주셔서 감사합니다. 정확한 주소 위치를 얻을 수 있습니까? –

+0

확인해 보겠습니다. +1 –

+0

예. 정확한 위치를 알려줍니다. –

2
String longti = "0"; 
    String lati = "0"; 
    LocationManager locationManager; 

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
       locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
         1000, 1, new MyLocationListners()); 

    final Location location = locationManager 
        .getLastKnownLocation(LocationManager.GPS_PROVIDER); 

//these are your longtitude and latitude 
     lati = String.valueOf(location.getLatitude()); 
     longti = String.valueOf(location.getLongitude()); 

//here we are getting the address using the geo codes(longtitude and latitude). 

String ad = getAddress(location.getLatitude(),location.getLongitude()); 


    private String getAddress(double LATITUDE, double LONGITUDE) { 
     String strAdd = ""; 
     Geocoder geocoder = new Geocoder(this, Locale.getDefault()); 
     try { 
      List<Address> addresses = geocoder.getFromLocation(LATITUDE, 
        LONGITUDE, 1); 
      if (addresses != null) { 
       Address returnedAddress = addresses.get(0); 
       StringBuilder strReturnedAddress = new StringBuilder(""); 

       for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) { 
        strReturnedAddress 
          .append(returnedAddress.getAddressLine(i)).append(
            "\n"); 
       } 
       strAdd = strReturnedAddress.toString(); 
       Log.w("My Current loction address", 
         "" + strReturnedAddress.toString()); 
      } else { 
       Log.w("My Current loction address", "No Address returned!"); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
      Log.w("My Current loction address", "Canont get Address!"); 
     } 
     return strAdd; 
    } 

public class MyLocationListners implements LocationListener { 

     @Override 
     public void onLocationChanged(Location location) { 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
     } 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
     } 

    } 

입니다 // 에있는 GPS와 인터넷을 확인 // 또한 때때로 위치가 늘 처음에 볼 수 몇 가지 // Google 서비스 문제로 인해 코드를 실행할 때 전화를 다시 시작해야합니다. //이 도움이 되었기를 바랍니다.

+1

휴대 전화를 다시 시작하면 주소가 있습니다. – Roadies

13

특정 Lat, Long에 대한 주소를 얻기위한 클래스를 만들었습니다.

public class getReverseGeoCoding { 
    private String Address1 = "", Address2 = "", City = "", State = "", Country = "", County = "", PIN = ""; 

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

     try { 

      JSONObject jsonObj = parser_Json.getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + Global.curLatitude + "," 
        + Global.curLongitude + "&sensor=true"); 
      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) == false || !long_name.equals(null) || long_name.length() > 0 || long_name != "") { 
         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")) { 
          // Address2 = Address2 + long_name + ", "; 
          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; 
         } 
        } 

        // JSONArray mtypes = zero2.getJSONArray("types"); 
        // String Type = mtypes.getString(0); 
        // Log.e(Type,long_name); 
       } 
      } 

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

    } 

    public String getAddress1() { 
     return Address1; 

    } 

    public String getAddress2() { 
     return Address2; 

    } 

    public String getCity() { 
     return City; 

    } 

    public String getState() { 
     return State; 

    } 

    public String getCountry() { 
     return Country; 

    } 

    public String getCounty() { 
     return County; 

    } 

    public String getPIN() { 
     return PIN; 

    } 

} 

JSON 파서 클래스

public class parser_Json { 
    public static JSONObject getJSONfromURL(String url) { 

     // initialize 
     InputStream is = null; 
     String result = ""; 
     JSONObject jObject = null; 

     // http post 
     try { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(url); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 

     } catch (Exception e) { 
      Log.e("log_tag", "Error in http connection " + e.toString()); 
     } 

     // convert response to string 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      result = sb.toString(); 
     } catch (Exception e) { 
      Log.e("log_tag", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 
      jObject = new JSONObject(result); 
     } catch (JSONException e) { 
      Log.e("log_tag", "Error parsing data " + e.toString()); 
     } 

     return jObject; 
    } 

} 
+0

Google지도 API 조건에 따르면 : "지도에 표시하지 않고 _지도를 찍는 것은 금지되어 있습니다 _"https://developers.google.com/maps/documentation/geocoding/ –

+0

을 참조하십시오. 'curLongitude'는 인식되지 않습니다. 내가 해결할 수있는 방법이 있니? – Marialena

+0

위도와 경도를 Global.curLongitude 및 Global.curLatitude에 전달하십시오. –

관련 문제