Wednesday, December 2, 2015

Get Address of Center Point of Google Map Android


Here I am placing the code snippet that can get address of center point of visible google map. Here I am using OnCameraChangeListener that will give address when map drag.

private GoogleMap googleMap;
googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {

    @Override
    public void onCameraChange(CameraPosition arg0) {
     search_location_view_TV.setText("Getting Address...");

     VisibleRegion visibleRegion = googleMap.getProjection().getVisibleRegion();
     Point x = googleMap.getProjection().toScreenLocation(visibleRegion.farRight);
     Point y = googleMap.getProjection().toScreenLocation(visibleRegion.nearLeft);
     Point centerPoint = new Point(x.x / 2, y.y / 2);
     LatLng centerFromPoint = googleMap.getProjection().fromScreenLocation(centerPoint);

     Log.d("Punto x", "x:" + x.x + "y:" + x.y);
     Log.d("Punto y", "y:" + y.x + "y:" + y.y);
     Log.d("MapFragment: ", "Center From Point: Long: " + centerFromPoint.longitude + " Lat" + centerFromPoint.latitude);

     String addressString = getCompleteAddressString(centerFromPoint.latitude, centerFromPoint.longitude);
     System.out.println("addressString..................."+addressString);
     search_location_view_TV.setText(addressString);
    }
   });

private String getCompleteAddressString(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;
 }

Reference:

googling.

No comments:

Post a Comment