Example usage for android.location Address setAddressLine

List of usage examples for android.location Address setAddressLine

Introduction

In this page you can find the example usage for android.location Address setAddressLine.

Prototype

public void setAddressLine(int index, String line) 

Source Link

Document

Sets the line of the address numbered by index (starting at 0) to the given String, which may be null.

Usage

From source file:dev.application.taxivip.helpers.LocationUtils.java

public static List<Address> getStringFromLocation(double lat, double lng)
        throws ClientProtocolException, IOException, JSONException {

    String address = String.format(Locale.getDefault(),
            "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&components=country:CO&region=co&language="
                    + Locale.getDefault().getCountry(),
            lat, lng);/*w w  w.j av a2 s.  c o m*/
    HttpGet httpGet = new HttpGet(address);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    List<Address> retList = null;

    response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
    InputStream stream = entity.getContent();
    int b;
    while ((b = stream.read()) != -1) {
        stringBuilder.append((char) b);
    }

    JSONObject jsonObject = new JSONObject();
    jsonObject = new JSONObject(stringBuilder.toString());

    retList = new ArrayList<Address>();

    if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
        JSONArray results = jsonObject.getJSONArray("results");
        for (int i = 0; i < results.length(); i++) {
            JSONObject result = results.getJSONObject(i);
            String indiStr = result.getString("formatted_address");
            Address addr = new Address(Locale.getDefault());
            addr.setAddressLine(0, indiStr);
            retList.add(addr);
        }
    }

    return retList;
}

From source file:no.ntnu.idi.socialhitchhiking.map.GeoHelper.java

/**
 * Gets a list of addresses from a set of coordinates
 * @param lat//from   w w  w .  j  a v  a 2 s .c o  m
 * @param lon
 * @param maxResults
 * @return
 */
public static List<Address> getAddressesFromLocation(double lat, double lon, int maxResults) {
    JSONArray responseArray = getJSONArrayFromLocation(lat, lon, maxResults);
    List<Address> addresses = new ArrayList<Address>();
    JSONObject jsonObj;
    for (int i = 0; i < responseArray.length(); i++) {
        Address address = new Address(Locale.getDefault());
        String addressLine;
        try {
            jsonObj = responseArray.getJSONObject(i);
            addressLine = jsonObj.getString("formatted_address");
            if (addressLine.contains(",")) {
                String[] lines = addressLine.split(",");
                for (int j = 0; j < lines.length; j++) {
                    address.setAddressLine(j, lines[j].trim());
                }
            }
            addresses.add(address);
        } catch (JSONException e) {
            continue;
        }
    }
    return addresses;
}

From source file:com.example.loc.MainActivity.java

public static List<Address> getFromLocation(double lat, double lng, int maxResult) {

    String address = String.format(Locale.ENGLISH,
            "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language="
                    + Locale.getDefault().getCountry(),
            lat, lng);/*from  w w w  . ja v  a 2s.  c  om*/
    HttpGet httpGet = new HttpGet(address);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    List<Address> retList = null;

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject = new JSONObject(stringBuilder.toString());

        retList = new ArrayList<Address>();

        if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
            JSONArray results = jsonObject.getJSONArray("results");
            for (int i = 0; i < results.length(); i++) {
                JSONObject result = results.getJSONObject(i);
                String indiStr = result.getString("formatted_address");
                Address addr = new Address(Locale.ENGLISH);
                addr.setAddressLine(0, indiStr);
                retList.add(addr);
            }
        }

    } catch (ClientProtocolException e) {
        Log.e(LocationUtils.APPTAG, "Error calling Google geocode webservice.", e);
    } catch (IOException e) {
        Log.e(LocationUtils.APPTAG, "Error calling Google geocode webservice.", e);
    } catch (JSONException e) {
        Log.e(LocationUtils.APPTAG, "Error parsing Google geocode webservice response.", e);
    }

    return retList;
}

From source file:it.smartcampuslab.riciclo.geo.OSMAddress.java

/**
 * Convert the object to {@link Address} data structure
 * @return converted {@link Address} instance with
 * address line corresponding to the formatted address of the object
 * with lat/lon, country name, and locality filled. 
 */// w  w  w  . j a  v a  2 s.c o  m
public Address toAddress() {
    Address a = new Address(locale);
    a.setAddressLine(0, formattedAddress());
    a.setCountryName(country());
    a.setLatitude(location[0]);
    a.setLongitude(location[1]);
    a.setLocality(city());
    return a;
}

From source file:org.microg.networklocation.backends.mapquest.NominatimGeocodeSource.java

private Address parseResponse(Locale locale, JSONObject result) throws JSONException {
    if (!result.has(WIRE_LATITUDE) || !result.has(WIRE_LONGITUDE) || !result.has(WIRE_ADDRESS)) {
        return null;
    }/*from   w  ww.j av  a  2  s.c  o m*/
    Address address = new Address(locale);
    address.setLatitude(result.getDouble(WIRE_LATITUDE));
    address.setLatitude(result.getDouble(WIRE_LONGITUDE));

    int line = 0;
    JSONObject a = result.getJSONObject(WIRE_ADDRESS);

    if (a.has(WIRE_THOROUGHFARE)) {
        address.setAddressLine(line++, a.getString(WIRE_THOROUGHFARE));
        address.setThoroughfare(a.getString(WIRE_THOROUGHFARE));
    }
    if (a.has(WIRE_SUBLOCALITY)) {
        address.setSubLocality(a.getString(WIRE_SUBLOCALITY));
    }
    if (a.has(WIRE_POSTALCODE)) {
        address.setAddressLine(line++, a.getString(WIRE_POSTALCODE));
        address.setPostalCode(a.getString(WIRE_POSTALCODE));
    }
    if (a.has(WIRE_LOCALITY_CITY)) {
        address.setAddressLine(line++, a.getString(WIRE_LOCALITY_CITY));
        address.setLocality(a.getString(WIRE_LOCALITY_CITY));
    } else if (a.has(WIRE_LOCALITY_TOWN)) {
        address.setAddressLine(line++, a.getString(WIRE_LOCALITY_TOWN));
        address.setLocality(a.getString(WIRE_LOCALITY_TOWN));
    } else if (a.has(WIRE_LOCALITY_VILLAGE)) {
        address.setAddressLine(line++, a.getString(WIRE_LOCALITY_VILLAGE));
        address.setLocality(a.getString(WIRE_LOCALITY_VILLAGE));
    }
    if (a.has(WIRE_SUBADMINAREA)) {
        address.setAddressLine(line++, a.getString(WIRE_SUBADMINAREA));
        address.setSubAdminArea(a.getString(WIRE_SUBADMINAREA));
    }
    if (a.has(WIRE_ADMINAREA)) {
        address.setAddressLine(line++, a.getString(WIRE_ADMINAREA));
        address.setAdminArea(a.getString(WIRE_ADMINAREA));
    }
    if (a.has(WIRE_COUNTRYNAME)) {
        address.setAddressLine(line++, a.getString(WIRE_COUNTRYNAME));
        address.setCountryName(a.getString(WIRE_COUNTRYNAME));
    }
    if (a.has(WIRE_COUNTRYCODE)) {
        address.setCountryCode(a.getString(WIRE_COUNTRYCODE));
    }

    return address;
}

From source file:edu.usf.cutr.opentripplanner.android.tasks.OTPGeocoding.java

protected Long doInBackground(String... reqs) {
    long count = reqs.length;

    String address = reqs[0];//from  w  w w.j  av  a  2  s .  co m
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    if (address == null || address.equalsIgnoreCase("")) {
        return count;
    }

    if (address.equalsIgnoreCase(context.getString(R.string.my_location))) {
        String currentLat = reqs[1];
        String currentLng = reqs[2];
        LatLng latLng = new LatLng(Double.parseDouble(currentLat), Double.parseDouble(currentLng));

        Address addressReturn = new Address(context.getResources().getConfiguration().locale);
        addressReturn.setLatitude(latLng.latitude);
        addressReturn.setLongitude(latLng.longitude);
        addressReturn.setAddressLine(addressReturn.getMaxAddressLineIndex() + 1,
                context.getString(R.string.my_location));

        addressesReturn.add(addressReturn);

        return count;
    }

    ArrayList<Address> addresses = null;

    if (prefs.getBoolean(OTPApp.PREFERENCE_KEY_USE_ANDROID_GEOCODER, true)) {
        Log.d("test", "create a geocoder");
        Geocoder gc = new Geocoder(context);
        try {
            if (selectedServer != null) {
                addresses = (ArrayList<Address>) gc.getFromLocationName(address,
                        context.getResources().getInteger(R.integer.geocoder_max_results),
                        selectedServer.getLowerLeftLatitude(), selectedServer.getLowerLeftLongitude(),
                        selectedServer.getUpperRightLatitude(), selectedServer.getUpperRightLongitude());
            } else {
                addresses = (ArrayList<Address>) gc.getFromLocationName(address,
                        context.getResources().getInteger(R.integer.geocoder_max_results));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    addresses = filterAddressesBBox(addresses);

    if ((addresses == null) || addresses.isEmpty()) {
        addresses = searchPlaces(address);

        for (int i = 0; i < addresses.size(); i++) {
            Address addr = addresses.get(i);
            String str = addr.getAddressLine(0);
            List<String> addrLines = Arrays.asList(str.split(", "));
            for (int j = 0; j < addrLines.size(); j++) {
                addr.setAddressLine(j, addrLines.get(j));
            }
        }
    }

    addresses = filterAddressesBBox(addresses);

    addressesReturn.addAll(addresses);

    return count;
}

From source file:edu.usf.cutr.opentripplanner.android.tasks.OTPGeocoding.java

private ArrayList<Address> searchPlaces(String name) {
    HashMap<String, String> params = new HashMap<String, String>();
    Places p;//w w w .j  a v a2 s .  c  o m

    /*params.put(Itract.PARAM_NAME, name);
    if (selectedServer != null) {
       params.put(Itract.PARAM_LAT, Double.toString(selectedServer.getGeometricalCenterLatitude()));
       params.put(Itract.PARAM_LON, Double.toString(selectedServer.getGeometricalCenterLongitude()));
    }
    p = new Itract();*/

    if (placesService.equals(context.getResources().getString(R.string.geocoder_google_places))) {
        params.put(GooglePlaces.PARAM_NAME, name);
        if (selectedServer != null) {
            params.put(GooglePlaces.PARAM_LOCATION,
                    Double.toString(selectedServer.getGeometricalCenterLatitude()) + ","
                            + Double.toString(selectedServer.getGeometricalCenterLongitude()));
            params.put(GooglePlaces.PARAM_RADIUS, Double.toString(selectedServer.getRadius()));
        }
        p = new GooglePlaces(getKeyFromResource());

        Log.v(TAG, "Using Google Places!");
    } else {
        params.put(Nominatim.PARAM_NAME, name);
        if (selectedServer != null) {
            params.put(Nominatim.PARAM_LEFT, Double.toString(selectedServer.getLowerLeftLongitude()));
            params.put(Nominatim.PARAM_TOP, Double.toString(selectedServer.getLowerLeftLatitude()));
            params.put(Nominatim.PARAM_RIGHT, Double.toString(selectedServer.getUpperRightLongitude()));
            params.put(Nominatim.PARAM_BOTTOM, Double.toString(selectedServer.getUpperRightLatitude()));
        }

        p = new Nominatim();

        Log.v(TAG, "Using Nominatim!");
    }

    ArrayList<POI> pois = new ArrayList<POI>();
    pois.addAll(p.getPlaces(params));

    ArrayList<Address> addresses = new ArrayList<Address>();

    for (int i = 0; i < pois.size(); i++) {
        POI poi = pois.get(i);
        Log.v(TAG, poi.getName() + " " + poi.getLatitude() + "," + poi.getLongitude());
        Address addr = new Address(context.getResources().getConfiguration().locale);
        addr.setLatitude(poi.getLatitude());
        addr.setLongitude(poi.getLongitude());
        String addressLine;

        if (poi.getAddress() != null) {
            if (!poi.getAddress().contains(poi.getName())) {
                addressLine = (poi.getName() + ", " + poi.getAddress());
            } else {
                addressLine = poi.getAddress();
            }
        } else {
            addressLine = poi.getName();
        }
        addr.setAddressLine(addr.getMaxAddressLineIndex() + 1, addressLine);
        addresses.add(addr);
    }

    return addresses;
}

From source file:eu.trentorise.smartcampus.jp.PlanNewJourneyFragment.java

private void findAddressForField(final String field, Location location) {
    List<Address> hereAddressesList = new SCGeocoder(getSherlockActivity()).findAddressesAsync(location);
    if (hereAddressesList != null && !hereAddressesList.isEmpty()) {
        Address hereAddress = hereAddressesList.get(0);
        savePosition(hereAddress, field);
    } else {/* w ww .ja va2 s .c  o  m*/
        Address customAddress = new Address(Locale.getDefault());
        customAddress.setLatitude(location.getLatitude());
        customAddress.setLongitude(location.getLongitude());
        customAddress.setAddressLine(0, "LON " + Double.toString(customAddress.getLongitude()) + ", LAT "
                + Double.toString(customAddress.getLatitude()));
        savePosition(customAddress, field);
    }
}

From source file:grandroid.geo.Geocoder.java

public static List<Address> getFromLocation(Locale locale, double lat, double lng, int maxResult) {
    String language = locale.getLanguage();
    if (locale == Locale.TAIWAN) {
        language = "zh-TW";
    }//from w w  w .j ava 2 s.  c o m
    String address = String.format(locale,
            "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=false&language="
                    + language,
            lat, lng);//locale.getCountry()
    HttpGet httpGet = new HttpGet(address);
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(AllClientPNames.USER_AGENT,
            "Mozilla/5.0 (Java) Gecko/20081007 java-geocoder");
    //client.getParams().setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 5 * 1000);
    //client.getParams().setIntParameter(AllClientPNames.SO_TIMEOUT, 25 * 1000);
    HttpResponse response;

    List<Address> retList = null;

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String json = EntityUtils.toString(entity, "UTF-8");

        JSONObject jsonObject = new JSONObject(json);

        retList = new ArrayList<Address>();

        if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
            JSONArray results = jsonObject.getJSONArray("results");
            if (results.length() > 0) {
                for (int i = 0; i < results.length() && i < maxResult; i++) {
                    JSONObject result = results.getJSONObject(i);
                    //Log.e(MyGeocoder.class.getName(), result.toString());
                    Address addr = new Address(Locale.getDefault());
                    // addr.setAddressLine(0, result.getString("formatted_address"));

                    JSONArray components = result.getJSONArray("address_components");
                    String streetNumber = "";
                    String route = "";
                    for (int a = 0; a < components.length(); a++) {
                        JSONObject component = components.getJSONObject(a);
                        JSONArray types = component.getJSONArray("types");
                        for (int j = 0; j < types.length(); j++) {
                            String type = types.getString(j);
                            if (type.equals("locality") || type.equals("administrative_area_level_3")) {
                                addr.setLocality(component.getString("long_name"));
                            } else if (type.equals("street_number")) {
                                streetNumber = component.getString("long_name");
                            } else if (type.equals("route")) {
                                route = component.getString("long_name");
                            } else if (type.equals("administrative_area_level_1")) {
                                addr.setAdminArea(component.getString("long_name"));
                            } else if (type.equals("country")) {
                                addr.setCountryName(component.getString("long_name"));
                                addr.setCountryCode(component.getString("short_name"));
                            }
                        }
                    }
                    addr.setAddressLine(0, route + " " + streetNumber);
                    if (result.has("formatted_address")) {
                        addr.setFeatureName(result.getString("formatted_address"));
                    }
                    addr.setLatitude(
                            result.getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
                    addr.setLongitude(
                            result.getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
                    if (addr.getAdminArea() == null) {
                        addr.setAdminArea("");
                    }
                    retList.add(addr);
                }
            }
        }
    } catch (ClientProtocolException e) {
        Log.e("grandroid", "Error calling Google geocode webservice.", e);
    } catch (IOException e) {
        Log.e("grandroid", "Error calling Google geocode webservice.", e);
    } catch (JSONException e) {
        Log.e("grandroid", "Error parsing Google geocode webservice response.", e);
    }
    return retList;
}

From source file:eu.trentorise.smartcampus.jp.PlanNewJourneyFragment.java

protected void createFavoritesDialog(final String field) {
    if (userPrefsHolder != null && userPrefsHolder.getFavorites() != null
            && !userPrefsHolder.getFavorites().isEmpty()) {
        final List<Position> list = userPrefsHolder.getFavorites();
        String[] items = new String[list.size()];
        for (int i = 0; i < items.length; i++) {
            items[i] = list.get(i).getName();
        }//ww w . j  a va 2 s  . co m

        AlertDialog.Builder builder = new AlertDialog.Builder(getSherlockActivity());
        builder.setTitle(getString(R.string.favorites_title));

        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // to be replaced with real favorites list
                Address address = new Address(Locale.getDefault());
                Position p = list.get(which);
                address.setLatitude(Double.parseDouble(p.getLat()));
                address.setLongitude(Double.parseDouble(p.getLon()));
                address.setAddressLine(0, p.getName());
                savePosition(address, field);

                if (FROM.equalsIgnoreCase(field)) {
                    ImageButton ibtn = (ImageButton) getView().findViewById(R.id.plannew_from_star);
                    ibtn.setImageResource(R.drawable.ic_fav_star_active);
                    ibtn.setTag(true);
                } else if (TO.equalsIgnoreCase(field)) {
                    ImageButton ibtn = (ImageButton) getView().findViewById(R.id.plannew_to_star);
                    ibtn.setImageResource(R.drawable.ic_fav_star_active);
                    ibtn.setTag(true);
                }
            }
        });

        builder.create().show();
    } else {
        Toast.makeText(getActivity(), R.string.favorites_empty_list, Toast.LENGTH_SHORT).show();
    }
}