緯度・経度から郵便番号を取得する
Geocoderクラスを使って緯度と経度から郵便番号を取得する方法です。
題名は郵便番号を取得するとなっていますが、住所も取得できます。
自分が郵便番号というキーワードで検索していたため自分用メモです。
developer.android.com
Gercoderを使用して住所(郵便番号)を使用する場合はバックエンドサービスを使用するので、インターネットに繋がっていないと取得が出来ません。
Gercoderが使用可能かどうかはisPresent()メソッドで確認します。
コードのサンプルはこんな感じです。
private String retrievePostalCode(Location location) { final Geocoder geocoder = new Geocoder(getApplicationContext()); if (geocoder.isPresent()) { try { List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); if (addresses != null) { for (Address address : addresses) { if (address.getLocality() != null && address.getPostalCode() != null) { Log.i(TAG,address.getPostalCode()); return address.getPostalCode(); } } } else Log.i(TAG,"No location found..!"); } catch (IOException e) { e.printStackTrace(); } } else { Log.i(TAG,"Geocoder is not present"); } return null; }