Esempio n. 1
0
  public static String goToGeocoder(Activity mContext, double lat, double lng) throws IOException {
    List<Address> almt;
    String alamat = null;
    // StringBuilder sb = new StringBuilder();
    try {
      Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
      almt = geocoder.getFromLocation(lat, lng, 5);
      if (almt.size() > 0 && almt != null) {

        Address almtSkrng = almt.get(0);
        // String admin_area = sb.append(almtSkrng.getAdminArea()).toString();
        // String postalcode = sb.append(almtSkrng.getPostalCode()).toString();
        if (almtSkrng.getAddressLine(0).equals(null) || almtSkrng.getAddressLine(0).equals("")) {
          alamat = almtSkrng.getFeatureName();
        }
        alamat = almtSkrng.getAddressLine(0) + " " + almtSkrng.getAdminArea();
      } else {
        alamat = "";
      }

    } catch (IOException e) {
      // TODO: handle exception
      // Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
      alamat = "";
      Log.e("yotomo", e.getMessage());
    }

    return alamat;
  }
Esempio n. 2
0
  private void getAddressFromLocation(final LatLng latlng, final MyFontTextView et) {

    /*
     * et.setText("Waiting for Address"); et.setTextColor(Color.GRAY);
     */
    /*
     * new Thread(new Runnable() {
     *
     * @Override public void run() { // TODO Auto-generated method stub
     */

    Geocoder gCoder = new Geocoder(getActivity());
    try {
      final List<Address> list = gCoder.getFromLocation(latlng.latitude, latlng.longitude, 1);
      if (list != null && list.size() > 0) {
        Address address = list.get(0);
        StringBuilder sb = new StringBuilder();
        if (address.getAddressLine(0) != null) {

          sb.append(address.getAddressLine(0)).append(", ");
        }
        sb.append(address.getLocality()).append(", ");
        // sb.append(address.getPostalCode()).append(",");
        sb.append(address.getCountryName());
        strAddress = sb.toString();

        strAddress = strAddress.replace(",null", "");
        strAddress = strAddress.replace("null", "");
        strAddress = strAddress.replace("Unnamed", "");
        if (!TextUtils.isEmpty(strAddress)) {

          et.setText(strAddress);
        }
      }
      /*
       * getActivity().runOnUiThread(new Runnable() {
       *
       * @Override public void run() { // TODO Auto-generated method stub
       * if (!TextUtils.isEmpty(strAddress)) {
       *
       * et.setText(strAddress);
       *
       *
       * } else { et.setText("");
       *
       * }
       *
       * } });
       */

    } catch (IOException exc) {
      exc.printStackTrace();
    }
    // }
    // }).start();

  }
Esempio n. 3
0
  private void geocodeLocation(String placeName) {

    // Following adapted from Conder and Darcey, pp.321 ff.
    Geocoder gcoder = new Geocoder(this);

    // Note that the Geocoder uses synchronous network access, so in a serious application
    // it would be best to put it on a background thread to prevent blocking the main UI if network
    // access is slow. Here we are just giving an example of how to use it so, for simplicity, we
    // don't put it on a separate thread.  See the class RouteMapper in this package for an example
    // of making a network access on a background thread. Geocoding is implemented by a backend
    // that is not part of the core Android framework, so we use the static method
    // Geocoder.isPresent() to test for presence of the required backend on the given platform.

    try {
      List<Address> results = null;
      if (Geocoder.isPresent()) {
        results = gcoder.getFromLocationName(placeName, numberOptions);
      } else {
        Log.i(TAG, "No geocoder found");
        return;
      }
      Iterator<Address> locations = results.iterator();
      String raw = "\nRaw String:\n";
      String country;
      int opCount = 0;
      while (locations.hasNext()) {
        Address location = locations.next();
        if (opCount == 0 && location != null) {
          lat = location.getLatitude();
          lon = location.getLongitude();
        }
        country = location.getCountryName();
        if (country == null) {
          country = "";
        } else {
          country = ", " + country;
        }
        raw += location + "\n";
        optionArray[opCount] =
            location.getAddressLine(0) + ", " + location.getAddressLine(1) + country + "\n";
        opCount++;
      }
      // Log the returned data
      Log.i(TAG, raw);
      Log.i(TAG, "\nOptions:\n");
      for (int i = 0; i < opCount; i++) {
        Log.i(TAG, "(" + (i + 1) + ") " + optionArray[i]);
      }
      Log.i(TAG, "lat=" + lat + " lon=" + lon);

    } catch (IOException e) {
      Log.e(TAG, "I/O Failure; do you have a network connection?", e);
    }
  }
 public static boolean a(Address paramAddress1, Address paramAddress2) {
   int i = 0;
   boolean bool;
   if (paramAddress1.getMaxAddressLineIndex() == paramAddress2.getMaxAddressLineIndex()) {
     bool = true;
   }
   while ((i <= paramAddress1.getMaxAddressLineIndex()) && (bool)) {
     bool = TextUtils.equals(paramAddress1.getAddressLine(i), paramAddress2.getAddressLine(i));
     i += 1;
     continue;
     bool = false;
   }
   return bool;
 }
  public String getAddress() {

    String display_address = "";

    display_address += address.getAddressLine(0) + "\n";

    for (int i = 1; i < address.getMaxAddressLineIndex(); i++) {
      display_address += address.getAddressLine(i) + ", ";
    }

    display_address = display_address.substring(0, display_address.length() - 1);

    return display_address;
  }
    private String getFullAddress(List<Address> addresses) {
      StringBuilder fullAddress = new StringBuilder();

      if (addresses != null && !addresses.isEmpty()) {
        Address address = addresses.get(0);

        for (int i = 0; i < address.getMaxAddressLineIndex(); ++i) {
          fullAddress.append(address.getAddressLine(i));
          fullAddress.append(", ");
        }
        fullAddress.append(address.getAddressLine(address.getMaxAddressLineIndex()));
      }

      return fullAddress.toString();
    }
 public static String toAddress(Address a) {
   StringBuilder sb = new StringBuilder();
   // if (Strings.isNotEmpty(a.getPostalCode())) {
   // sb.append(a.getPostalCode()).append(' ');
   // }
   // if (Strings.isNotEmpty(a.getCountryName())) {
   // sb.append(a.getCountryName()).append(' ');
   // }
   // if (Strings.isNotEmpty(a.getAdminArea())) {
   // sb.append(a.getAdminArea()).append(' ');
   // }
   // if (Strings.isNotEmpty(a.getSubAdminArea())) {
   // sb.append(a.getSubAdminArea()).append(' ');
   // }
   // if (Strings.isNotEmpty(a.getLocality())) {
   // sb.append(a.getLocality()).append(' ');
   // }
   // if (Strings.isNotEmpty(a.getSubLocality())) {
   // sb.append(a.getSubLocality()).append(' ');
   // }
   // if (Strings.isNotEmpty(a.getThoroughfare())) {
   // sb.append(a.getThoroughfare()).append(' ');
   // }
   for (int i = 0; i <= a.getMaxAddressLineIndex(); i++) {
     String line = a.getAddressLine(i);
     if (Strings.isEmpty(line)) {
       continue;
     }
     sb.append(line).append(' ');
   }
   return sb.toString().trim();
 }
Esempio n. 8
0
    @Override
    protected String doInBackground(Location... params) {

      Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
      // get current location from input parameter list
      Location location = params[0];
      List<Address> addresses = null;
      try {
        /*
         * Call getFromLocation() method with lat, lng of current
         * location and return at most 1 result
         */
        addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

      } catch (IOException e) {
        e.printStackTrace();
        return null;
      }
      if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        String addressString =
            address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "";
        addressString =
            addressString.concat(", " + address.getLocality() + ", " + address.getCountryName());
        addressStr = address.getLocality() + ", " + address.getCountryName();
        return addressString;
      } else {
        return null;
      }
    }
  private String getGeocodedBikeAddress(Bike bike) {
    Log.d("LocationSample", "getGeocodedBikeAddress(" + bike.getName() + ")");

    // perform a reverse geocode to get the address
    if (Geocoder.isPresent()) {
      Geocoder geocoder = new Geocoder(context, Locale.getDefault());

      try {
        // reverse geocode from current GPS position
        List<Address> results =
            geocoder.getFromLocation(bike.getLatitude(), bike.getLongitude(), 1);

        if (results.size() > 0) {
          Address match = results.get(0);
          String address = match.getAddressLine(0);
          bike.setAddress(address);
          return address;
        } else {
          Log.d(
              "LocationSample",
              "No results found while reverse geocoding GPS location for bike station: "
                  + bike.getName());
          return "";
        }
      } catch (IOException e) {
        e.printStackTrace();
        return "";
      }
    } else {
      Log.d("LocationSample", "No geocoder present");
      return "";
    }
  }
  @Override
  public void onStart() {
    super.onStart();
    TextView msg = (TextView) getDialog().findViewById(R.id.mapdialog_msg);
    if (address != null) msg.setText(address.getAddressLine(0));
    msg.setMovementMethod(new ScrollingMovementMethod());
    Button b = (Button) getDialog().findViewById(R.id.mapdialog_cancel);
    b.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            getDialog().dismiss();
          }
        });
    b = (Button) getDialog().findViewById(R.id.mapdialog_ok);
    b.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            Intent data = new Intent();
            data.putExtra("address", address);
            data.putExtra("field", activity.getIntent().getExtras().getString("field"));
            activity.setResult(RESULT_SELECTED, data);
            activity.finish();
            getDialog().dismiss();
          }
        });
  }
Esempio n. 11
0
    @Override
    protected String doInBackground(Long... params) {
      try {
        synchronized (coder) { // only one lookup at a time
          long id = params[0];
          Cursor locs = db.fetchLocations(id);
          if (locs.getCount() < 1) return null; // No lat longs avail

          double latitude = locs.getDouble(locs.getColumnIndex(LocationLogDbAdapter.KEY_LATITUDE));
          double longitude =
              locs.getDouble(locs.getColumnIndex(LocationLogDbAdapter.KEY_LONGITUDE));
          List<Address> addrs = coder.getFromLocation(latitude, longitude, 1);

          if (addrs.size() < 1) return null; // Failed to find on google

          Address addr = addrs.get(0);
          StringBuilder builder = new StringBuilder();
          int maxLine = Math.min(addr.getMaxAddressLineIndex(), 1);
          for (int line = 0; line <= maxLine; line++)
            builder.append(addr.getAddressLine(line) + " ");

          String result = builder.toString();

          // Store this as the new description for the flight
          db.updateFlight(id, null, result, null, null);

          return result;
        }
      } catch (Exception ex) {
        // FIXME - log failures
        return null;
      }
    }
Esempio n. 12
0
  public void getLocation(Location location) {
    // OBTENER LA DIRECCION DE LA CALLE A PARTIR DE LA LATITUD Y LA LONGITUD
    if (location.getLatitude() != 0.0 && location.getLongitude() != 0.0) {
      Geocoder geocoder = new Geocoder(this, Locale.getDefault());

      try {
        List<Address> list =
            geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        if (!list.isEmpty()) {
          Address direccion = list.get(0);
          tvDireccion.setText("Mi dirección es: \n" + String.valueOf(direccion.getAddressLine(0)));
          // String ubicacion="Mi ubicación actual es: "+"\n Latitud= "+location.getLatitude()+"\n
          // Longitud= "+location.getLongitude();
          String ubicacion =
              "Mi ubicación actual es: "
                  + "\n Latitud: "
                  + String.valueOf(location.getLatitude())
                  + "\n Longitud: "
                  + String.valueOf(location.getLongitude());
          tvUbicacion.setText(ubicacion);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
 private String getAddress(Activity a, Location loc2) {
   // TODO Auto-generated method stub
   Geocoder geocoder = new Geocoder(a, Locale.getDefault());
   StringBuilder result = new StringBuilder();
   List<Address> addresses;
   try {
     addresses = geocoder.getFromLocation(loc2.getLatitude(), loc2.getLongitude(), 1);
     if (addresses.size() > 0) {
       Address pata = addresses.get(0);
       result.append(pata.getAddressLine(pata.getMaxAddressLineIndex() - 2));
       // result.append(pata.getSubLocality());
       // result.append(",");
       // result.append(pata.getLocality());
       // if(pata.getPostalCode()!=null){
       // result.append(",");
       // result.append(pata.getPostalCode());
       // }
       Toast.makeText(c, "sent", Toast.LENGTH_LONG).show();
       return result.toString();
     }
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     Toast.makeText(c, "error", Toast.LENGTH_LONG).show();
     return "error";
   }
   return "error";
 }
Esempio n. 14
0
    @Override
    protected void onPostExecute(List<Address> addresses) {

      if (addresses == null || addresses.size() == 0) {
        Toast.makeText(getActivity(), "No Location found", Toast.LENGTH_SHORT).show();
      }

      // Clears all the existing markers on the map
      googleMap.clear();

      // Adding Markers on Google Map for each matching address
      for (int i = 0; i < addresses.size(); i++) {

        Address address = (Address) addresses.get(i);

        // Creating an instance of GeoPoint, to display in Google Map
        latLng = new LatLng(address.getLatitude(), address.getLongitude());

        String addressText =
            String.format(
                "%s, %s",
                address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                address.getCountryName());

        markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title(addressText);

        googleMap.addMarker(markerOptions);

        // Locate the first location
        if (i == 0) googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
      }
    }
Esempio n. 15
0
 /**
  * Gets the reverse geo coding string for a location.
  *
  * @param context the context
  * @param location the location
  */
 private static String getReverseGeoCoding(Context context, Location location) {
   if (location == null || !ApiAdapterFactory.getApiAdapter().isGeoCoderPresent()) {
     return null;
   }
   Geocoder geocoder = new Geocoder(context);
   try {
     List<Address> addresses =
         geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
     if (addresses.size() > 0) {
       Address address = addresses.get(0);
       int lines = address.getMaxAddressLineIndex();
       if (lines > 0) {
         return address.getAddressLine(0);
       }
       String featureName = address.getFeatureName();
       if (featureName != null) {
         return featureName;
       }
       String thoroughfare = address.getThoroughfare();
       if (thoroughfare != null) {
         return thoroughfare;
       }
       String locality = address.getLocality();
       if (locality != null) {
         return locality;
       }
     }
   } catch (IOException e) {
     // Can safely ignore
   }
   return null;
 }
Esempio n. 16
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();
    }
  }
  private AlertDialog makeLocationChoiceDialogBox() {
    final String[] addressStrings = new String[addresses.size()];
    Address address = null;
    openSoftKeyboard();

    for (int index = 0; index < addresses.size(); ++index) {
      address = addresses.get(index);
      addressStrings[index] =
          (address.getAddressLine(0)
              + "\n"
              + address.getLocality()
              + "\n"
              + address.getCountryName());
    }

    AlertDialog LocationChoice =
        new AlertDialog.Builder(this)
            .setTitle("Select Location")
            .setItems(
                addressStrings,
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichChoice) {
                    setLocation(addressStrings[whichChoice].toString());
                    Address chosenAddress = addresses.get(whichChoice);
                    setLocationLatitude(chosenAddress.getLatitude());
                    setLocationLongitude(chosenAddress.getLongitude());
                    setProximity(1);
                    dialog.dismiss();
                  }
                })
            .create();
    return LocationChoice;
  }
Esempio n. 18
0
    @Override
    protected Void doInBackground(Location... params) {
      Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());

      Location loc = params[0];
      List<Address> addresses = null;
      try {
        addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
      } catch (IOException e) {
        e.printStackTrace();
        // Update address field with the exception.
        Message.obtain(handler, UPDATE_ADDRESS, e.toString()).sendToTarget();
      }
      if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        // Format the first line of address (if available), city, and country name
        String addressText =
            String.format(
                "%s, %s, %s",
                address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                address.getLocality(),
                address.getCountryName());
        // Update address field on UI
        Message.obtain(handler, UPDATE_ADDRESS, addressText).sendToTarget();
      }
      return null;
    }
    @Override
    protected String doInBackground(Location... params) {
      try {
        Location location = params[0];
        Geocoder geocoder = new Geocoder(context);
        List<Address> enderecos =
            geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

        if (null != enderecos && !enderecos.isEmpty()) {
          Address endereco = enderecos.get(0);
          return endereco.getAddressLine(0) + ", " + endereco.getAddressLine(1);
        }
      } catch (IOException e) {
        Log.e("GeocoderTask", e.getMessage(), e);
      }
      return null;
    }
Esempio n. 20
0
  private String buildAddressString(Address address) {
    StringBuilder sbAddr = new StringBuilder();

    for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
      sbAddr.append(address.getAddressLine(i)).append("\n");
    }

    return sbAddr.toString();
  }
Esempio n. 21
0
 /**
  * Get a Geocoder instance, get the latitude and longitude look up the address, and return it
  *
  * @params params One or more Latlng 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 MarkerPos doInBackground(MarkerPos... params) {
   Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
   // Get the current location from the input parameter list
   MarkerPos markpos = new MarkerPos(params[0]);
   LatLng loc = markpos.getPosition();
   // Create a list to contain the result address
   List<Address> addresses = null;
   try {
     /*
      * Return 1 address.
      */
     addresses = geocoder.getFromLocation(loc.latitude, loc.longitude, 1);
   } catch (IOException e1) {
     Log.e("LocationSampleActivity", "IO Exception in getFromLocation()");
     e1.printStackTrace();
     markpos.setAdresse("Impossible d'avoir l'adresse. Vérifier connexion réseau");
     return markpos;
   } catch (IllegalArgumentException e2) {
     // Error message to post in the log
     String errorString =
         "Illegal arguments "
             + Double.toString(loc.latitude)
             + " , "
             + Double.toString(loc.longitude)
             + " passed to address service";
     Log.e("LocationSampleActivity", errorString);
     e2.printStackTrace();
     markpos.setAdresse(errorString);
     return markpos;
   }
   // 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 addressText =
         String.format(
             "%s, %s, %s",
             // If there's a street address, add it
             address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
             // Locality is usually a city
             address.getLocality(),
             // The country of the address
             address.getCountryName());
     // Return the text
     markpos.setAdresse(addressText);
     return markpos;
   } else {
     markpos.setAdresse("No address found");
     return markpos;
   }
 }
Esempio n. 22
0
  public String getAddressLine(Context context) {
    List<Address> addresses = getGeocoderAddress(context);

    if (addresses != null && addresses.size() > 0) {
      Address address = addresses.get(0);
      String addressLine = address.getAddressLine(0);

      return addressLine;
    } else {
      return null;
    }
  }
Esempio n. 23
0
 @Override
 protected void onHandleIntent(Intent intent) {
   // Si no se ha llamado correctamente al servicio, retornamos.
   if (intent == null || !intent.hasExtra(EXTRA_LOCALIZACION)) {
     entregarRespuesta(false, getString(R.string.localizacion_requerida));
     return;
   }
   // Si el servicio de Geocoding no está disponible, retornamos.
   if (!Geocoder.isPresent()) {
     entregarRespuesta(false, getString(R.string.geocoder_no_disponible));
     return;
   }
   // Se inicializan las variables.
   String mensajeError = "";
   List<Address> direcciones = null;
   Location location = intent.getParcelableExtra(EXTRA_LOCALIZACION);
   // Se obtiene el Geocoder (para el idioma del dispositivo).
   Geocoder geocoder = new Geocoder(this, Locale.getDefault());
   // Se obtiene la lista de direcciones correspondientes a la
   // localización, a través del geocoder (máximo 1 dirección)
   try {
     direcciones =
         geocoder.getFromLocation(
             location.getLatitude(), location.getLongitude(), MAX_DIRECCIONES);
   } catch (IOException e) {
     // Si se produce un error es que el servicio de Geocoder no
     // está disponible.
     mensajeError = getString(R.string.geocoder_no_disponible);
   } catch (IllegalArgumentException illegalArgumentException) {
     // Si la longitud y latitud indicadas no son válidas.
     mensajeError = getString(R.string.lat_long_invalidas);
   }
   // Si no se ha encontrado ninguna dirección.
   if (direcciones == null || direcciones.size() == 0) {
     // Si no se ha producido un error anterior.
     if (mensajeError.isEmpty()) {
       mensajeError = getString(R.string.direccion_no_encontrada);
     }
     // Se entrega el resultado de error al cliente del servicio.
     entregarRespuesta(false, mensajeError);
   } else {
     // Si se ha obtenido una dirección correctamente, se coge cada
     // una de sus líneas.
     Address direccion = direcciones.get(0);
     ArrayList<String> lineas = new ArrayList<>();
     for (int i = 0; i < direccion.getMaxAddressLineIndex(); i++) {
       lineas.add(direccion.getAddressLine(i));
     }
     // Se entrega la dirección resultante al cliente del servicio,
     // en forma de cadena.
     entregarRespuesta(true, TextUtils.join(System.getProperty("line.separator"), lineas));
   }
 }
 private String ObtenerDireccion(double lati, double longi) {
   Geocoder geocoderDireccion = new Geocoder(context);
   List<Address> addresses = null;
   try {
     addresses = geocoderDireccion.getFromLocation(lati, longi, 1);
   } catch (IOException e) {
     e.printStackTrace();
   }
   Address address = addresses.get(0);
   String direccion = address.getAddressLine(0);
   return direccion;
 }
  public String toString() {
    String display_address = "";

    if (address.getFeatureName() != null) {
      display_address += address + ", ";
    }

    for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
      display_address += address.getAddressLine(i);
    }

    return display_address;
  }
Esempio n. 26
0
 public static StringBuilder a(CharSequence paramCharSequence, Address paramAddress) {
   StringBuilder localStringBuilder = new StringBuilder();
   int i = 0;
   int j = paramAddress.getMaxAddressLineIndex();
   while (i <= j) {
     String str = paramAddress.getAddressLine(i);
     if ((!TextUtils.isEmpty(localStringBuilder)) && (!TextUtils.isEmpty(str))) {
       localStringBuilder.append(paramCharSequence);
     }
     localStringBuilder.append(str);
     i += 1;
   }
   return localStringBuilder;
 }
Esempio n. 27
0
    @Override
    protected String doInBackground(Location... params) {
      Geocoder geocoder = new Geocoder(mContext, 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 addressText =
            String.format(
                "%s, %s",
                // If there's a street address, add it
                address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                // Locality is usually a city
                address.getLocality());
        // Return the text
        return addressText;
      } else {
        return "No address found";
      }
    }
  @Override
  protected void onHandleIntent(Intent intent) {
    Location location = intent.getParcelableExtra(AddressLocationActivity.LOCATION);
    int type = intent.getIntExtra(AddressLocationActivity.TYPE, 1);
    String address = intent.getStringExtra(AddressLocationActivity.ADDRESS);

    List<Address> list = new ArrayList<Address>();
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    String error = "";
    String resultAddress = "";

    try {
      if (type == 2 || address == null) {
        list =
            (ArrayList<Address>)
                geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
      } else {
        list = (ArrayList<Address>) geocoder.getFromLocationName(address, 1);
      }
    } catch (IOException e) {
      e.printStackTrace();
      error = "Network problem";
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      error = "Illegal arguments";
    }

    if (list != null && list.size() > 0) {
      Address a = list.get(0);

      if (type == 2 || address == null) {
        for (int i = 0, tam = a.getMaxAddressLineIndex(); i < tam; i++) {
          resultAddress += a.getAddressLine(i);
          resultAddress += i < tam - 1 ? ", " : "";
        }
      } else {
        resultAddress += a.getLatitude() + "\n";
        resultAddress += a.getLongitude();
      }
    } else {
      resultAddress = error;
    }

    MessageEB m = new MessageEB();
    m.setClassName(AddressLocationActivity.class.getName());
    m.setResultMessage(resultAddress);

    EventBus.getDefault().post(m);
  }
Esempio n. 29
0
    @Override
    protected void onPostExecute(List<Address> addresses) {

      if (addresses == null || addresses.size() == 0) {
        Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
        setProgressBarIndeterminateVisibility(false);

        return;
      }

      ViewMapFragment mMapFragment =
          (ViewMapFragment) getSupportFragmentManager().findFragmentByTag("map");

      if (!searchMarkers.isEmpty()) {
        // Clears all the existing markers on the map
        for (Marker m : searchMarkers) {
          m.remove();
        }
        searchMarkers.clear();
      }

      // Adding Markers on Google Map for each matching address
      for (int i = 0; i < addresses.size(); i++) {

        Address address = (Address) addresses.get(i);

        // Creating an instance of GeoPoint, to display in Google Map
        LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());

        String addressText =
            String.format(
                "%s, %s",
                address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                address.getCountryName());

        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title(addressText);
        markerOptions.icon(
            BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

        searchMarkers.add(mMapFragment.mMap.addMarker(markerOptions));

        // Locate the first location
        if (i == 0) mMapFragment.mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
      }
      querying = false;
      setProgressBarIndeterminateVisibility(false);
    }
 public MainActivitySaveObject(
     Location loc, Boolean isNewLocation, Address address, ArrayList<YakMessage> messages) {
   this.loc_lat = Double.valueOf(loc.getLatitude());
   this.loc_lon = Double.valueOf(loc.getLongitude());
   this.provider = loc.getProvider();
   this.isNewLocation = isNewLocation;
   if (address == null) {
     this.address = "";
     this.locale = new Locale("null");
   } else {
     this.address = address.getAddressLine(0);
     this.locale = address.getLocale();
   }
   this.messages = messages;
 }