List of usage examples for android.location Address getLocality
public String getLocality()
From source file:cmu.troy.applogger.AppService.java
private void logApps(List<String> newApps, List<String> currentApps) throws IOException { /*//from w w w . ja va2 s .c o m * Empty newApps means current apps are the same with the last apps. So there is no need to * update last apps file or log file. */ if (newApps == null || newApps.size() == 0) return; lastApps = currentApps; Date now = new Date(); /* Append new Apps into log file */ JSONObject job = new JSONObject(); String id = String.valueOf(now.getTime()); try { job.put(JSONKeys.id, id); job.put(JSONKeys.first, newApps.get(0)); job.put(JSONKeys.log_type, JSONValues.OPEN_AN_APP); /* Log Location block */ Location mLocation = null; if (mLocationClient.isConnected()) mLocation = mLocationClient.getLastLocation(); if (mLocation != null) { job.put(JSONKeys.loc_available, true); job.put(JSONKeys.latitude, mLocation.getLatitude()); job.put(JSONKeys.longitude, mLocation.getLongitude()); job.put(JSONKeys.location_accuracy, mLocation.getAccuracy()); job.put(JSONKeys.location_updated_time, (new Date(mLocation.getTime())).toString()); Date updateTime = new Date(mLocation.getTime()); if ((updateTime.getTime() - now.getTime()) / 60000 > 5) { Tools.runningLog("Last location is too old, a location update is triggered."); LocationRequest request = new LocationRequest(); request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationClient.requestLocationUpdates(request, new LocationListener() { @Override public void onLocationChanged(Location arg0) { } }); } if (lastLocation == null || lastAddress == null || lastLocation.distanceTo(mLocation) > Tools.SMALL_DISTANCE) { /* Log Address if location is available */ Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List<Address> addresses = null; addresses = geocoder.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(), 1); if (addresses != null && addresses.size() > 0) { job.put(JSONKeys.addr_available, true); Address address = addresses.get(0); lastAddress = address; job.put(JSONKeys.address, address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : ""); job.put(JSONKeys.city, address.getLocality()); job.put(JSONKeys.country, address.getCountryName()); } else { job.put(JSONKeys.addr_available, false); } } else { job.put(JSONKeys.addr_available, true); job.put(JSONKeys.address, lastAddress.getMaxAddressLineIndex() > 0 ? lastAddress.getAddressLine(0) : ""); job.put(JSONKeys.city, lastAddress.getLocality()); job.put(JSONKeys.country, lastAddress.getCountryName()); } lastLocation = mLocation; } else { if (!mLocationClient.isConnecting()) mLocationClient.connect(); job.put(JSONKeys.loc_available, false); } } catch (JSONException e) { Log.e("JSON", e.toString()); } Tools.logJsonNewBlock(job); }
From source file:com.quantcast.measurement.service.QCLocation.java
private void sendLocation(Location location) { final Double lat = location.getLatitude(); final Double longTemp = location.getLongitude(); _geoTask = new AsyncTask<Double, Void, MeasurementLocation>() { @Override/* w ww .j a v a 2 s .c om*/ protected MeasurementLocation doInBackground(Double... params) { MeasurementLocation retval; double latitude = params[0]; double longitude = params[1]; QCLog.i(TAG, "Looking for address."); try { QCLog.i(TAG, "Geocoder."); List<Address> addresses = _geocoder.getFromLocation(latitude, longitude, 1); if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); retval = new MeasurementLocation(address.getCountryCode(), address.getAdminArea(), address.getLocality(), address.getPostalCode()); } else { QCLog.i(TAG, "Geocoder reverse lookup failed."); retval = this.fallbackGeoLocate(latitude, longitude); } } catch (Exception e) { QCLog.i(TAG, "Geocoder API not available."); retval = this.fallbackGeoLocate(latitude, longitude); } return retval; } protected MeasurementLocation fallbackGeoLocate(double latitude, double longitude) { MeasurementLocation retval = null; // call googles map api directly MeasurementLocation geoInfo = lookup(latitude, longitude); if (geoInfo != null && !this.isCancelled()) { retval = geoInfo; } else { QCLog.i(TAG, "Google Maps API reverse lookup failed."); } return retval; } @Override protected void onPostExecute(MeasurementLocation address) { if (null != address && address.getCountry() != null) { QCLog.i(TAG, "Got address and sending..." + address.getCountry() + " " + address.getState() + " " + address.getLocality()); HashMap<String, String> params = new HashMap<String, String>(); params.put(QCEvent.QC_EVENT_KEY, QC_EVENT_LOCATION); if (address.getCountry() != null) { params.put(QC_COUNTRY_KEY, address.getCountry()); } if (address.getState() != null) { params.put(QC_STATE_KEY, address.getState()); } if (address.getLocality() != null) { params.put(QC_CITY_KEY, address.getLocality()); } if (address.getPostalCode() != null) { params.put(QC_POSTALCODE_KEY, address.getPostalCode()); } QCMeasurement.INSTANCE.logOptionalEvent(params, null, null); } } }; //Async execute needs to be on main thread if (Looper.getMainLooper().getThread() == Thread.currentThread()) { if (_geoTask != null && _geoTask.getStatus() == AsyncTask.Status.PENDING) { _geoTask.execute(lat, longTemp); } } else { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (_geoTask != null && _geoTask.getStatus() == AsyncTask.Status.PENDING) { _geoTask.execute(lat, longTemp); } } }); } }
From source file:org.jraf.android.piclabel.app.form.FormActivity.java
private String reverseGeocode(float lat, float lon) { Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List<Address> addresses; try {/*from www .j av a 2 s. c o m*/ addresses = geocoder.getFromLocation(lat, lon, 1); } catch (Throwable t) { Log.w(TAG, "reverseGeocode Could not reverse geocode", t); return null; } if (addresses == null || addresses.isEmpty()) return null; Address address = addresses.get(0); ArrayList<String> strings = new ArrayList<String>(5); if (address.getMaxAddressLineIndex() > 0) strings.add(address.getAddressLine(0)); if (!TextUtils.isEmpty(address.getLocality())) strings.add(address.getLocality()); if (!TextUtils.isEmpty(address.getCountryName())) strings.add(address.getCountryName()); return TextUtils.join(", ", strings); }
From source file:com.yayandroid.utility.MapHelperFragment.java
/** * Parses found address object from GeoCoder, and posts informations *///from ww w .j a va2 s . c o m private void parseAddressInformation(Address address) { /** * This parsing also may need to be modified up to your country's * addressing system */ String value = address.getSubLocality(); if (value != null) PostInformation(LocInfoType.COUNTY, value); value = address.getLocality(); if (value != null) PostInformation(LocInfoType.LOCALITY, value); value = address.getAdminArea(); if (value != null) PostInformation(LocInfoType.CITY, value); value = address.getCountryName(); if (value != null) PostInformation(LocInfoType.COUNTRY, value); // If there is still some fields to get information about, then post // googleMap api to get them boolean isThereAnyLeft = false; for (int i = 0; i < requiredInformations.length; i++) { if (!requiredInformations[i].hasSent) { isThereAnyLeft = true; } } if (isThereAnyLeft) fetchInformationUsingGoogleMap(); }
From source file:tw.com.geminihsu.app01.fragment.Fragment_Client_Service_test.java
private void getCurrentAddress(double longitude, double latitude) { Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault()); try {//from w w w . ja v a2 s. c o m List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1); if (addressList != null && addressList.size() > 0) { Address address = addressList.get(0); StringBuilder sb = new StringBuilder(); for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { sb.append(address.getAddressLine(i)).append("\n"); } sb.append(address.getLocality()).append("\n"); sb.append(address.getPostalCode()).append("\n"); sb.append(address.getCountryName()); result.setLatitude(latitude); result.setLongitude(longitude); result.setCountryName(address.getCountryName()); result.setLocality(address.getLocality()); result.setZipCode(address.getPostalCode()); result.setLocation(sb.toString()); if (address.getCountryCode().equals("TW")) { result.setAddress(address.getAddressLine(0).substring(3, address.getAddressLine(0).length())); result.setLocation(address.getAddressLine(0).substring(3, address.getAddressLine(0).length())); } else { result.setAddress(sb.toString()); result.setLocation(sb.toString()); } curAddress = result.getAddress(); } } catch (IOException e) { Log.e("", "Unable connect to Geocoder", e); } //test = true; }
From source file:tw.com.geminihsu.app01.fragment.Fragment_Client_Service.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getCurrentGPSLocationBroadcastReceiver = new BroadcastReceiver() { @Override// ww w . ja v a 2 s . com public void onReceive(Context context, Intent intent) { // if(!test) { // textView.append("\n" +intent.getExtras().get("coordinates")); if (intent.getExtras().containsKey("longitude")) { double longitude = (double) intent.getExtras().get("longitude"); double latitude = (double) intent.getExtras().get("latitude"); googleMap.clear(); setMapView(longitude, latitude); Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault()); try { List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1); if (addressList != null && addressList.size() > 0) { Address address = addressList.get(0); StringBuilder sb = new StringBuilder(); for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { sb.append(address.getAddressLine(i)).append("\n"); } sb.append(address.getLocality()).append("\n"); sb.append(address.getPostalCode()).append("\n"); sb.append(address.getCountryName()); result.setLatitude(latitude); result.setLongitude(longitude); result.setCountryName(address.getCountryName()); result.setLocality(address.getLocality()); result.setZipCode(address.getPostalCode()); result.setLocation(sb.toString()); if (address.getCountryCode().equals("TW")) { result.setAddress( address.getAddressLine(0).substring(3, address.getAddressLine(0).length())); result.setLocation( address.getAddressLine(0).substring(3, address.getAddressLine(0).length())); } else { result.setAddress(sb.toString()); result.setLocation(sb.toString()); } } } catch (IOException e) { Log.e("", "Unable connect to Geocoder", e); } //test = true; } // } } }; sendDataRequest = new JsonPutsUtil(getActivity()); sendDataRequest.setServerRequestOrderManagerCallBackFunction( new JsonPutsUtil.ServerRequestOrderManagerCallBackFunction() { @Override public void createNormalOrder(NormalOrder order) { if (progressDialog_loading != null) { progressDialog_loading.cancel(); progressDialog_loading = null; } Intent intent = new Intent(getActivity(), ClientTakeRideSearchActivity.class); Bundle b = new Bundle(); b.putInt(Constants.ARG_POSITION, Integer.valueOf(order.getTicket_id())); intent.putExtras(b); startActivity(intent); //finish(); } @Override public void cancelNormalOrder(NormalOrder order) { Intent intent = new Intent(getActivity(), MainActivity.class); startActivity(intent); //finish(); } }); }
From source file:dynamite.zafroshops.app.MainActivity.java
public LocationBase getAddress(boolean force) { Geocoder geocoder = new Geocoder(this, Locale.ENGLISH); SharedPreferences preferences = getPreferences(0); SharedPreferences.Editor editor = preferences.edit(); boolean locationToggle = preferences.getBoolean(StorageKeys.LOCATION_TOGGLE_KEY, locationToggleDefault); try {//from w w w . ja v a2 s . c o m if (!force && LastLocation != null) { if (preferences.contains(StorageKeys.COUNTRY_KEY) && !preferences.getString(StorageKeys.COUNTRY_KEY, "").equals("")) { LastLocation.CountryCode = preferences.getString(StorageKeys.COUNTRY_KEY, ""); LastLocation.Town = preferences.getString(StorageKeys.TOWN_KEY, ""); LastLocation.Street = preferences.getString(StorageKeys.STREET_KEY, ""); LastLocation.StreetNumber = preferences.getString(StorageKeys.STREETNUMBER_KEY, ""); } } else if (locationToggle && LastLocation != null) { List<Address> addresses = geocoder.getFromLocation(LastLocation.Latitude, LastLocation.Longitude, 1); if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); LastLocation.CountryCode = address.getCountryCode(); LastLocation.Town = address.getLocality(); if (address.getMaxAddressLineIndex() > 0) { String line = address.getAddressLine(0); if (line.compareTo(LastLocation.Town) < 0) { LastLocation.Street = line.replaceAll("(\\D+) \\d+.*", "$1"); LastLocation.StreetNumber = line.replaceAll("\\D+ (\\d+.*)", "$1"); } } editor.putString(StorageKeys.COUNTRY_KEY, LastLocation.CountryCode); editor.putString(StorageKeys.TOWN_KEY, LastLocation.Town); editor.putString(StorageKeys.STREET_KEY, LastLocation.Street); editor.putString(StorageKeys.STREETNUMBER_KEY, LastLocation.StreetNumber); editor.commit(); } } else { return null; } return LastLocation; } catch (IOException e) { return null; } }
From source file:com.cecs492a_group4.sp.SingleEvent.java
public String reverseGeocode(double latitude, double longitude) throws IOException { Geocoder gc = new Geocoder(this); if (gc.isPresent()) { List<Address> list = gc.getFromLocation(latitude, longitude, 1); //(latitude, longitude, 1) //33.777043, -118.114395, 1) Address address = list.get(0); StringBuffer str = new StringBuffer(); if (address.getAddressLine(0) != null && address.getLocality() != null && address.getAdminArea() != null && address.getPostalCode() != null && address.getCountryName() != null) { //str.append(address.getAddressLine(0) + ", "); //str.append(address.getLocality() + ", "); //str.append(address.getAdminArea() + " "); //str.append(address.getPostalCode() + ", "); //str.append(address.getCountryName()); //str.append("USA"); //String strAddress = str.toString(); String strAddress = (address.getAddressLine(0) + ", " + address.getLocality() + ", " + address.getAdminArea() + " " + address.getPostalCode() + ", " + "USA"); return strAddress; } else {//ww w . j av a 2 s . c om return null; } } return null; }
From source file:es.rczone.tutoriales.gmaps.MainActivity.java
protected void onActivityResult(int requestCode, int resultCode, Intent data) { /**//from w ww. ja v a2s .co m * Result for Address activity */ if (requestCode == 1) { if (resultCode == RESULT_OK) { Address current_location = data.getExtras().getParcelable("result"); LatLng addressLocation = new LatLng(current_location.getLatitude(), current_location.getLongitude()); CameraPosition camPos = new CameraPosition.Builder().target(addressLocation) //Center camera in 'Plaza Maestro Villa' .zoom(16) //Set 16 level zoom .build(); CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos); map.animateCamera(camUpd3); String description = current_location.getThoroughfare() + " " + current_location.getSubThoroughfare() + ", " + current_location.getLocality() + ", " + current_location.getCountryName(); Marker m = map.addMarker(new MarkerOptions().position(addressLocation)); markersList.add(m); Toast.makeText(this, description, Toast.LENGTH_LONG).show(); } if (resultCode == RESULT_CANCELED) { // Write your code if there's no result } } }
From source file:com.astifter.circatext.YahooJSONParser.java
public Weather getWeather(String data, Address address) throws JSONException { Weather weather = new Weather(); // We create out JSONObject from the data JSONObject jObj = new JSONObject(data); JSONObject queryObj = getObject("query", jObj); try {/*from w w w .java 2 s. c om*/ @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); weather.time = sdf.parse(getString("created", queryObj)); } catch (Throwable t) { weather.time = null; } JSONObject resultsObj = getObject("results", queryObj); JSONObject channelObj = getObject("channel", resultsObj); JSONObject itemObj = getObject("item", channelObj); JSONObject condition = getObject("condition", itemObj); weather.currentCondition.setCondition(getString("text", condition)); int code = getInt("code", condition); weather.currentCondition.setWeatherId(code); weather.currentCondition.setDescr(Weather.translateYahoo(code)); float temperatureF = getFloat("temp", condition); float temperatureC = (temperatureF - 32f) / 1.8f; weather.temperature.setTemp(temperatureC); try { // Tue, 04 Aug 2015 10:59 pm CEST Locale l = Locale.ENGLISH; SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy hh:mm a", l); String date = getString("date", condition).replace("pm", "PM").replace("am", "AM"); weather.lastupdate = sdf.parse(date); } catch (Throwable t) { weather.lastupdate = null; } Location loc = new Location(); loc.setCountry(address.getCountryCode()); loc.setCity(address.getLocality()); weather.location = loc; return weather; }