Preface:
One of readers asked me to write about getting the names of the location that I touch on the map if it is possible to get names from coordinates. That query triggered me to write this article. The answer is yes we can get location names if we have coordinates, the process is called Geocoding.
Geocoding is the process in which we translate latitude and longitude sets to text based address or string location names. Like if we have the coordinates 33695043,73050000 and we want to know which location is it. We will use geocoding and will find out that its Islamabad, the capital of Pakistan. Same is the case with Reverse Geocoding, if we have the name Islamabad, we can Reverse Geocode it to fine the coordinates. To continue with this article I have used the code from my last tutorial i.e, https://mirnauman.wordpress.com/2012/04/26/android-google-maps-tutorial-part-7-drawing-a-path-or-line-between-two-locations/ but u guys don’t need to use the code from that tutorial. You can use ur current google maps app and just insert the OnTouchEvent method the YourOverlay Class that extends Overlay Class
A lil boring theory:
We will use the Geocoder Class. This class is used for Geocoding and Reverse Geocoding. Now in Reverse Geocoding things can be a lil tricky coz the returned latitude, longitude values depend on the string address details that a user has provided. It may be just a city name, a city name with a street name or a city name with street name and name of a building or specific location. 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. The major public methods of this class are getFromLocation() and getFromLocationName(). The earlier one will transform lat,long values to string location names and the later one will get the coordinates from string location names. both the methods will return an array of address i.e, List< Addresses >.
Enough theory, now some real stuff
Add the following code to the class that extends Overlay Class
@Override public boolean onTouchEvent(MotionEvent event, MapView mapView) { //---when user lifts his finger--- if (event.getAction() == 1) { GeoPoint p = mapView.getProjection().fromPixels( (int) event.getX(), (int) event.getY()); Toast.makeText(getBaseContext(), p.getLatitudeE6() / 1E6 + "," + p.getLongitudeE6() /1E6 , Toast.LENGTH_SHORT).show(); Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault()); try { List<Address> addresses = geoCoder.getFromLocation(p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1); String strCompleteAddress= ""; if (addresses.size() > 0) { for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++) strCompleteAddress+= addresses.get(0).getAddressLine(i) + "\n"; } Log.i("MyLocTAG => ", strCompleteAddress); Toast.makeText(getBaseContext(), strCompleteAddress, Toast.LENGTH_LONG).show(); } catch (IOException e) { Log.i("MyLocTAG => ", "this is the exception part"); e.printStackTrace(); } return true; } else return false; }
The first Toast will show only the latitude and longitude in number for the location that is touched. Then we created an object of the Geocoder class.
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
Than we called the getFromLocation method, provided it with the latitude and longitude values and the number of search results that will be returned.
List<Address> addresses = geoCoder.getFromLocation(p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1);
After this we concatenate each value in the Addresses array list to get a single string with the complete location address.
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++) strCompleteAddress += addresses.get(0).getAddressLine(i) + "\n";
The last part displays a Toast that will show the string location name.
Toast.makeText(getBaseContext(), strCompleteAddress, Toast.LENGTH_LONG).show();
Same is the case with Reverse Geocoding, if we have the string location name we can get the coordinates to that location by using Reverse Geocoding. The sample code for Reverse Geocoding is attached below.
Geocoder geoCoder = new Geocoder(this, Locale.getDefault()); try { List<Address> addresses = geoCoder.getFromLocationName("Bhattai Rd Islamabad", 5); String strCompleteAddress = ""; if (addresses.size() > 0) { p = new GeoPoint( (int) (addresses.get(0).getLatitude() * 1E6), (int) (addresses.get(0).getLongitude() * 1E6)); mc.animateTo(p); mapView.invalidate(); } } catch (IOException e) { e.printStackTrace(); }
Related articles
- Android Google Maps Tutorial Part 7, Drawing A Path or Line Between Two Locations (mirnauman.wordpress.com)
- Android Google Maps Tutorial Part 6, Getting The Location That Is Touched. (mirnauman.wordpress.com)
39 comments
Comments feed for this article
June 15, 2012 at 6:59 pm
manu
this is very laggy method my phone is very slow by using this code.
how can i implement this by using Async Task or thread ?? can u explain that ……..please help me… thanks in advance…
June 17, 2012 at 4:32 pm
Mir
this is just to demonstrate how to work around google maps. this is the core functionality of getting the names from coordinates. if u know how to work with threads, u can simply put this in a thread. if u dont know how to work wid threads than i ll write an all new tutorial about working with threads. but still that wont be spoon feeding. if will provide just the main functionality. wat u will do is, get chunks from both and implement ur own logic.
June 18, 2012 at 4:44 pm
manu
Thanks Mir..i will do…
i have another doubt how we draw a route like the form of road.. (ie,reach the destination through road)can u give me an idea about that..
June 19, 2012 at 5:11 am
Mir
their r two ways to get the path along a road, first move ur actual device on along the road and draw the path using my tutorial. secondly open google earth, draw a path along a road, save the path as a KML. parse the KML in android code and draw the path using that kml. Currently i am working on making kml parsing simpler.
July 9, 2012 at 10:35 am
Rafał Machnik
use the multi threading to geocoding, and Handler to get the message and display the values from the geocoding method
June 19, 2012 at 6:27 am
manu
thank u mir for the information.i will try that .. i am a beginner in android so i think u will post the KML parsing for us……
July 24, 2012 at 5:36 pm
manohar
this is an exhaustive tutorial , well written and thank you for your time .
August 2, 2012 at 3:56 am
Mir
thanks manohar
August 3, 2012 at 3:55 am
Kenny
Dear Mir, I’m trying to parse the KML file but I’ve realized it’s useless cause KML file isn’t downloadable from google earth now. Do you have another way?
September 23, 2012 at 6:12 pm
laxmi
this program is not displaying the address it jumps in to the exception in my code .i have copied this whole program eventhough its not working what can be the reason please answer me on my mail
September 24, 2012 at 6:24 am
Mir
well if u have started directly from this program than there could be endless reasons for the exception. first of all u need to start from part 1 of this series. if everything upto this parts works fine than u need to check wat updates u have installed. u need to tweek the code and the avd accordingly. more over if u can print the exception that will help in trouble shooting the issue.
September 25, 2012 at 8:23 pm
laxmi
i have followed you through the beginning and every thing was going fine but in the case of reverse geocoding i got stucked ,i diddn’t get the place name rather it jumps to exception handling part. and prints nothing.even i switched myself from 2.2 api 8 to api 10.
is this the emulator issue?
September 26, 2012 at 4:45 am
Mir
in reverse geo coding its not necessary that wat ever place u click will show u the name. coz only certain specific coordinates are mapped to certain names. if there is even a single digit difference, name for that location of will not be returned. to test ur app. u need to hard code names and coodinates. and get those names and coodinates from internet or google maps or google earth.
November 19, 2012 at 4:31 am
levi91
Thanks for your sharing Mir..
I have a problem in development my android map app, i want to use mylocation coordinate as a trigger to appear information about current location. e.g : I’m at a large location, such as a nasional meseum, and my app will automaticly say “welcome to botani meseum” base on trigger of coordinate .may i use geocoding for this case?
November 20, 2012 at 5:53 am
Mir
yes, u have to use geocoding to get the name of ur location according to ur coordinates.
November 28, 2012 at 9:53 am
Android Google Maps(Geocoding and Reverse Geocoding.) « Said Fuad
[…] view source […]
December 9, 2012 at 11:27 am
patrix
I followed your posts and performed the same steps mentioned in those posts. However, in this post of Geocoding, I am getting an IOException as “Service not available” at the line that includes ‘getFromLocation()’ method. Same is in the case of ‘getFromLocationName()’. Please Help.
December 9, 2012 at 11:28 am
patrix
please help me with the above problem as soon as possible, its very urgent
December 18, 2012 at 7:26 am
Mir
dear patrix, sorry for late reply. this issue can be raised from a number of reasons. for starters you can update the emulator.
January 19, 2013 at 10:26 pm
Roby
Hi!Please help me with a problem – how can I combine part 8 with part 3(Adding An Image to GoogleMaps)?
January 20, 2013 at 6:22 pm
Mir
hi, wat exactly u want to do. can u explain it. i won’t be able to write the whole code for you but i can atleast guide u.
February 24, 2013 at 6:14 pm
Maimoonah
Thanks,
I want to write address in some points in the map,for example:”home”,”Supermarket”
Can I as programmer?
And what if user can do this ?
February 26, 2013 at 8:15 am
Mir
yes u can, just like image overlays, u need to map text to specific coordinates in the overlay layer. for storing them either u need to store the text in a text file (but that wont be a good idea) or u can store the values in SQLite Database. or u can even create xml files and store values in them. which ever like the best.
February 26, 2013 at 8:46 pm
Maimoonah
Thanks for answer
April 11, 2013 at 8:25 pm
abin sharma
Very Good Morning to all. I am Working on the Same Code since last Morning But my Emulator(AVD) is just showing the MAP not the location of the map. Please Help me. Thanks. Here is Code
*****
public boolean onTouchEvent(MotionEvent event,MapView mapview)
{
if(event.getAction()==1){
GeoPoint p=mapview.getProjection().fromPixels((int) event.getX(),(int )event.getY() );
/* Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + “,” +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
*/
Geocoder geocoder=new Geocoder(getBaseContext(), Locale.getDefault());
try{
List addresses=geocoder.getFromLocation(p.getLatitudeE6()/1E6, p.getLongitudeE6()/1E6, 1);
String add=””;
if(addresses.size()>0)
{
for(int i=0;i<addresses.get(0).getMaxAddressLineIndex();i++)
add+= addresses.get(0).getAddressLine(i)+"\n";
}
Log.i("MyLocaltag", add);
Toast.makeText(getBaseContext(),add , Toast.LENGTH_LONG).show();
}
catch(IOException e)
{
Log.i("secondlocaltag","exception part");
e.printStackTrace();
}
return true;
}
return false;
}
*****
and i am getting notification in log file showing "secondlocaltag-exception part" it means there is some problem in try block may be in this line or any other " List _____" .Please solve out my problem.
April 13, 2013 at 8:40 am
Mir
Dear abin sharma,
you said that ur avd is showing the map but not the location of the map. wat exactly you mean by that. does ur avd show an empty grid with no map at all or it does show the map but when u want to move to the current location or some hardcoded location though the code , ur map on the avd dont browse to that location. both of the above scenarios have different solutions. secondly if you can add a log statement before every statement in the try block you will get to the exact statement which is generating the error.
thanks.
April 13, 2013 at 1:31 pm
abin sharma
Thanks for your Reply mr. Mir I solved out the problem. Actually the problem was that My lap is keep on showing but my current location is not displaying in the toast. But it fixed right now. Thanks.keep in touch,See you soon. 🙂
May 14, 2013 at 10:02 am
nummerupplysningen
I think the admin of this web page is truly working hard for his site, because here every information is quality based information.
May 15, 2013 at 2:33 pm
Abin sharma
Yes, Mr. sningen 🙂
May 15, 2013 at 2:34 pm
Abin sharma
Yes Mr. Sningen 🙂
May 28, 2013 at 8:04 am
Genevieve
Why visitors still make use of to read news papers when in this technological globe everything is existing
on web?
June 11, 2013 at 4:29 am
Mir
because for every media there is a different audience. the guys that r used to reading hardcopy news papers, they will never use the web coz the web has not that level of satisfaction that they need. having a solid material physical paper in hand gives them the satisfaction that the virtual existence of material on the web can’t.
there are still ppl around us that listen to radio’s (FM, AM etc ) wid dedicated radio devices and not the built in radio that comes in phones.
June 11, 2013 at 4:20 am
jackpot 6000 gratis
I love what you guys are up too. This kind of clever work and
reporting! Keep up the amazing works guys I’ve added you guys to my own blogroll.
July 16, 2013 at 6:18 am
Kishore
Hi Mir:
Am getting “java.io.ioexception service not available geocoder”
can i get any solution for this(in android device) am not able to display address
—
kishore
July 16, 2013 at 6:25 am
Mir
there are places for which when u click, u will get the address or name of place but there are coordinates on the grid to which no text address are associated, so this could be one cause. u need to check ur app for a known location and handle the exception for unknown locations. secondly google has launched android google maps api 2.0, the tutorial that u r following is of api 1.0, alot has changed. I have working on writing the same set of tutorials for api ver 2.0 as alot of things are not working they way they used to be before the launch of 2.0.
July 24, 2013 at 2:35 pm
Mohamed
Hi,
can you please tell me why this code return always exception?
Geocoder g = new Geocoder(getBaseContext(), Locale.getDefault());
String staddress = “Rue général leclerc, Paris,france”;
try{
List loc = g.getFromLocationName(staddress, 5);
p.setText(“yes”);
}
catch(IOException e) {
p.setText(“no”);
}
November 13, 2013 at 4:43 pm
Abubucker (@athick2)
here is my issue. When i use getFromLocation and pass lat, lon it gives me an address but that is not the exact address i am in right now.
I do understand that it’s quite difficult to provide the exact address. As an alternative i want to show multiple (10) nearby address to the user within a 50 meter radius and i want to be able to allow the user to pick up the one that is closest in match to his address. How do we achieve it ? Help much appreciated
November 17, 2013 at 8:14 am
Mir
Hello Abubucker,
Thanks for going through my articles. I have started working on my first book on android, and am almost at the end. the print version will be out any day in Nov, and am continuously in contact with the publisher to provide instant feedback what they need from me. I have not written any thing on my blog , but will start again from where i have left. so far the article that you are following is a bit out dated. Google Maps for Android API 1.0,
i have started writing for API Ver 2.0 but so far have only published two articles. will continue as soon as my books print version is out. I ll take ur senario on top, but will write my solution in API Ver 2.0. I hope u wont mind and will wait a few more days with me.
November 17, 2013 at 8:15 am
Mir
u can also follow the link to my first book
http://www.packtpub.com/learning-android-canvas/book
although its a bit irrelevant in ur context.