Sunday, 13 July 2014

Get Latitude & Longitude from Address in Android

Below is the simple code to get the Latitude & Longitude from the zip code of  city.

 private Geocoder geocode = new Geocoder(this);  
 String address = "<zip code>";  
 /**  
 * Method to get latitude,longitude from address.  
 * @param addressStr-Address or zip code of city.  
 * @param gc- Geocoder instance.  
 *   
 */  
 public static void geocodeAddress(String addressStr, Geocoder gc) {  
     Address address = null;  
     List<Address> addressList = null;  
    try {  
       if (!TextUtils.isEmpty(addressStr)) {  
        addressList = gc.getFromLocationName(addressStr, 5);  
      }  
     } catch (Exception e) {  
       e.printStackTrace();  
     }  
    if (null != addressList && addressList.size() > 0) {  
           address = addressList.get(0);  
     }  
    if (null != address && address.hasLatitude()  
     && address.hasLongitude()) {  
           latitude = address.getLatitude();  
           longitude = address.getLongitude();  
       }  
    if (latitude != null && longitude != null)  
     {  
     mGoogleMap2.addMarker(new MarkerOptions()  
        .position(new LatLng(latitude, longitude)));  
    mGoogleMap2.moveCamera(CameraUpdateFactory.newLatLngZoom(  
       new LatLng(latitude, longitude), 10));  
     }  
  }