Simple GoogleMaps (GeoCoder / Convert address to lon/lat)

Tutorials that use the MapActivity. Many using GPS functionality.

Simple GoogleMaps (GeoCoder / Convert address to lon/lat)

Postby michels » Wed Sep 24, 2008 4:15 pm

GoogleMaps with Geocoder Class


This tutorial is also available in german at my android weblog Androidianer.de

Hey there,

I've written this tutorial, because there were a lot of questions in the android-group and in this forum about the functionality of the Geocoder Class and the possibility to convert an address in the longitude and latitude.
I hope this tutorial can clarify the most problems.

What the application can do:
Convert an entered address in longitude and latitude and display it in a map.

How it looks like:
Image


Here we go:

1. Create a nice layout in the main.xml. I will not explain XML-layouting here, cause there are a lot of good tutorials from plusminus in this forum. Donwload the attached source code to see my main.xml

2. Add the following permissions to the Manifest.xml over the <application> Tag

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  2. <uses-permission android:name="android.permission.INTERNET" />
  3.  
Parsed in 0.001 seconds, using GeSHi 1.0.8.4


3. Have fun with java. It's so easy with GeoCoder class:

All you have to do is:
- Create a new Geocoder instance
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. gc = new Geocoder(this); //create new geocoder instance
  2.  
Parsed in 0.030 seconds, using GeSHi 1.0.8.4


- Write a OnClickListener for the search button (btnSearch) and get the entered address from the EditText-field (address)
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. gc = new Geocoder(this); //create new geocoder instance
  2. btnSearch.setOnClickListener(new OnClickListener() {
  3.   public void onClick(View v) {
  4.     String addressInput = adress.getText().toString(); //Get input text
  5.   }
  6. });
  7.  
Parsed in 0.031 seconds, using GeSHi 1.0.8.4


- Let the GeoCoder class search for the entered address (don't forget the try-catch-statement)
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. gc = new Geocoder(this); //create new geocoder instance
  2. btnSearch.setOnClickListener(new OnClickListener() {
  3.   public void onClick(View v) {
  4.     String addressInput = adress.getText().toString(); //Get input text
  5.     try {
  6.       List<Address> foundAdresses = gc.getFromLocationName(addressInput, 5); //Search addresses
  7.     }
  8.     catch (Exception e) {
  9.       //@todo: Show error message
  10.     }
  11.   }
  12. });
  13.  
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


- Get the longitude and latitude from the found addresses and display the map (see full source code for the navigateToLocation function)
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. gc = new Geocoder(this); //create new geocoder instance
  2. btnSearch.setOnClickListener(new OnClickListener() {
  3.   public void onClick(View v) {
  4.     String addressInput = adress.getText().toString(); //Get input text
  5.     try {
  6.       List<Address> foundAdresses = gc.getFromLocationName(addressInput, 5); //Search addresses
  7.       for (int i = 0; i < foundAdresses.size(); ++i) {
  8.         //Save results as Longitude and Latitude
  9.         //@todo: if more than one result, then show a select-list
  10.         Address x = foundAdresses.get(i);
  11.         lat = x.getLatitude();
  12.         lon = x.getLongitude();
  13.       }
  14.       navigateToLocation((lat * 1000000), (lon * 1000000), myMap); //display the found address
  15.     }
  16.     catch (Exception e) {
  17.       //@todo: Show error message
  18.     }
  19.   }
  20. });
  21.  
Parsed in 0.038 seconds, using GeSHi 1.0.8.4



Full Source
The full source also displays an error if the address wasn't found (check also the attachment for manifest and main.xml):

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. //Lot's of imports here... see full source
  2.  
  3. public class simpleGoogleMaps extends MapActivity {
  4.   protected boolean isRouteDisplayed() { return false; }
  5.   private MapView myMap;
  6.   private Button btnSearch;
  7.   private EditText adress;
  8.   private Geocoder gc;
  9.   private double lat;
  10.   private double lon;
  11.        
  12.        
  13.   @Override
  14.   public void onCreate(Bundle savedInstanceState) {
  15.     super.onCreate(savedInstanceState);
  16.     setContentView(R.layout.main);
  17.        
  18.     myMap = (MapView) findViewById(R.id.simpleGM_map); //Get map from XML
  19.     btnSearch = (Button) findViewById(R.id.simpleGM_btn_search); //Get button from XML
  20.     adress = (EditText) findViewById(R.id.simpleGM_adress); //Get address from XML
  21.        
  22.     gc = new Geocoder(this); //create new geocoder instance
  23.                
  24.     btnSearch.setOnClickListener(new OnClickListener() {
  25.       public void onClick(View v) {
  26.         String addressInput = adress.getText().toString(); //Get input text
  27.                                
  28.         try {
  29.                                        
  30.           List<Address> foundAdresses = gc.getFromLocationName(addressInput, 5); //Search addresses
  31.                                        
  32.           if (foundAdresses.size() == 0) { //if no address found, display an error
  33.             Dialog locationError = new AlertDialog.Builder(simpleGoogleMaps.this)
  34.               .setIcon(0)
  35.               .setTitle("Error")
  36.               .setPositiveButton(R.string.ok, null)
  37.               .setMessage("Sorry, your address doesn't exist.")
  38.               .create();
  39.             locationError.show();
  40.           }
  41.           else { //else display address on map
  42.             for (int i = 0; i < foundAdresses.size(); ++i) {
  43.               //Save results as Longitude and Latitude
  44.               //@todo: if more than one result, then show a select-list
  45.               Address x = foundAdresses.get(i);
  46.               lat = x.getLatitude();
  47.               lon = x.getLongitude();
  48.             }
  49.           navigateToLocation((lat * 1000000), (lon * 1000000), myMap); //display the found address
  50.           }
  51.         }
  52.         catch (Exception e) {
  53.           //@todo: Show error message
  54.         }
  55.                                
  56.       }
  57.     });
  58.     }
  59.    
  60.   /**
  61.   * Navigates a given MapView to the specified Longitude and Latitude
  62.   */
  63.   public static void navigateToLocation (double latitude, double longitude, MapView mv) {
  64.     GeoPoint p = new GeoPoint((int) latitude, (int) longitude); //new GeoPoint
  65.     mv.displayZoomControls(true); //display Zoom (seems that it doesn't work yet)
  66.     MapController mc = mv.getController();
  67.     mc.animateTo(p); //move map to the given point
  68.     int zoomlevel = mv.getMaxZoomLevel(); //detect maximum zoom level
  69.     mc.setZoom(zoomlevel - 1); //zoom
  70.     mv.setSatellite(false); //display only "normal" mapview    
  71.   }
  72. }
  73.  
Parsed in 0.047 seconds, using GeSHi 1.0.8.4


I hope this demonstrates how easy it is to convert an address in long/lat with GeoCoder.
See the GoogleMaps Mini Tutorial from lordhong if you want to add more features to your application.
But with GeoCoder you mustn't use strange Yahoo-API requests :-)

Thanks to plusminus for his great tutorials. Hope I can give something back with this one.

[Edit:] When you read the APIs you will see that it is recommended to put the getFromLocation() method in an own thread. Read the Simple GoogleMaps with Threads tutorial to see how it works.

Greetings from Germany
Mic
Attachments
simpleGoogleMaps.tar
Full Source Code
(65.5 KiB) Downloaded 3636 times
Last edited by michels on Fri Dec 05, 2008 1:22 am, edited 3 times in total.
michels
Junior Developer
Junior Developer
 
Posts: 17
Joined: Wed Sep 24, 2008 12:37 pm
Location: Germany

Top

Postby plusminus » Wed Sep 24, 2008 4:22 pm

Hey michels,

thank you for contributing to the community and greetings back to Germany (I'm German too).
Nice step-by-step example :!:
-
Best Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby plusminus » Wed Sep 24, 2008 6:07 pm

Btw, as the GeoCoder does a blocking network-query, it should be placed in a Thread, as otherwise the UI will be unavailable until it returns :!:
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby michels » Thu Sep 25, 2008 1:21 pm

plusminus wrote:Btw, as the GeoCoder does a blocking network-query, it should be placed in a Thread, as otherwise the UI will be unavailable until it returns :!:


Hey plusminus,

you're right. I read that too, but I'm not an expert in threads so far :wink: and I thought it's too complicated to explain GeoCoder and threads in one tutorial.

So I wrote a seperate tutorial for threads last night.

Simple GoogleMaps with threads

Hope that I understand everything right.

greetings
Mic
michels
Junior Developer
Junior Developer
 
Posts: 17
Joined: Wed Sep 24, 2008 12:37 pm
Location: Germany

Postby plusminus » Thu Sep 25, 2008 2:25 pm

Yeah thats fine. See my comment over there.

I usually do such thing with
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. runOnUiThread(new Runnable(){
  2.  
  3.     public void run(){
  4.  
  5.         // ...
  6.  
  7.     }
  8.  
  9. }
Parsed in 0.035 seconds, using GeSHi 1.0.8.4

because then I don't have to create a new Handler, create message, handle with what-ids and stuff. So its a bit simpler.

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby ndroid » Wed Dec 17, 2008 12:48 pm

hi
i am getting following exception
" Unable to parse response from server" when i search for London.
here is the snippet
try
{
foundAdresses = gc.getFromLocationName(addressInput, 5); // Search
// addresses
Thread.sleep(1500);
}
catch (Exception e)
{
// @todo: Show error message
Log.i("TEST", "exception in thread " + e.getMessage());
}
even as i observe after first search its sending this exception evry time for any location.
ndroid
Junior Developer
Junior Developer
 
Posts: 15
Joined: Mon Dec 15, 2008 1:29 pm

Top

Re: Simple GoogleMaps (GeoCoder / Convert address to lon/lat

Postby Dhr » Thu Sep 16, 2010 9:15 am

hie michels ,

Thanks very much for this tutorial, Its very much helpful for me.
But whenver I run it shows nothing after clicking on the "GO" button.
I can see only the map, not the exact location.

Please suggest me.

~Dhr
User avatar
Dhr
Junior Developer
Junior Developer
 
Posts: 24
Joined: Thu Aug 19, 2010 11:59 am
Location: Ahd, Gujarat, India

Re: Simple GoogleMaps (GeoCoder / Convert address to lon/lat

Postby poornima_s » Fri Nov 12, 2010 11:54 am

hie michels ,

Thanks for this good tutorial,But whenver I run it shows 'service unavailable'.

Please suggest me.

Poornima S
poornima_s
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Nov 03, 2010 5:44 am

Re: Simple GoogleMaps (GeoCoder / Convert address to lon/lat

Postby sw22 » Fri Nov 26, 2010 12:53 pm

poornima_s wrote:hie michels ,

Thanks for this good tutorial,But whenver I run it shows 'service unavailable'.

Please suggest me.

Poornima S


I found on the Internet that this is an emulator bug, try it on a real device, it might be working. It was my case actually :).
sw22
Freshman
Freshman
 
Posts: 6
Joined: Wed Sep 29, 2010 2:03 pm

Re: Simple GoogleMaps (GeoCoder / Convert address to lon/lat

Postby ksolveson » Tue Nov 30, 2010 11:08 pm

just wanted to say thanks for very helpful tutorial. When using Google Maps API 8, had same "no service" problem as previously posted, but when I reverted to Google Maps API 7, worked fine. (Here's link to website that tipped me off: http://osdir.com/ml/Android-Developers/ ... 00293.html)

Thanks again.
ksolveson
Once Poster
Once Poster
 
Posts: 1
Joined: Tue Nov 30, 2010 11:02 pm

Re: Simple GoogleMaps (GeoCoder / Convert address to lon/lat

Postby Openxcell » Tue Mar 29, 2011 1:09 pm

michels wrote:
GoogleMaps with Geocoder Class


This tutorial is also available in german at my android weblog Androidianer.de

Hey there,

I've written this tutorial, because there were a lot of questions in the android-group and in this forum about the functionality of the Geocoder Class and the possibility to convert an address in the longitude and latitude.
I hope this tutorial can clarify the most problems.

What the application can do:
Convert an entered address in longitude and latitude and display it in a map.

How it looks like:
Image


Here we go:

1. Create a nice layout in the main.xml. I will not explain XML-layouting here, cause there are a lot of good tutorials from plusminus in this forum. Donwload the attached source code to see my main.xml

2. Add the following permissions to the Manifest.xml over the <application> Tag

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  2. <uses-permission android:name="android.permission.INTERNET" />
  3.  
Parsed in 0.001 seconds, using GeSHi 1.0.8.4


3. Have fun with java. It's so easy with GeoCoder class:

All you have to do is:
- Create a new Geocoder instance
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. gc = new Geocoder(this); //create new geocoder instance
  2.  
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


- Write a OnClickListener for the search button (btnSearch) and get the entered address from the EditText-field (address)
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. gc = new Geocoder(this); //create new geocoder instance
  2. btnSearch.setOnClickListener(new OnClickListener() {
  3.   public void onClick(View v) {
  4.     String addressInput = adress.getText().toString(); //Get input text
  5.   }
  6. });
  7.  
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


- Let the GeoCoder class search for the entered address (don't forget the try-catch-statement)
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. gc = new Geocoder(this); //create new geocoder instance
  2. btnSearch.setOnClickListener(new OnClickListener() {
  3.   public void onClick(View v) {
  4.     String addressInput = adress.getText().toString(); //Get input text
  5.     try {
  6.       List<Address> foundAdresses = gc.getFromLocationName(addressInput, 5); //Search addresses
  7.     }
  8.     catch (Exception e) {
  9.       //@todo: Show error message
  10.     }
  11.   }
  12. });
  13.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


- Get the longitude and latitude from the found addresses and display the map (see full source code for the navigateToLocation function)
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. gc = new Geocoder(this); //create new geocoder instance
  2. btnSearch.setOnClickListener(new OnClickListener() {
  3.   public void onClick(View v) {
  4.     String addressInput = adress.getText().toString(); //Get input text
  5.     try {
  6.       List<Address> foundAdresses = gc.getFromLocationName(addressInput, 5); //Search addresses
  7.       for (int i = 0; i < foundAdresses.size(); ++i) {
  8.         //Save results as Longitude and Latitude
  9.         //@todo: if more than one result, then show a select-list
  10.         Address x = foundAdresses.get(i);
  11.         lat = x.getLatitude();
  12.         lon = x.getLongitude();
  13.       }
  14.       navigateToLocation((lat * 1000000), (lon * 1000000), myMap); //display the found address
  15.     }
  16.     catch (Exception e) {
  17.       //@todo: Show error message
  18.     }
  19.   }
  20. });
  21.  
Parsed in 0.039 seconds, using GeSHi 1.0.8.4



Full Source
The full source also displays an error if the address wasn't found (check also the attachment for manifest and main.xml):

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. //Lot's of imports here... see full source
  2.  
  3. public class simpleGoogleMaps extends MapActivity {
  4.   protected boolean isRouteDisplayed() { return false; }
  5.   private MapView myMap;
  6.   private Button btnSearch;
  7.   private EditText adress;
  8.   private Geocoder gc;
  9.   private double lat;
  10.   private double lon;
  11.        
  12.        
  13.   @Override
  14.   public void onCreate(Bundle savedInstanceState) {
  15.     super.onCreate(savedInstanceState);
  16.     setContentView(R.layout.main);
  17.        
  18.     myMap = (MapView) findViewById(R.id.simpleGM_map); //Get map from XML
  19.     btnSearch = (Button) findViewById(R.id.simpleGM_btn_search); //Get button from XML
  20.     adress = (EditText) findViewById(R.id.simpleGM_adress); //Get address from XML
  21.        
  22.     gc = new Geocoder(this); //create new geocoder instance
  23.                
  24.     btnSearch.setOnClickListener(new OnClickListener() {
  25.       public void onClick(View v) {
  26.         String addressInput = adress.getText().toString(); //Get input text
  27.                                
  28.         try {
  29.                                        
  30.           List<Address> foundAdresses = gc.getFromLocationName(addressInput, 5); //Search addresses
  31.                                        
  32.           if (foundAdresses.size() == 0) { //if no address found, display an error
  33.             Dialog locationError = new AlertDialog.Builder(simpleGoogleMaps.this)
  34.               .setIcon(0)
  35.               .setTitle("Error")
  36.               .setPositiveButton(R.string.ok, null)
  37.               .setMessage("Sorry, your address doesn't exist.")
  38.               .create();
  39.             locationError.show();
  40.           }
  41.           else { //else display address on map
  42.             for (int i = 0; i < foundAdresses.size(); ++i) {
  43.               //Save results as Longitude and Latitude
  44.               //@todo: if more than one result, then show a select-list
  45.               Address x = foundAdresses.get(i);
  46.               lat = x.getLatitude();
  47.               lon = x.getLongitude();
  48.             }
  49.           navigateToLocation((lat * 1000000), (lon * 1000000), myMap); //display the found address
  50.           }
  51.         }
  52.         catch (Exception e) {
  53.           //@todo: Show error message
  54.         }
  55.                                
  56.       }
  57.     });
  58.     }
  59.    
  60.   /**
  61.   * Navigates a given MapView to the specified Longitude and Latitude
  62.   */
  63.   public static void navigateToLocation (double latitude, double longitude, MapView mv) {
  64.     GeoPoint p = new GeoPoint((int) latitude, (int) longitude); //new GeoPoint
  65.     mv.displayZoomControls(true); //display Zoom (seems that it doesn't work yet)
  66.     MapController mc = mv.getController();
  67.     mc.animateTo(p); //move map to the given point
  68.     int zoomlevel = mv.getMaxZoomLevel(); //detect maximum zoom level
  69.     mc.setZoom(zoomlevel - 1); //zoom
  70.     mv.setSatellite(false); //display only "normal" mapview    
  71.   }
  72. }
  73.  
Parsed in 0.047 seconds, using GeSHi 1.0.8.4


I hope this demonstrates how easy it is to convert an address in long/lat with GeoCoder.
See the GoogleMaps Mini Tutorial from lordhong if you want to add more features to your application.
But with GeoCoder you mustn't use strange Yahoo-API requests :-)

Thanks to plusminus for his great tutorials. Hope I can give something back with this one.

[Edit:] When you read the APIs you will see that it is recommended to put the getFromLocation() method in an own thread. Read the Simple GoogleMaps with Threads tutorial to see how it works.

Greetings from Germany
Mic


Really an amazing information post. You can understand easily and quickly. Thanks for sharing.
Openxcell
Experienced Developer
Experienced Developer
 
Posts: 79
Joined: Mon Mar 28, 2011 1:59 pm

Re: Simple GoogleMaps (GeoCoder / Convert address to lon/lat

Postby maheshthakuri » Mon Jun 06, 2011 12:02 pm

Anyone can help me. I m getting the error java.io.IOException: unable to parse response from server .
I m also getting my custom error on finding any place like india, london , etc in between.
I tried a lot to fix it but unable to fix it. :(
Attachments
MapDemo.zip
(47.12 KiB) Downloaded 261 times
maheshthakuri
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Jun 06, 2011 9:37 am

Re: Simple GoogleMaps (GeoCoder / Convert address to lon/lat

Postby Skeniver » Fri Oct 07, 2011 10:18 am

Hey everyone

Great tut. Thanks.

I am only getting one search result from the Geocoder's .getFromLocationName("address", 5). I think it is returning results based on my phones locale, but I don't know how to override it.

eg. I live in the UK, and if I search for 'Canterbury', it only returns Canterbury, UK; and not Canterbury, New Zealand.

No matter what I search for (when using search terms that should get multiple results), I only get one.

Anybody know how to get past this?
Follow me on twitter -> http://twitter.com/Skeniver
Apps & blog -> http://www.formidableapps.co.uk
User avatar
Skeniver
Senior Developer
Senior Developer
 
Posts: 106
Joined: Tue Feb 03, 2009 3:51 pm
Location: Canterbury, UK

Re: Simple GoogleMaps (GeoCoder / Convert address to lon/lat

Postby jackandrews7 » Sun Nov 06, 2011 8:56 pm

Thanks for this explanation, Michels. Helped me a lot!
jackandrews7
Freshman
Freshman
 
Posts: 2
Joined: Sun Nov 06, 2011 8:34 pm

Re: Simple GoogleMaps (GeoCoder / Convert address to lon/lat

Postby sephtian » Wed Apr 11, 2012 4:38 am

how can this code run in api 8?
sephtian
Freshman
Freshman
 
Posts: 2
Joined: Fri Apr 06, 2012 7:47 am

Top
Next

Return to Map Tutorials

Who is online

Users browsing this forum: No registered users and 0 guests