@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 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; }
@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)); } }
@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; }
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(); }
/** * 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; } }
public String getCountryName(Context context) { List<Address> addresses = getGeocoderAddress(context); if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); String countryName = address.getCountryName(); return countryName; } else { return null; } }
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 String getCountry(double lat, double lon) { Geocoder geocode = new Geocoder(mContext, Locale.getDefault()); try { List<Address> addresses = geocode.getFromLocation(lat, lon, 1); if (addresses != null) { Address fetchedAddress = addresses.get(0); return fetchedAddress.getCountryName(); } } catch (IOException e) { return ""; } return ""; }
/** * Returns a simple one-line address based on city and country * * @param address * @return */ public String getSimpleLocation(Address address) { StringBuilder builder = new StringBuilder(); String locality = address.getLocality(); String countryName = address.getCountryName(); if (!StringUtils.isEmpty(locality)) { builder.append(locality); } else if (!StringUtils.isEmpty(countryName)) { builder.append(countryName); } return builder.toString(); }
/** * 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(); }
@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); }
@Override protected String doInBackground(Location... locations) { Geocoder geocoder = new Geocoder(_context, Locale.getDefault()); Location location = locations[0]; List<Address> addresses = null; try { addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); } catch (IOException ex1) { Log.e(LocationUtils.APPTAG, getString(R.string.IO_Exception_getFromLocation)); ex1.printStackTrace(); return (getString(R.string.IO_Exception_getFromLocation)); } catch (IllegalArgumentException ex2) { String errorString = getString( R.string.illegal_argument_exception, location.getLatitude(), location.getLongitude()); Log.e(LocationUtils.APPTAG, errorString); ex2.printStackTrace(); return errorString; } if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); String addressText = getString( R.string.address_output_string, // if there is a street address address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", // locality is the city address.getLocality(), address.getCountryName()); return addressText; } else { return getString(R.string.no_address_found); } }
private void updateWithNewLocation(Location location) { TextView myLocationText; myLocationText = (TextView) findViewById(R.id.myLocationText); String latLongString = "No location found"; String addressString = "No address found"; if (location != null) { // Update the position overlay. positionOverlay.setLocation(location); Double geoLat = location.getLatitude() * 1E6; Double geoLng = location.getLongitude() * 1E6; GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue()); mapController.animateTo(point); double lat = location.getLatitude(); double lng = location.getLongitude(); latLongString = "Lat:" + lat + "\nLong:" + lng; double latitude = location.getLatitude(); double longitude = location.getLongitude(); Geocoder gc = new Geocoder(this, Locale.getDefault()); if (!Geocoder.isPresent()) addressString = "No geocoder available"; else { try { List<Address> addresses = gc.getFromLocation(latitude, longitude, 1); StringBuilder sb = new StringBuilder(); if (addresses.size() > 0) { Address address = addresses.get(0); 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()); } addressString = sb.toString(); } catch (IOException e) { Log.d("WHEREAMI", "IO Exception", e); } } } myLocationText.setText("Your Current Position is:\n" + latLongString + "\n\n" + addressString); }
static String a(Address paramAddress) { Locale localLocale = paramAddress.getLocale(); Object localObject2 = paramAddress.getCountryName(); Object localObject1 = localObject2; if (TextUtils.isEmpty((CharSequence) localObject2)) { localObject1 = localLocale.getDisplayCountry(localLocale); } localObject2 = localObject1; if (TextUtils.isEmpty((CharSequence) localObject1)) { localObject2 = localLocale.getISO3Country(); } localObject1 = localObject2; if (TextUtils.isEmpty((CharSequence) localObject2)) { localObject1 = paramAddress.getCountryCode(); } return (String) localObject1; }
private static String formatAddress(final Address address) { final ArrayList<String> addressParts = new ArrayList<String>(); final String countryName = address.getCountryName(); if (countryName != null) { addressParts.add(countryName); } final String locality = address.getLocality(); if (locality != null) { addressParts.add(locality); } else { final String adminArea = address.getAdminArea(); if (adminArea != null) { addressParts.add(adminArea); } } return StringUtils.join(addressParts, ", "); }
/** * Update the note using the details provided. The note to be updated is specified using the * rowId, and it is altered to use the title and body values passed in * * @param rowId id of note to update * @param title value to set note title to * @param body value to set note body to * @return true if the note was successfully updated, false otherwise */ public boolean updateTrack(long rowId, MusicTrack track, Address a) { ContentValues initialValues = new ContentValues(); Date d = new Date(); initialValues.put(KEY_DATETIME, d.getTime()); initialValues.put(KEY_TRACK, track.mTrackName); initialValues.put(KEY_ALBUM, track.mAlbumName); initialValues.put(KEY_ARTIST, track.mArtistName); initialValues.put(KEY_CITY, a.getLocality()); initialValues.put(KEY_STATE, a.getAdminArea()); initialValues.put(KEY_COUNTRY, a.getCountryName()); initialValues.put(KEY_FEATURE, a.getFeatureName()); initialValues.put(KEY_LON, a.getLongitude()); initialValues.put(KEY_LAT, a.getLatitude()); return mDb.update(DATABASE_TABLE, initialValues, KEY_ROWID + "=" + rowId, null) > 0; }
@Override protected boolean onTap(int index) { // nothing so far. mMapController.animateTo(mGeoPoint); // show the addr in the toast box. Address address = mAddr.get(0); Toast.makeText( MapViewMain.this, address.getAddressLine(0) + ", " + address.getLocality() + ", " + address.getCountryName(), Toast.LENGTH_LONG) .show(); return true; }
/** * Create a new note using the title and body provided. If the note is successfully created return * the new rowId for that note, otherwise return a -1 to indicate failure. * * @param title the title of the note * @param body the body of the note * @return rowId or -1 if failed */ public long insertTrack(MusicTrack track, Address a) { Date d = new Date(); ContentValues initialValues = new ContentValues(); initialValues.put(KEY_DATETIME, d.getTime()); initialValues.put(KEY_TRACK, track.mTrackName); initialValues.put(KEY_ALBUM, track.mAlbumName); initialValues.put(KEY_ARTIST, track.mArtistName); if (a != null) { initialValues.put(KEY_CITY, a.getLocality()); initialValues.put(KEY_STATE, a.getAdminArea()); initialValues.put(KEY_COUNTRY, a.getCountryName()); initialValues.put(KEY_FEATURE, a.getFeatureName()); initialValues.put(KEY_LON, a.getLongitude()); initialValues.put(KEY_LAT, a.getLatitude()); } return mDb.insert(DATABASE_TABLE, null, initialValues); }
public String getLocationName() { if (!isConnected()) { return "Network is disabled"; } else { List<Address> addresses = null; Geocoder geocoder = new Geocoder(context.getApplicationContext(), Locale.getDefault()); try { addresses = geocoder.getFromLocation(getLatitude(), getLongitude(), 1); } catch (IOException e) { e.printStackTrace(); } Address address = addresses.get(0); return address.getCountryName() + ", " + address.getLocality() + ", " + address.getAdminArea() + ", " + address.getAddressLine(0); } }
@Override protected String doInBackground(Type... params) { if (((FOGmain) ((Activity) callingAcitivity).getApplicationContext()).isNetworkConnected() == false) { return "no_connection"; } else { Geocoder geocoder = new Geocoder(((Activity) callingAcitivity).getBaseContext(), Locale.getDefault()); addresses = new ArrayList<Address>(); type = params[0]; if (Geocoder.isPresent()) { try { if (type == Type.ADDRESSTOLOCATION) { addresses = geocoder.getFromLocationName(addressText, 5); return "AddressToLocation"; } else if (type == Type.LOCATIONTOADDRESS) { addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); addressText = String.format( "%s, %s, %s", address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", address.getLocality(), address.getCountryName()); return addressText; } } } catch (IOException e) { e.printStackTrace(); } } return null; } }
/** * Get a geocoding service instance, pass latitude and longitude to it, format the returned * address, and return the address to the UI thread. */ @Override protected String doInBackground(Location... params) { /* * Get a new geocoding service instance, set for localized addresses. This example uses * android.location.Geocoder, but other geocoders that conform to address standards * can also be used. */ Geocoder geocoder = new Geocoder(localContext, Locale.getDefault()); // Get the current location from the input parameter list Location location = params[0]; // Create a list to contain the result address List<Address> addresses = null; // Try to get an address for the current location. Catch IO or network problems. try { /* * Call the synchronous getFromLocation() method with the latitude and * longitude of the current location. Return at most 1 address. */ addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); // Catch network or other I/O problems. } catch (IOException exception1) { // Log an error and return an error message Log.e(LocationUtils.APPTAG, getString(R.string.IO_Exception_getFromLocation)); // print the stack trace exception1.printStackTrace(); // Return an error message return (getString(R.string.IO_Exception_getFromLocation)); // Catch incorrect latitude or longitude values } catch (IllegalArgumentException exception2) { // Construct a message containing the invalid arguments String errorString = getString( R.string.illegal_argument_exception, location.getLatitude(), location.getLongitude()); // Log the error and print the stack trace Log.e(LocationUtils.APPTAG, errorString); exception2.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 String addressText = getString( R.string.address_output_string, // 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 return addressText; // If there aren't any addresses, post a message } else { return getString(R.string.no_address_found); } }
/** * 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); }
@Override protected void onPostExecute(List<Address> addresses) { if (addresses == null || addresses.size() == 0) { Toast.makeText(getContext(), "No Location found", Toast.LENGTH_SHORT).show(); } // Clears all the existing markers on the map mMap.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); mMap.setOnMarkerClickListener( new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { tvSelectedLoc.setText(marker.getTitle() + marker.getPosition().toString()); etEvntLoactioan.setText(marker.getTitle()); event.setAddressLocation(marker.getTitle()); event.setLang(marker.getPosition().longitude); event.setLat(marker.getPosition().latitude); return true; } }); mMap.addMarker(markerOptions); // Locate the first location if (i == 0) { mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13)); tvSelectedLoc.setText(addressText); etEvntLoactioan.setText(addressText); event.setAddressLocation(addressText); event.setLang(latLng.longitude); event.setLat(latLng.latitude); } } /** * Manipulates the map once available. This callback is triggered when the map is ready to be * used. This is where we can add markers or lines, add listeners or move the camera. In this * case, we just add a marker near Sydney, Australia. If Google Play services is not installed * on the device, the user will be prompted to install it inside the SupportMapFragment. This * method will only be triggered once the user has installed Google Play services and returned * to the app. */ }
/** * @param location 当前坐标 * @return 地理位置的国家名称 */ public String updateWithNewLocation(Location location, Context mContext) { String addressString = "Unknown"; if (location == null) { Log.i(TAG, "location is null"); location = localLocation; } if (location != null) { double latitude = location.getLatitude(); double longitude = location.getLongitude(); // 更具地理环境来确定编码 Geocoder geocoder = new Geocoder(mContext, Locale.CHINA); List<Address> allAddress = null; try { // 取得地址相关的一些信息\经度、纬度 allAddress = geocoder.getFromLocation(latitude, longitude, 1); StringBuilder sb = new StringBuilder(); StringBuilder sbline = new StringBuilder(); if (allAddress.size() > 0) { Address address = allAddress.get(0); for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { sbline.append(address.getAddressLine(i)); } addressString = address.getCountryName(); if (!addressString.equals("")) { return addressString; } String adminArea = address.getAdminArea(); // 省 sb.append("adminArea(省)=" + address.getAdminArea()).append("\n"); // 省 String locality = address.getLocality(); sb.append("locality(地区,市)=" + address.getLocality()).append("\n"); // 城市名称 String featureName = address.getFeatureName(); sb.append("FeatureName(街道)=" + address.getFeatureName()).append("\n"); // 街道名称,一定要显示 addressString = sb.toString(); /* * 如果 getMaxAddressLineIndex中只显示“中国“则”str=省+地区+街道 如果程度 */ int start = sbline.indexOf("中国"); String strSbline = sbline.toString(); if (strSbline.equals("中国")) { // 不做显示,只显示判断地区和省 if (adminArea.equals(locality)) { // 省和地区相同 addressString = locality + featureName; // "地区:"+"街道:"+ } else { // 省和地区不一样 addressString = adminArea + locality + featureName; // "省:"+"地区:"+"街道:" } } else { if (start != -1) { // 有中国2字 String subStr = sbline.toString().substring(start + 2); // 去掉中国2字 addressString = subStr + featureName; } } if (locality.contains("市")) { locality = locality.substring(0, locality.indexOf("市")); } // mLocationCurrentCity = locality;// 定位城市赋值 } addressString = sbline.toString(); return addressString; } catch (IOException e) { e.printStackTrace(); Log.i(TAG, "LocationInfo updateWithNewLocation exception : " + e.toString()); } } return addressString; }
/** * 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"; } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_bike_spot); configToolBar(); session = new SessionManager(getApplicationContext()); HashMap<String, String> user = session.getUserDetails(); sessionUser = user.get(session.KEY_REGISTRATION); edtTextAddressName = (EditText) findViewById(R.id.editTextAddressBikeSpot); edtTextNumber = (EditText) findViewById(R.id.editTextAddressNumber); edtTextReference = (EditText) findViewById(R.id.editTextReference); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); String provider = getBestProvider(); addListenerOnNumberPickerCapacity(); loadBikeSpotCathegory(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } location = locationManager.getLastKnownLocation(provider); // LocationManager.GPS_PROVIDER if (location == null) { location = getCurrentLocationFromUser(); } if (location != null) { this.onLocationChanged(location); } Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); try { List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); Address address = addresses.get(0); street = address.getAddressLine(0); cityState = address.getAddressLine(1); String[] parts = street.split(","); street = parts[0]; number = address.getFeatureName(); city = address.getLocality(); country = address.getCountryName(); postalCode = address.getPostalCode(); edtTextAddressName.setText(street.toString()); edtTextNumber.setText(number.toString()); } catch (Exception e) { AlertDialog.Builder dialogo = new AlertDialog.Builder(NewBikeSpotActivity.this); dialogo.setTitle("Aviso!"); dialogo.setMessage(MESSAGE_EMPTY_ADDRESS); dialogo.setNeutralButton( "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { showMapActivity(); } }); dialogo.show(); } addEditTextOnEditorActionListener(); btnSaveBikeSpotLocal = (Button) findViewById(R.id.btnSaveBikeSpot); btnSaveBikeSpotLocal.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if ((edtTextReference.getText().toString().trim().length() == 0) || (edtTextAddressName.getText().toString().trim().length() == 0) || (edtTextNumber.getText().toString().trim().length() == 0)) { Toast.makeText(getApplicationContext(), MESSAGE_ERROR_NOFILLED, Toast.LENGTH_LONG) .show(); } else { final String fullAddressNewBikeSpot = edtTextAddressName .getText() .toString() .trim() .concat(", ") .concat( edtTextNumber .getText() .toString() .trim() .concat(" - ") .concat(cityState)); boolean check = isBikeSpotExists(convertLocationToParseGeoPoint(location)); boolean check2 = isBikeSpotExists(fullAddressNewBikeSpot); if (check || check2) { Toast.makeText(getApplicationContext(), MESSAGE_BIKESPOT_EXISTS, Toast.LENGTH_LONG) .show(); } else { saveNewBikeSpot(); showMapActivity(); } } } }); imgBikeSpotPic = (ImageButton) findViewById(R.id.imageButtonPicture); ivBikeSpot = (ImageView) findViewById(R.id.imageViewBikeSpot); imgBikeSpotPic.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { try { if (isDeviceSupportCamera()) captureImage(); } catch (Exception ex) { openDialogCamera(); } } }); }
public void send(View v) { Button button = (Button) v; button.setText("SENT"); EditText edittext = (EditText) findViewById(R.id.editText); String details = edittext.getText().toString(); String phoneNo = "9292442978"; // Insert server phone number here. 9292442978 gps = new GPSTracker(MainActivity.this); double latitude = 0.0; double longitude = 0.0; if (gps.canGetLocation()) { latitude = gps.getLatitude(); longitude = gps.getLongitude(); } else { // can't get location // GPS or Network is not enabled // Ask user to enable GPS/network in settings gps.showSettingsAlert(); } String message = "swagmaster2000\n"; String cityName; String countryName; Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault()); List<Address> addresses; try { addresses = gcd.getFromLocation(latitude, longitude, 1); cityName = addresses.get(0).getLocality(); countryName = addresses.get(0).getCountryName(); Address address = addresses.get(0); String readablehurrdurr = 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(), // The country of the address address.getCountryName(), address.getPostalCode()); // getPostalCode() message += (readablehurrdurr + "\n"); message += (countryName + "\n"); message += (cityName + "\n"); } catch (IOException e) { e.printStackTrace(); } message += details + "\n"; // Toast.makeText(getApplicationContext(), message + longitude + "\n" + latitude, // Toast.LENGTH_LONG).show(); if (edittext.getText().toString().equals("")) { Toast.makeText( getApplicationContext(), "Please describe the emergency and your location", Toast.LENGTH_LONG) .show(); button.setText("SEND"); return; } flag = displayGpsStatus(); if (flag) { try { SmsManager smsManager = SmsManager.getDefault(); PendingIntent sentPI; String SENT = "SMS_SENT"; sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0); smsManager.sendTextMessage(phoneNo, null, message, sentPI, null); Toast.makeText( getApplicationContext(), "Sent. Please wait for aid.", // "SMS sent. " + sentPI.toString() Toast.LENGTH_LONG) .show(); } catch (Exception e) { // error lol Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } } else { alertbox(); } edittext.setText(""); }
public void initiateLocation() { if (placeName == null) return; JSONObject locationInfo = getLocationInfo(placeName); try { lon = ((JSONArray) locationInfo.get("results")) .getJSONObject(0) .getJSONObject("geometry") .getJSONObject("location") .getDouble("lng"); lat = ((JSONArray) locationInfo.get("results")) .getJSONObject(0) .getJSONObject("geometry") .getJSONObject("location") .getDouble("lat"); } catch (Exception e) { e.printStackTrace(); } int numberOptions = 5; String[] optionArray = new String[numberOptions]; 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. try { List<Address> results = gcoder.getFromLocationName(placeName, numberOptions); Iterator<Address> locations = results.iterator(); String raw = "\nRaw String:\n"; String country; int opCount = 0; while (locations.hasNext()) { Address location = locations.next(); 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.i("Location-List", raw); Log.i("Location-List", "\nOptions:\n"); for (int i = 0; i < opCount; i++) { Log.i("Location-List", "(" + (i + 1) + ") " + optionArray[i]); } ShowTheMap.putLatLong(lat, lon); } catch (IOException e) { Log.e("Geocoder", "I/O Failure; is network available?", e); } }