Geocoding Code not Working - Googlemaps - java

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" />

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);
}

How can I get addresses from a specific country / state / political division in Android?

I am developing an application that uses the Google Maps API, and the user set an address and the application finds different and possible addresses that match the address that the user entered, but I want the address of a specific city, state or country if it is possible.
For example:
I want to find the address "Washington Ave.", Google Maps find some address:
"Washington Avenue, Filadelfia, Pensilvania"
"Washington Avenue, New Orleans, Louisiana"
"Washington Avenue, Houston, Texas"
But, what if I want just results inside Houston City? Or Pensilvania?, Or another country?
I have this Java code in Android Studio that finds a possible address that matches a String (address written by the user), and the possible options can only show 5, and it returns the latitude and longitude of the address written by the user
Geocoder geocoder = new Geocoder(this);
List<Address> addresses = new ArrayList<>();
addresses = geocoder.getFromLocationName("Manuel de la Peña y Peña 805-835, Bella Vista, 64410 Monterrey, N.L.", 5);
if(addresses.size() > 0) {
double latitude= addresses.get(0).getLatitude();
double longitude= addresses.get(0).getLongitude();
}
So, how can I find addresses inside a specifically a citiy, state or country in Google Maps API for Android?
In order to get addresses located inside a certain area you should use a service that supports strict bounds for address search. Currently strict bounds are supported in place autocomplete service and you can find documentation in Places SDK for Android:
https://developers.google.com/places/android-sdk/autocomplete#get_place_predictions_programmatically
The idea is create a rectangular bounds object that matches the city or region you are interested in and use strict bound filters when you search address predictions.
The code snippet is the following. Note setLocationRestriction and setCountry filters when you construct a prediction request
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
// Create a RectangularBounds object for area you are interested in.
RectangularBounds bounds = RectangularBounds.newInstance(
new LatLng(-33.880490, 151.184363),
new LatLng(-33.858754, 151.229596));
// Use the builder to create a FindAutocompletePredictionsRequest.
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
// Call setLocationRestriction() with bounds in order to restrict search to given area.
.setLocationRestriction(bounds)
.setCountry("au")
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(query)
.build();
placesClient
.findAutocompletePredictions(request)
.addOnSuccessListener((response) -> {
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
Log.i(TAG, prediction.getPlaceId());
Log.i(TAG, prediction.getPrimaryText(null).toString());
}
}).addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.e(TAG, "Place not found: " + apiException.getStatusCode());
}
});
For further details please have a look at Places SDK for Android documentation.
I hope this helps!

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?

Easy way to get city from LocationManager on Android?

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.

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