How to get Latitude Longitude from more than 500 addresses? - android

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.

Related

Android Geocoder returns null city name

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.

Reverse GeoCoordinate Class gives Location Not found error

i m using google Reverse Geocoding API in my app, i m succussfully able to get get coordinate using google geolocation API. Now i m trying to get Location Name from Reverse Geocoding API , but always returns Location not found error
here is my code:
Geocoder geocoder= new Geocoder(MainActivity.this, Locale.ENGLISH);
if(geocoder.isPresent()){
List<Address> list;
try {
list = geocoder.getFromLocation(37.42279, -122.08506,1);
Address address = list.get(0);
Log.d("this is working","thsi sis working");
StringBuffer str = new StringBuffer();
str.append("Name: " + address.getLocality() + "\n");
str.append("Sub-Admin Ares: " + address.getSubAdminArea() + "\n");
str.append("Admin Area: " + address.getAdminArea() + "\n");
str.append("Country: " + address.getCountryName() + "\n");
str.append("Country Code: " + address.getCountryCode() + "\n");;
String strAddress = str.toString();
JsonDatas.setText(strAddress);
Log.d("Address", strAddress);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i have several question
how google know that which app requested the API and how google determine of Quota that app. in google API developer Console, google gave Quota for app API
Why i m getting location not found error but searching on google map location is showing
do i need to add google Geocoder APi key into my app - right now i m only Geolocation API key using for retrieve Coordinates
Please correct me if i m wrong, Please give suggestion so my code will work fine
thanks
Make sure you have latest Google play library in your project. I am using this code and working for me.
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
// Finding address using reverse geocoding
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
String addressText = "";
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
Thread.sleep(500);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
addressText = String.format(
"%s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(1) : "", "", "");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return addressText;
}
#Override
protected void onPostExecute(String addressText) {
}
}
Where LatLng is Latitude and longitute, check this for doc.
and to use write down new ReverseGeocodingTask(this).execute(latlng); where you want to get data.
Make sure you are adding permission into your manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

android application which takes city name and return latitude and longitude

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.

Geocoder getFromLocation(lat,lon) doesn't work

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.

Android: Reverse geocoding - getFromLocation

I am trying to get an address based on the long/lat. it appears that something like this should work?
Geocoder myLocation = Geocoder(Locale.getDefault());
List myList = myLocation.getFromLocation(latPoint,lngPoint,1);
The issue is that I keep getting : The method Geocoder(Locale) is undefined for the type savemaplocation
Any assistance would be helpful. Thank you.
Thanks, I tried the context, locale one first, and that failed and was looking at some of the other constructors (I had seen one that had mentioned just locale). Regardless,
It did not work, as I am still getting : The method Geocoder(Context, Locale) is undefined for the type savemaplocation
I do have : import android.location.Geocoder;
The following code snippet is doing it for me (lat and lng are doubles declared above this bit):
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Here is a full example code using a Thread and a Handler to get the Geocoder answer without blocking the UI.
Geocoder call procedure, can be located in a Helper class
public static void getAddressFromLocation(
final Location location, final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality();
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to Geocoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
Here is the call to this Geocoder procedure in your UI Activity:
getAddressFromLocation(mLastKownLocation, this, new GeocoderHandler());
And the handler to show the results in your UI:
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String result;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
result = bundle.getString("address");
break;
default:
result = null;
}
// replace by what you need to do
myLabel.setText(result);
}
}
Don't forget to put the following permission in your Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
It looks like there's two things happening here.
1) You've missed the new keyword from before calling the constructor.
2) The parameter you're passing in to the Geocoder constructor is incorrect. You're passing in a Locale where it's expecting a Context.
There are two Geocoder constructors, both of which require a Context, and one also taking a Locale:
Geocoder(Context context, Locale locale)
Geocoder(Context context)
Solution
Modify your code to pass in a valid Context and include new and you should be good to go.
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> myList = myLocation.getFromLocation(latPoint, lngPoint, 1);
Note
If you're still having problems it may be a permissioning issue. Geocoding implicitly uses the Internet to perform the lookups, so your application will require an INTERNET uses-permission tag in your manifest.
Add the following uses-permission node within the manifest node of your manifest.
<uses-permission android:name="android.permission.INTERNET" />
The reason for this is the non-existent Backend Service:
The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform.
First get Latitude and Longitude using Location and LocationManager class. Now try the code below for Get the city,address info
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(lat, lng, 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());
}
City info is now in sb. Now convert the sb to String (using sb.toString() ).
Well, I am still stumped. So here is more code.
Before I leave my map, I call SaveLocation(myMapView,myMapController); This is what ends up calling my geocoding information.
But since getFromLocation can throw an IOException, I had to do the following to call SaveLocation
try
{
SaveLocation(myMapView,myMapController);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Then I have to change SaveLocation by saying it throws IOExceptions :
public void SaveLocation(MapView mv, MapController mc) throws IOException{
//I do this :
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
List myList = myLocation.getFromLocation(latPoint, lngPoint, 1);
//...
}
And it crashes every time.
Use this
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

Categories

Resources