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.068 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.072 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.081 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.166 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.113 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 1488 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: 2696
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: 2696
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.083 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: 2696
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

Return to Map Tutorials

Who is online

Users browsing this forum: Yahoo [Bot] and 1 guest