I have an activity which first uses an AsyncTask to get and parse data from a server.
The entries contain a latitude and a longitude.
Then, in onPostExecute() I load my adapter and display my listView. And in my adapter's getView() I try to display the location with the latitude and the longitude :
private String getPosition(String longitude, String latitude)
{
float lon = Float.parseFloat(longitude),
lat = Float.parseFloat(latitude);
Geocoder geocoder = new Geocoder(MyActivity.this, Locale.getDefault());
List<Address> addresses = null;
try
{
addresses = geocoder.getFromLocation(lat, lon, 1);
} catch (IOException e)
{
e.printStackTrace();
}
if(addresses == null || addresses.size() == 0) return "No location found.";
else
{
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
return (city + ", " + country.toUpperCase());
}
}
I always get "No location found." but I'm sure some entries are correct. For example one has a latitude of 39.017 and a longitude of 125.73. Google's API show there is at least one address for it :
http://maps.googleapis.com/maps/api/geocode/json?latlng=39.017,125.73&sensor=true
I've also declared this in my Manifest :
<uses-permission android:name="android.permission.INTERNET" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
But all this won't return any address. Any idea why?
geoCoder.getFromLocation (Reverse Geocoding) method will work when you build avd (virtual device) target as Google API 19 and also the application is built with the target set as "Google API 19" (you can modify the build target using Project->Properties). This worked for me. Should you need more details please reply to this post.
Related
I am new to Android development, following is my code about use Geocoder to get city name of current location, it returns null:
private void updateCurrentLocation(Location location) {
double lat = 0.0, lng = 0.0;
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
Log.i("tag", "Latitute is" + lat + ", Longtitute is" + lng);
} else {
City_Name = "Unavailable";
}
List<Address> list = null;
Geocoder geocoder = new Geocoder(this.getActivity());
try {
list = geocoder.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
//may provide multiple locations.
if (list != null && list.size() > 0) {
Address address = list.get(0);
City_Name = address.getLocality();
}
Log.i("Try", "CityName:" + City_Name);
//send empty message
handler.sendEmptyMessage(1);
}
I opened GPS services, add ACCESS_FINE_LOCATION and INTERNET permission in Manifest already. Also, I searched similar questions in Stackoverflow about Geocoder returns null, but haven't found useful solutions. One of them is analyze JSON from Geocoder website, but it doesn't work either.
Can anyone help with this? Thank you!
BTW, is there any better solution to receive a city name? Thank you!
If the "getFromLocation" method gives you an empty set then it's because the server that is being looked up doesn't have the address information for the coordinates you're passing it. This is also noted in the docs. So I think that you should let it go and use another service like the Google Maps geocoding service or another one like Nominatim from the OpenStreetMap project.
I have more than 700 addresses in database.
I want to plot them region wise.
I have implement this code :
public LatLng getSingleLocationFromAddress(String strAddress)
{
Geocoder coder = new Geocoder(this, Locale.getDefault());
List<Address> address = null;
Address location = null;
GeoPoint p1 = null;
LatLng temp = null;//new LatLng(26.0000, 121.0000);
String strAddresNew = strAddress.replace(",", " ");
try
{
address = coder.getFromLocationName(strAddresNew, 1);
if (!address.isEmpty())
{
location = address.get(0);
location.getLatitude();
location.getLongitude();
temp = new LatLng(location.getLatitude(), location.getLongitude());
Log.d("Latlng : ", temp + "");
} else
{
arrTemp.add(strAddress);
System.out.println(arrTemp);
}
} catch (IOException e)
{
Toast.makeText(mContext, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
return temp;
}
But the problem is when I call this method in loop like this:
Marker TP1 = googleMap.addMarker(new MarkerOptions().position(getSingleLocationFromAddress(fullAddress)));
The line coder.getFromLocationName(strAddresNew, 1); returns null for some addresses, for example if I have an ArrayList of 7 addresses then I get only 4-5 LatLong values.
Use below lines of code...It can be helpful for you
Declare these variables above yours Oncreate or OncreatView
List<Address> From_geocode = null;
private double sLat, sLong;
private Geocoder geocoder;
Than inside yours oncreate or oncreateVIew use these lines of code
geocoder = new Geocoder(getActivity());
try {
From_geocode = geocoder.getFromLocationName("PUT THE ADDRESS HERE", 1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (From_geocode.size() > 0) {
System.out.println("2");
From_geocode.get(0).getLatitude(); // getting
// latitude
From_geocode.get(0).getLongitude();
sLat = From_geocode.get(0).getLatitude();
sLong = From_geocode.get(0).getLongitude();
System.out.println("LATITUTE====="+sLat+" LONGITUTE====="+sLong);
}
And provide the entry inside the manifest file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Although the google database is extensive it is possible that some of the addresses that you have supplied could not be geocoded. Hence you will not get a lat/lon for those addresses. You could probably check the status of the response.
As mentioned in the link below
https://developers.google.com/maps/documentation/geocoding/#StatusCodes
The "status" field within the Geocoding response object contains the status of the request, and may contain debugging information to help you track down why geocoding is not working. The "status" field may contain the following values:
"OK" indicates that no errors occurred; the address was successfully parsed and at least one geocode was returned.
"ZERO_RESULTS" indicates that the geocode was successful but returned no results. This may occur if the geocoder was passed a non-existent address.
An android application which takes city name as input and return longitude and latitude of the city.
Which method i should used to do it?
What changes will be needed in android manifest file?
You can try using Forward GeoCoding like this:
if(Geocoder.isPresent()){
try {
String location = "MyLocation";
Geocoder gcoder = new Geocoder(this);
List<Address> addresses= gcoder.getFromLocationName(location, 5); // get the found Address Objects
List<LatLng> ll = new ArrayList<LatLng>(addresses.size()); // A list to save the coordinates if they are available
for(Address addr : addresses){
if(addr.hasLatitude() && addr.hasLongitude()){
ll.add(new LatLng(addr.getLatitude(), addr.getLongitude();
}
}
} catch (IOException e) {
// handle the exception
}
}
You will require permission for Internet in manifest file.
<uses-permission android:name="android.permission.INTERNET"/>
Here is a blog that can help you.
Hope this helps.
I am testing an app which takes latitude and longitude with help of GPS in Samsung Tablet. I am able to capture current latitude, longitude from GPS unit. Now I want to get address from these location using latitude longitude without use of Internet i.e. wi-fi, mobile data.
I am doing it below manner:
public String getAddress(Context ctx, double latitude, double longitude) {
StringBuilder result = new StringBuilder();
try {
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
String locality=address.getLocality();
String city=address.getCountryName();
String region_code=address.getCountryCode();
String zipcode=address.getPostalCode();
double lat =address.getLatitude();
double lon= address.getLongitude();
result.append(locality+" ");
result.append(city+" "+ region_code+" ");
result.append(zipcode);
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return result.toString();
}
private class GetCurrentAddress extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// this lat and log we can get from current location but here we given hard coded
double latitude=12.916523125961666;
double longitude=77.61959824603072;
String address= getAddress(context, latitude, longitude);
return address;
}
#Override
protected void onPostExecute(String resultString) {
dialog.dismiss();
result.setText(resultString);
}
}
In mainfest i do below entries:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It is not possible to get Address from Lat Lang without internet because google also do geocoding
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
this getFromLocation() method should be run in asynTask and with internet then it gives desired result.
<uses-permission android:name="android.permission.INTERNET" />
Internet permission also need
It's not possible because GeoCoder needs external service which depends on internet.
Yes it is possible if U just need to get lat/long of user using GPS.
When any case for Geo-coding comes into consideration then you will need network connection in order to hit Google API for same.
Hope it fulfills your query !
I am working on a android app in which i came across a situation in which i need to get the current user postcode, so i am getting the current latitude and longitude but is there any way to find the current postcode by providing latitude and longitude.
If any web service or database to provide this information is available then please let me know about it.
If you are talking about PostalCode then, use this..
Geocoder geoCoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> address = null;
if (geoCoder != null){
try {
address= geoCoder.getFromLocation(latPoint, lngPoint, 1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (address.size()> 0){
String postCode = address.get(0).getPostalCode();
}
With these two permission on Manifest file..
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
At present the only official source of this data is the Royal Mail's Postcode Address File (PAF), which requires a licence (at some cost).