Easy way to get city from LocationManager on Android? - java

I'm trying to figure out the city of where the user is using their location. Using LocationManager and Geocoder I get some nice data from the longitude and latitude, but I can't get one thing. The subAdminArea a.k.a. the city. It always returns null for me, even though everything else including the postal code is received. Is there something I am missing?
Basically this is a method I call for getting data.
public String getLocation(Locale locale, Context context, boolean city, boolean postal, boolean state_prov) throws IOException{
LocationManager locMan = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locList = new MyLocList();
Geocoder gC = new Geocoder(context,locale);
Location gpsLocation = locMan.getLastKnownLocation(locMan.GPS_PROVIDER);
locMan.requestLocationUpdates(locMan.NETWORK_PROVIDER, 500, 200, locList);
Location networkLocation = locMan.getLastKnownLocation(locMan.NETWORK_PROVIDER);
if (city)
return (gC.getFromLocation(networkLocation.getLatitude(), networkLocation.getLongitude(), 1).get(0).getSubAdminArea());
else if (postal)
return (gC.getFromLocation(networkLocation.getLatitude(), networkLocation.getLongitude(), 1).get(0).getPostalCode());
else if (state_prov)
return (gC.getFromLocation(networkLocation.getLatitude(), networkLocation.getLongitude(), 1).get(0).getAdminArea());
else
return "";
}
and the call to this method is done via:
String city = getLocation(Locale.getDefault(),getBaseContext(),true,false,false);
The only other option I have found through some research is sending a request to
http://maps.googleapis.com/maps/api/geocode/json?address=POSTALCODE&sensor=true
and it gives me a JSON of that location based on the postal code, which I can then parse, but it seems like a lot of work to find the city.
Could there be something I am missing? Or something I did wrong? I am new to location services for android.

Try this:
Geocoder gc = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gc.getFromLocation(latitude, longitude, maxResults);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < addresses.getMaxAddressLineIndex(); i++)
Log.d("=Adress=",addresses.getAddressLine(i));
}
You will get postal code, city , country, ....

I used this answer and it worked perfectly fine. It was able to get the location despite the problems I initially had in this question.

Related

How to get address from current location from setMyLocationEnabled(true);

In my project I used Google Maps Activity and to get the user's current location I used setMyLocationEnabled(this); method to get the location. And when I tried to fetch the latitude and longitude from that location it throws a error says null object reference.
I looked for many videos in YouTube and examined many questions in stack overflow and blogs but I can't find the proper code to be done to do that. Some use deprecated methods and some go way beyond the topic.
So all I want is to do the reverse geo coding to get the address from my location and also add a marker at that point.
Help me guide what to do and how to obtain that I'm stuck with that from past 4 days.
Reverse Geocoding is what you are looking for. Geocoder class can be used
Look at this Android: Reverse geocoding - getFromLocation
It will give you idea of using reverse geocoding
You can use getFromLocation from Geocoder.
Sample code.
Geocoder geocoder = new Geocoder(context, 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());
String result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
}

Set double coordinates to GMaps

I have got 3 maps on my app, want to change longtitude and latitude with Parse.com if it's needed.
I follow this way:
String place1latitudeSTRING = "49.986595";
public Double place1latitude = Double.valueOf(place1latitudeSTRING);
String place1longitudeSTRING = "31.294509";
public Double place1longitude = Double.valueOf(place1longitudeSTRING);
then i download changes from Parse.com. In my LOG i can see that application really download new double.
Then i have got condition:
Double list_maps_new_coordinates = maps_coordinates.get(6);
String place1longitudeChanged = Double.toString(list_maps_new_coordinates);
place1longitude = Double.valueOf(place1longitudeChanged);
And finally in my private void SetUpMap i have got this code:
mMap.addMarker(new MarkerOptions().position(new LatLng(place1latitude, place1longitude))
Question: Why not change the coordinates? Where is mistake?

Android SQLite vs File vs JSON?

I'm using google maps to plot markers on a map. I can save the data for ALL these points (it's over 17000 rows with 3 columns: shopId,shopName,lat,long).
I can also send JSON queries specifying my lat/long and the radius at what shops around I want data about. Then I'll receive the data back. This works, but when I create the markers (with AsyncTask) freezing occurs in the app (and it is noticeable).
This is the code I'm using to generate the custom markers on Google maps:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONArray jsonArray = new JSONArray(result);
String finalReturn[] = result.split("\\r?\\n");
if(jsonArray.get(0).toString().equals("4")) {
for (int i = 1; i < finalReturn.length; i++) {
jsonArray = new JSONArray(finalReturn[i]);
IconGenerator iconGenerator = new IconGenerator(getApplicationContext());
iconGenerator.setStyle(IconGenerator.STYLE_RED);
iconGenerator.setRotation(90);
iconGenerator.setContentRotation(-90);
Bitmap iconBitmap = iconGenerator.makeIcon(jsonArray.get(5).toString());
Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(jsonArray.getDouble(6), jsonArray.getDouble(7)))
.icon(BitmapDescriptorFactory.fromBitmap(iconBitmap)));
marker.setTitle(jsonArray.getString(1));
marker.setSnippet(jsonArray.getString(2) + " " + jsonArray.getString(8));
}
}
} catch (JSONException e) {
}
My question is, what is the best solution here, store the points in a MySQL server and generate nearest shops from that area (SQlite Getting nearest locations (with latitude and longitude) something like this), or always query the server for the data. Or maybe a hybrid of both (query the server, then save the data in an SQLite db.)
I'm only a beginner in Android so sorry if this question is simple.
The fastest way should be to save the data in an SQLite db and query it from there, but if you only need the few shops that are near the user, it should be fine to simply call the web service every time.
Other than that, the freezing that occurs in your app is most likely due to the onPostExecute Method being called in the UI-Thread and you doing heavy work in this method.
You should not parse your JSON there, but rather in the doInBackground method and for each parsed element call publishProgress that calls the onProgressUpdate Method (which is also executed in the UI-Thread.
Like this, you can handle setting one single marker on the map at a time and that way, the time between the single onProgressUpdate calls can be used by the system to update the UI and so the freezing should no longer occur.
It should look somewhat like this:
protected Void doInBackground(...) {
String result = getResult();
try {
JSONArray jsonArray = new JSONArray(result);
String finalReturn[] = result.split("\\r?\\n");
if(jsonArray.get(0).toString().equals("4")) {
for (int i = 1; i < finalReturn.length; i++) {
jsonArray = new JSONArray(finalReturn[i]);
publishProgress(jsonArray);
}
}
} catch (JSONException e) {
//handle error
}
}
#Override
protected void onProgressUpdate(JSONArray... progress) {
JSONArray array = progress[0];
IconGenerator iconGenerator = new IconGenerator(getApplicationContext());
iconGenerator.setStyle(IconGenerator.STYLE_RED);
iconGenerator.setRotation(90);
iconGenerator.setContentRotation(-90);
Bitmap iconBitmap = iconGenerator.makeIcon(jsonArray.get(5).toString());
Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(jsonArray.getDouble(6), jsonArray.getDouble(7)))
.icon(BitmapDescriptorFactory.fromBitmap(iconBitmap)));
marker.setTitle(jsonArray.getString(1));
marker.setSnippet(jsonArray.getString(2) + " " + jsonArray.getString(8));
}

Geocoding Code not Working - Googlemaps

I am trying to use geocoding to take an address, work out the longitude and latitude and then display an overlay on the map.
I am using the below code, however the log entry Log.e("Found",""+lat); never triggers and I'm not sure why. Can anybody help ?
Thanks !
private void showpins() throws IOException {
Geocoder gc = new Geocoder(this);
String Address = "Oxford Street, London";
Log.e("Lat",""+Address);
List<Address> foundAdresses = gc.getFromLocationName(Address, 5); //Search addresses
int lat;
int lon;
for (int i = 0; i < foundAdresses.size(); ++i) {
Address x = foundAdresses.get(i);
lat = (int) x.getLatitude();
lon = (int) x.getLongitude();
Log.e("Found",""+lat);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin);
CustomizedItemOverlay itemizedOverlay =
new CustomizedItemOverlay(drawable, this);
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayitem =
new OverlayItem(point, "Hello", "Location");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
}
}
There are definite issues with this in certain emulator API levels. See Issue 8816: service not available. For example API level 8 won't work. I find that API level 7 is OK if you call the method twice. The behaviour on real devices is not known to me. I don't think Google guarantee that the service will always be available.
Either you address is not in Google maps address database or your app does not have internet access privileges.
Check in http://maps.google.com that the address is actually found.
That yor app has internet access privileges. You must have this in ypur app manifest:
<uses-permission android:name="android.permission.INTERNET" />

Location Exception while using GPS(Location API)

I have downloaded google map application on sonyerricsom T700 mobile its working fine,its java application.So as per my understanding that is also using Location API.
This link shows that it does not have GPS.
But it is showing map and even locating photo's clicked on device on google map.
So I am tried below code in j2me using Location API(JSR-179).Its working fine on emulator.
But when I am trying the same on Sony erisccon T700 mobile its giving below exception:
Exception:
javax.microedition.location.LocationException:All service providers are out of service.
Code:
try {
// Create a Criteria object for defining desired selection criteria
Criteria cr = new Criteria();
LocationProvider lp = LocationProvider.getInstance(cr);
l = lp.getLocation(60);
c = l.getQualifiedCoordinates();
//cityMap.setCategories(selectedCategories);
if (c != null) {
// use coordinate information
double lat = c.getLatitude();
//latitude="";
latitude = ""+lat;
Latitude.setString(latitude);
double lon = c.getLongitude();
longitude =""+lon;
Longitude.setString(longitude);
}
}
catch (LocationException e) {
alert = new Alert("LocationException");
alert.setString("Unable to retrive location information:" + e);
alert.setTimeout(2000);
display.setCurrent(alert);
// not able to retrive location information
//e.printStackTrace();
} catch (InterruptedException ie) {
alert = new Alert("InterruptedException");
alert.setString("Operation Interrupted:" + ie);
alert.setTimeout(2000);
display.setCurrent(alert);
}
}
Please suggest me any solution for this...
Thank and regards.
Yeah, I bet it's not exact location like you would get from GPS.
Google has other ways of finding your location... it's probably using Cell ID. Luckily Sony Ericsson handsets are quite easy to find Cell ID from, see here. Once you have it, you can look it up in a cell ID database to find location.

Categories