Exemple #1
0
  private void getLocality(Location location) {
    if (location != null) {
      longitude = location.getLongitude();
      latitude = location.getLatitude();
      try {
        address = (Address) geocoder.getFromLocation(latitude, longitude, 1).toArray()[0];
        String locality = address.getSubAdminArea();
        if (locality == null) {
          locality = address.getLocality();
        }

        if (locality == null) {
          locality = address.getSubAdminArea();
        }
        if (locality == null) {
          locality = address.getAddressLine(0);
        }
        Toast t = Toast.makeText(getApplicationContext(), locality, Toast.LENGTH_LONG);
        t.show();
      } catch (Exception e) {
        System.out.println(e);
        //            }
        //            longitude = location.getLongitude();
        //            latitude = location.getLatitude();
        //            Toast t = Toast.makeText(getApplicationContext(),
        //                    String.format("long: " + longitude + "\nlat: " + latitude),
        // Toast.LENGTH_LONG);
        //            t.show();
      }
    } else {
      Toast t = Toast.makeText(getApplicationContext(), "NO LAST LOCATION", Toast.LENGTH_SHORT);
      t.show();
    }
  }
 @Background
 void task(String r, String num, DialogInterface dialog) {
   if (currentAddress == null) {
     return;
   }
   String addressCompl =
       currentAddress.getSubAdminArea() != null
           ? currentAddress.getSubAdminArea()
           : currentAddress.getLocality();
   List<Address> addresses =
       GPSUtils.getFromLocationName(getActivity(), r + ", " + num + " - " + (addressCompl));
   if (addresses.isEmpty()) {
     toast(getString(R.string.address_not_found));
     dialog.dismiss();
   } else {
     final Address address = addresses.get(0);
     street = address.getThoroughfare();
     if (!TextUtils.isEmpty(num) && StringUtils.isNumeric(num.substring(0, 1))) {
       number = num;
     } else {
       number = "";
     }
     updateUiAdapter(address);
   }
 }
 @Background
 void dialogNumberTask(String num1, DialogInterface dialog) {
   List<Address> addresses =
       GPSUtils.getFromLocationName(
           getActivity(),
           street
               + ", "
               + num1
               + " - "
               + (currentAddress.getSubAdminArea() != null
                   ? currentAddress.getSubAdminArea()
                   : currentAddress.getLocality()));
   if (addresses.isEmpty()) {
     toast(getString(R.string.address_not_found));
     dialog.dismiss();
   } else {
     final Address address = addresses.get(0);
     street = address.getThoroughfare();
     if (!num1.isEmpty() && StringUtils.isNumeric(num1.substring(0, 1))) {
       number = num1;
     } else {
       number = "";
     }
     updateUiAdapter(address);
   }
 }
 /**
  * Format the address
  *
  * @param address the address that need to be formated
  * @return formated address
  */
 private static String formatAddress(Address address) {
   StringBuilder stringBuilder = new StringBuilder();
   String location = "";
   location = address.getLocality();
   stringBuilder.append(
       location != null
           ? (location + ", ")
           : (address.getSubAdminArea() != null) ? (address.getSubAdminArea() + ", ") : "");
   location = address.getAdminArea();
   stringBuilder.append(location != null ? (location + ", ") : "");
   stringBuilder.append(location != null ? address.getCountryName() : address.getCountryCode());
   return stringBuilder.toString();
 }
  public static void logAddress(String logTag, Address address) {

    int maxAddressLineIndex = address.getMaxAddressLineIndex();
    for (int i = 0; i <= maxAddressLineIndex; i++) {
      String addressLine = address.getAddressLine(i);
      Log.d(logTag, i + ":  " + addressLine);
    }

    double latitude = 0.0d;
    double longitude = 0.0d;

    boolean hasLatitude = address.hasLatitude();
    if (hasLatitude) {
      latitude = address.getLatitude();
    }
    boolean hasLongitude = address.hasLongitude();
    if (hasLongitude) {
      longitude = address.getLongitude();
    }

    String adminArea = address.getAdminArea();
    String featureName = address.getFeatureName();
    String locality = address.getLocality();
    String postalCode = address.getPostalCode();
    String premises = address.getPremises();
    String subAdminArea = address.getSubAdminArea();
    String subLocality = address.getSubLocality();
    String subThoroughfare = address.getSubThoroughfare();
    String thoroughfare = address.getThoroughfare();
    String phone = address.getPhone();
    String url = address.getUrl();

    // logValue(logTag, "latitude", hasLatitude, latitude);
    // logValue(logTag, "longitude", hasLongitude, longitude);
    //        logValue(logTag,"adminArea", adminArea);
    //        logValue(logTag,"featureName", featureName);
    //        logValue(logTag,"locality", locality);
    //        logValue(logTag,"postalCode", postalCode);
    //        logValue(logTag,"premises", premises);
    //        logValue(logTag,"subThoroughfare", subThoroughfare);
    //        logValue(logTag,"subAdminArea",subAdminArea);
    //        logValue(logTag,"subLocality", subLocality);
    //        logValue(logTag,"thoroughfare", thoroughfare);
    //        logValue(logTag,"phone", phone);
    //        logValue(logTag,"url", url);
  }
  /**
   * Display details for the geocoded address returned by map
   *
   * <p>This method is intended for usage with create_client_entry_address.xml
   *
   * @param activity current activity
   * @param geoAddress entity geo addresses
   */
  public static void displayGeocodedAddress(
      Activity activity, android.location.Address geoAddress) {
    final String methodName = "displayGeocodedAddress";
    // Alog.d(classTag, methodName);

    if (geoAddress == null) {
      Alog.e(methodName, "Geocoded address is not set. Cannot display address");
      return;
    }

    // Parse the geocoded Address into Mambu's Address class (5 lines)
    // final int totalLines = geoAddress.getMaxAddressLineIndex();
    // Get the whole string first
    String mapAddressString = MapActivity.getAddressString(geoAddress);
    Alog.d(methodName, "Returned overall address=" + mapAddressString);

    if (TextUtils.isEmpty(mapAddressString)) {
      // Shouldn't happen but just in case
      Alog.e(methodName, "Geocoded Address has no associated data. Nothing to display?");
      return;
    }
    // Set LatLng in the Address field from the returned Geocoded data
    EditText addressLineOneTxt = (EditText) activity.findViewById(R.id.streetAddressLine1);
    // We don't pit anything into line twp - for now
    EditText addressLineTwoTxt = (EditText) activity.findViewById(R.id.streetAddressLine2);
    EditText cityTxt = (EditText) activity.findViewById(R.id.streetAddressCity);
    EditText stateTxt = (EditText) activity.findViewById(R.id.streetAddressState);
    EditText zipPostCodeTxt = (EditText) activity.findViewById(R.id.streetAddressPostCode);
    EditText countryTxt = (EditText) activity.findViewById(R.id.streetAddressCountry);

    TextView latitudeTxt = (TextView) activity.findViewById(R.id.latitude);
    TextView longitudeTxt = (TextView) activity.findViewById(R.id.longitude);

    final int updateColor =
        activity.getResources().getColor(R.color.green_mambu_dark); // green_mambu

    double positionLatitude = geoAddress.getLatitude();
    double positionLongitude = geoAddress.getLongitude();
    Alog.d(
        methodName,
        "Displaying returned Latitude=" + positionLatitude + "\tLongitude=" + positionLongitude);
    if (latitudeTxt != null && longitudeTxt != null) {
      // Save currently displayed values and check if they changed
      BigDecimal currentLatitude = AppHelper.formatPosition(latitudeTxt.getText().toString());
      BigDecimal currentLongitude = AppHelper.formatPosition(longitudeTxt.getText().toString());
      // Alog.d(methodName, "Current: Latitude=" + currentLatitude + "\tLongitude=" +
      // currentLongitude);
      // Get the difference with new ones
      final double invPosition = -1.0f;
      double currentLatDbl = currentLatitude == null ? invPosition : currentLatitude.doubleValue();
      double currentLongDbl =
          currentLongitude == null ? invPosition : currentLongitude.doubleValue();

      // Display in Red if the difference greater than max allowed
      final double maxDif = 0.000001f;
      boolean latChanged = false;
      if (Math.abs(currentLatDbl - positionLatitude) >= maxDif) {
        latChanged = true;
      }
      boolean longChanged = false;
      if (Math.abs(currentLongDbl - positionLongitude) >= maxDif) {
        longChanged = true;
      }
      // Alog.d(methodName, "Latitude changed=" + latChanged + "\tLongitude Changed=" +
      // longChanged);

      // Display Latitude
      String latitudeStr = AppHelper.formatPosition(positionLatitude);
      latitudeTxt.setText(latitudeStr);
      int latColor = latChanged ? updateColor : defaultColor;
      int typeface = latChanged ? updateTypeface : defaultTypeface;
      latitudeTxt.setTextColor(latColor);
      latitudeTxt.setTypeface(null, typeface);

      // Display Longitude
      String longitudeStr = AppHelper.formatPosition(positionLongitude);
      longitudeTxt.setText(longitudeStr);
      int longColor = longChanged ? updateColor : defaultColor;
      typeface = longChanged ? updateTypeface : defaultTypeface;
      longitudeTxt.setTextColor(longColor);
      longitudeTxt.setTypeface(null, typeface);
    }
    // Display Google address as returned by map
    TableRow mapAddressRow = (TableRow) activity.findViewById(R.id.mapAddressRow);
    if (mapAddressRow != null) {
      mapAddressRow.setVisibility(View.VISIBLE);
    }
    TextView mapAddress = (TextView) activity.findViewById(R.id.mapAddress);
    if (mapAddress != null) {
      mapAddress.setVisibility(View.VISIBLE);
      final String googlePrefix = "Google: ";
      final String displayGeoAddress = googlePrefix + mapAddressString;
      mapAddress.setText(displayGeoAddress);
      mapAddress.setTypeface(null, Typeface.ITALIC);
    }
    // We have some address data. See whatever specific information we can get from this location

    // Get the data
    // Alog.d(methodName, "Geocoded address has lines count=" + totalLines);

    // Get the address in pieces. If any part is found - display and remove it from the original
    // address string.
    // Display what's left in line 1 and line 2

    // Make a working copy to keep track of still not parsed lines
    String remainingAddress = mapAddressString;

    // Get Country name and Country Code
    // Set Country field
    String countryName = geoAddress.getCountryName();
    String countryCode = geoAddress.getCountryCode();
    // Alog.d(methodName, "Updating Country");
    remainingAddress =
        setUpdatedValue(countryTxt, countryName, countryCode, updateColor, remainingAddress);

    // Get City field
    String locality = geoAddress.getLocality();
    String subLocality = geoAddress.getSubLocality();
    // Alog.d(methodName, "Updating City");
    remainingAddress =
        setUpdatedValue(cityTxt, locality, subLocality, updateColor, remainingAddress);

    // Get State /province
    String adminAreas = geoAddress.getAdminArea();
    String subAdminArea = geoAddress.getSubAdminArea();
    // Alog.d(methodName, "Updating State");
    remainingAddress =
        setUpdatedValue(stateTxt, adminAreas, subAdminArea, updateColor, remainingAddress);

    // Get Postal Code
    String postalCode = geoAddress.getPostalCode();
    // Alog.d(methodName, "Updating Postal Code");
    remainingAddress =
        setUpdatedValue(zipPostCodeTxt, postalCode, null, updateColor, remainingAddress);

    // We are not using Feature name
    // String featureName = geoAddress.getFeatureName();

    // See what's is the remaining string
    remainingAddress = remainingAddress == null ? "" : remainingAddress.replaceAll(",", " ");
    String[] remainingLines = remainingAddress.split("\\n");
    // int numLines = remainingLines.length;
    // Alog.d(methodName, "Remaining lines count=" + numLines);

    // Whatever was not extracted already (as City, Country, PostalCode, etc,) goes into Line 1 and
    // Line 2
    // Get Line 1 and save it as Mambu's Line 1
    String line1 = remainingLines[0].replaceAll("\\s", " ");
    line1 = line1.trim();
    // Update line 1 only if it was empty and geo address does have line 1
    boolean wasLine1Empty =
        TextUtils.isEmpty(addressLineOneTxt.getText()) && !TextUtils.isEmpty(line1);
    if (wasLine1Empty) {
      addressLineOneTxt.setText(line1);
    }
    // Define color to show line 1 is not changes but needs to be reviewed as the location changes
    final int unchangedColor = activity.getResources().getColor(R.color.dark_yellow);
    int theColor = wasLine1Empty ? updateColor : unchangedColor; // defaultColor
    int theTypeface = wasLine1Empty ? updateTypeface : updateTypeface; // defaultTypeface

    addressLineOneTxt.setTextColor(theColor);
    addressLineOneTxt.setTypeface(null, theTypeface);

    // Remove line 1 form the original string
    if (!TextUtils.isEmpty(line1)) {
      remainingAddress = remainingAddress.replace(line1, "");
    }

    // If anything still remaining, put it in Mambu's Line 2
    remainingAddress = remainingAddress.replace("\\s", " ");
    remainingAddress = remainingAddress.replace("\n", "");
    String line2 = remainingAddress.trim();
    if (line2.length() > 0) {
      // Do Not set line 2 for now
      // addressLineTwoTxt.setText(line2);
    }
    // Set the same colors as for line 1 .
    addressLineTwoTxt.setTextColor(theColor);
    addressLineTwoTxt.setTypeface(null, theTypeface);

    // Alog.d(methodName, "Country Name=" + countryName + " Country code=" + countryCode + " Postal
    // code="
    // + postalCode + "  Admin area=" + adminAreas + " Feature Name=" + featureName + " Locality=" +
    // locality
    // + "  Sub Locality=" + subLocality);

    Alog.d(methodName, "Remaining  address=" + remainingAddress);
    // Alog.d("Line1 =" + line1 + "\nLine 2=" + line2);

  }
    /**
     * Get a Geocoder instance, get the latitude and longitude look up the address, and return it
     *
     * @params params One or more Location objects
     * @return A string containing the address of the current location, or an empty string if no
     *     address can be found, or an error message
     */
    @Override
    protected String doInBackground(Location... params) {

      Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
      // Get the current location from the input parameter list
      Location loc = params[0];
      // Create a list to contain the result address
      List<Address> addresses = null;
      try {
        /*
         * Return 1 address.
         */
        addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
      } catch (IOException e1) {
        Log.e("LocationSampleActivity", "IO Exception in getFromLocation()");
        e1.printStackTrace();
        return ("IO Exception trying to get address");
      } catch (IllegalArgumentException e2) {
        // Error message to post in the log
        String errorString =
            "Illegal arguments "
                + Double.toString(loc.getLatitude())
                + " , "
                + Double.toString(loc.getLongitude())
                + " passed to address service";
        Log.e("LocationSampleActivity", errorString);
        e2.printStackTrace();
        return errorString;
      }
      // If the reverse geocode returned an address
      if (addresses != null && addresses.size() > 0) {
        // Get the first address
        Address address = addresses.get(0);
        /*
         * Format the first line of address (if available), city, and
         * country name.
         */

        String addressMessage = address.getAddressLine(0) + " " + address.getAddressLine(1);
        String addressText =
            String.format(
                "%s, %s, %s, %s",
                // If there's a street address, add it
                address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                // Locality is usually a city
                address.getLocality(),
                address.getPremises(),
                // The country of the address
                address.getCountryName());

        // streetAddress = address.getAddressLine(1);
        // Return the text

        streetadd =
            address.getAddressLine(0)
                + ","
                + address.getAddressLine(1)
                + ","
                + address.getCountryName();

        Log.e(
            "TAG",
            address.getAddressLine(0)
                + ""
                + address.getCountryCode()
                + " "
                + address.getCountryName());
        countryId = address.getCountryCode();
        country = address.getCountryName();
        adlevel1 = address.getAdminArea();
        adlevel2 = address.getSubAdminArea();
        // streetadd = address.getAddressLine(0)
        // + address.getAddressLine(1);
        locality = address.getLocality();
        postalcode = address.getPostalCode();

        Log.e("check country code", "" + address.getCountryCode());
        Log.e("Locale", "" + address.getLocale());
        Log.e("Maxaddlineindex", "" + address.getMaxAddressLineIndex());
        Log.e("subadminarea", "" + address.getSubAdminArea());
        Log.e("addres line", "" + address.getAddressLine(0));
        Log.e("addres line 1", "" + address.getAddressLine(1));
        Log.e("adminarea", "" + address.getAdminArea());
        Log.e("featurename", "" + address.getFeatureName());
        Log.e("adminarea", "" + address.getAdminArea());
        Log.e("Locality", "" + address.getLocality());
        Log.e("premises", "" + address.getPremises());
        Log.e("postalcode", "" + address.getPostalCode());
        Log.e("sublocality", "" + address.getSubLocality());
        Log.e("extras", "" + address.getExtras());

        Log.e("back country", "" + country);

        Log.e("streetAddress", "" + streetadd);
        return addressMessage;
      } else {
        return "No address found";
      }
    }
 private String getCity() {
   return currentAddress.getSubAdminArea() != null
       ? currentAddress.getSubAdminArea()
       : currentAddress.getLocality();
 }