andbook!.pdf - Learning Android Get an anddev.org - Android-Shirt Back to index
anddev.org Header Logo
FAQ Search Top rated articles Browse Feeds anddev.org - Authors Contact Details Register Log in

GoogleMaps Mini

Goto page 1, 2  Next
 
       anddev.org - Android Development Community | Android Tutorials | Index -> Map Tutorials
Author Message
lordhong
Developer
Developer


Joined: 22 Nov 2007
Posts: 41
Location: New York

PostPosted: Tue Dec 11, 2007 2:20 pm    Post subject: GoogleMaps Mini Reply with quote

GoogleMaps Mini


Question What is this: Basically it's a small map application that you can enter an address and lookup map in street/satellite/traffic views, including zoom in/out functions. the addresses are stored in db and utilize the auto-complete to show your historical inputs. Geocode translation is done through Yahoo Geo API.

Source codes are included and GPLV2, anyway, feel free to grab it and any comment/question please let me know.

Question Problems/Questions: post right below...

Difficulty: 3 of 5 Smile

What it will look like:





Description:
First, I modified the DBHelper from Notepad tutorial 1 to use for storing the address/location history.
Nothing fancy here, just need to make a few changes to accommodate the location stuff:

Java:
private static final String DATABASE_CREATE =
        "create table addresses (rowid integer primary key autoincrement, "
            + "address text not null, latitude integer, longitude integer);";


I also need to be able to look up by location (String), so the fetchRow query is modified a bit:

Java:
Cursor c =
            db.query(false, DATABASE_TABLE, new String[] {
                "rowid", "address", "latitude", "longitude"}, "address='" + address+"'", null, null,
                null, null);


You can see the single quote ' used in the criteria field, and yes, you do need single quotes around your value for String/Text fields. Crying or Very sad I thought maybe android api is smart enough to figure out the data type and surround it w/ single quotes if needed... Rolling Eyes apparently not yet Laughing Laughing Laughing

Then for the 5 buttons on the toolbar, I pretty much referenced from Steven Osborn's Undroid project at: http://code.google.com/p/undroid/w/list
Many thanks to Steven's great contribution, along with Tango icons, it looks really nice, at least for someone lack basic graphical design sense, such as me... Embarassed

To translate the location to geocode, I use Yahoo geo API for that, the code is really simple:

Java:
public class YahooGeoAPI {

     private static final String LOGGER = "lordhong.yahoo";
     private static final String APPID = "your yahoo app id goes here";
     private static final String YAHOO_GEO_API_URL = "http://local.yahooapis.com/MapsService/V1/geocode?appid=";
     private static HttpConnectionManager connectionManager = new SimpleHttpConnectionManager();
     
     public static String getGeoCode(String location) throws IOException {
          StringBuffer url = new StringBuffer(YAHOO_GEO_API_URL);
          url.append(APPID).append("&location=").append(location.replaceAll(" ", "+"));
         
          Log.i(LOGGER, "yahoo geo request: " + url.toString());
          HttpURL httpURL = new HttpURL(url.toString());
          HostConfiguration host = new HostConfiguration();
          host.setHost(httpURL.getHost(), httpURL.getPort());
          HttpConnection connection = connectionManager.getConnection(host);
          connection.open();
          GetMethod get = new GetMethod(url.toString());
          get.execute(new HttpState(), connection);
          String response = get.getResponseBodyAsString();
          Log.i(LOGGER, "yahoo geo response: " + response);
          connection.close();
          return response;
     }
}


This returns the Yahoo geo api XML response as String. I don't have any error-handling here for invalid location, multiple locations, etc. I just assume it works... Embarassed

Then I build the XML SAX parsing part by referenced from Davanum Srinivas' LocateMe at: http://davanum.wordpress.com/2007/11/30/android-poor-mans-my-location-show-current-cell-location/

So I created a YahooGeocodeHandler to do just that:

Java:
public class YahooGeocodeHandler extends DefaultHandler



Finally, from what I learned HERE AT ANDDEV.org, I put together this mini google map layout:

XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >


     <AutoCompleteTextView id="@+id/address"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="@string/search_term"
          android:completionThreshold="1"
          android:selectAllOnFocus="true" />

     
     <view id="@+id/mapview"
          class="com.google.android.maps.MapView"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:layout_weight="1" />

         
     <view class="lordhong.apps.ToolBar$ToolBarView"
          id="@+id/toolbar"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"/>


</LinearLayout>



In the main mini app class, I have some basic stuff/variables, and adapter for the address/location:
Java:
public class MiniGMap extends MapActivity {
     
     private static MapView mapview;
     private static AutoCompleteTextView address;
     private DBHelper dbHelper;
     private ArrayList<String> addresses;
     private static final String LOGGER = "lordhong.miniGmap";



In the onCreate() method, all the views are init.ed, key events are registered, db is init.ed, and historical addresses are populated:

Java:
public void onCreate(Bundle icicle) {
     super.onCreate(icicle);
     
     requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
       
        ToolBar.setup(this);
        mapview = (MapView)findViewById(R.id.mapview);
        address = (AutoCompleteTextView)findViewById(R.id.address);
        address.setKeyListener(new OnKeyListener() {

               public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode==KeyEvent.KEYCODE_DPAD_CENTER) {
                         // get value from address auto-complete
                         String addr = address.getText().toString();
                         Log.i(LOGGER, "addr: " + addr);
                         // get lat. and long. from db
                         DBHelper.AddressRow row = dbHelper.fetchRow(addr);
                         if (row.rowId!=-1) {
                              // navigate to geo location
                              navigateToGeoCode(row.latitude, row.longitude);
                         } else {
                              // address not found, maybe a new address?
                              try {
                                   String yahooGeoResponse = YahooGeoAPI.getGeoCode(addr);
                                   YahooGeocodeHandler handler = new YahooGeocodeHandler();
                                   try {
                                   Xml.parse(yahooGeoResponse, handler);
                               } catch (SAXException e) {
                                   Log.e(LOGGER, e.toString(), e);
                               }
                               Log.i(LOGGER, "latitude: " + handler.getLatitude());
                               Log.i(LOGGER, "Longitude: " + handler.getLongitude());
                               if (handler.getLatitudeAsLong()!=-1 && handler.getLongitudeAsLong()!=-1) {
                                   dbHelper.createRow(addr, handler.getLatitudeAsLong(), handler.getLongitudeAsLong());
                                   navigateToGeoCode(handler.getLatitudeAsLong(), handler.getLongitudeAsLong());
                                   // re-populate the addresses, including the new address
                                   populateAddresses();
                               }
                              } catch (Exception e) {
                                   Log.e(LOGGER, "addr error from yahoo geo lookup: " + addr, e);
                              }
                             
                              //Log.i("lordhong.miniGmap", "NOT FOUND!: " + addr);
                         }
                    }
                    return false;
               }
         
        });
        dbHelper = new DBHelper(this);
        populateAddresses();
    }



Then I provide some static methods for map operations:

Java:
public static void zoomIn() {
     mapview.getController().zoomTo(mapview.getZoomLevel() + 1);
    }
   
    public static void zoomOut() {
     mapview.getController().zoomTo(mapview.getZoomLevel() - 1);
    }
   
    public static void satellite() {
     mapview.toggleSatellite();
    }
   
    public static void traffic() {
     mapview.toggleTraffic();
    }
   
    public static void enterAddress() {
     address.requestFocus();
     address.setSelectAllOnFocus(true);
    }

private void navigateToGeoCode(long latitude, long longitude) {
     Log.i(LOGGER, latitude+"--"+longitude);
     Point p = new Point((int)latitude, (int)longitude);
          MapController mc = mapview.getController();
          mc.animateTo(p);
          mc.zoomTo(21);
    }


Here's the populate address method:

Java:
public void populateAddresses() {
     addresses = new ArrayList<String>();
     
     List<AddressRow> rows = dbHelper.fetchAllRows();
     for (AddressRow row : rows) {
          addresses.add(row.address);
     }
     
     ArrayAdapter<String> addressAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, addresses);
     address.setAdapter(addressAdapter);
    }



Shocked Shocked this completes my first tutorial... please forgive my writing as I'm having a pretty bad cold right now Embarassed any question, please reply in this thread.

Again, many thanks to Steven, Davanum, and plusminus for their great contributions, and last but not the least, our anddev.org forum, THE BEST ANDROID FORUM!!!

/me drinking vick's... Rolling Eyes



MiniGMap0.9.1.rar
 Description:

Download
 Filename:  MiniGMap0.9.1.rar
 Filesize:  21.81 KB
 Downloaded:  945 Time(s)

Back to top
View user's profile Send private message
piyush
Freshman
Freshman


Joined: 10 Dec 2007
Posts: 2

PostPosted: Tue Dec 11, 2007 2:26 pm    Post subject: Reply with quote

Hi...
i have execute apllication [MiniGMap0.9.1] but unable to find MAP Question on screen..
how u getting map with ur amppliaction.

Thanks in advance.
Piyush
Back to top
View user's profile Send private message Send e-mail
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Tue Dec 11, 2007 2:29 pm    Post subject: Reply with quote

Hello piyush,

I accidentally deleted this topic Embarassed Embarassed Embarassed
could restore posts, but lost the zip-source, can you append it to your post please Question Exclamation Question


Does your Application show NOTHING or pretty soft gridlines Question

Best Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
lordhong
Developer
Developer


Joined: 22 Nov 2007
Posts: 41
Location: New York

PostPosted: Tue Dec 11, 2007 4:09 pm    Post subject: Reply with quote

Shocked i will attach the source later... need to find it somewhere, dont have my laptop w/ me...

as for the map, sometimes the initial map shows nothing/grid, you can drag the map a bit to force it to render...
does this answer your question?

Thanks,
Back to top
View user's profile Send private message
lordhong
Developer
Developer


Joined: 22 Nov 2007
Posts: 41
Location: New York

PostPosted: Tue Dec 11, 2007 5:37 pm    Post subject: SOURCE!!! Reply with quote

Embarassed here's the source zip... Wink


MiniGMap0.9.1.rar
 Description:
:)

Download
 Filename:  MiniGMap0.9.1.rar
 Filesize:  21.81 KB
 Downloaded:  528 Time(s)

Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Wed Dec 12, 2007 5:44 pm    Post subject: Reply with quote

Thanks lord Wink
_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
kosirm
Freshman
Freshman


Joined: 01 Dec 2007
Posts: 3

PostPosted: Thu Dec 13, 2007 3:17 pm    Post subject: great tutorial, thanks! Reply with quote

great tutorial, thanks!
Back to top
View user's profile Send private message
johnny
Freshman
Freshman


Joined: 27 Nov 2007
Posts: 3

PostPosted: Sun Dec 23, 2007 4:43 pm    Post subject: Icons Reply with quote

I know that +- wrote it in his frist reply on the undeleted post:

Which is the iconset you are using for your App? i would like to use it too.

Thank you
Back to top
View user's profile Send private message
lordhong
Developer
Developer


Joined: 22 Nov 2007
Posts: 41
Location: New York

PostPosted: Sun Dec 23, 2007 7:26 pm    Post subject: Reply with quote

Very Happy Tango Icons!
http://tango.freedesktop.org/Tango_Icon_Gallery
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Sun Dec 23, 2007 7:33 pm    Post subject: Reply with quote

Hey johnny,

nice memory Very Happy
I assumed it was the Tango Icon Library and I was right Smile .

[Edit]
damn i was to slow Wink

Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
johnny
Freshman
Freshman


Joined: 27 Nov 2007
Posts: 3

PostPosted: Mon Dec 24, 2007 3:43 am    Post subject: Reply with quote

Nice memory would've been, if i could have remembered the icontheme Wink

Thank you for the quick response.

MERRY CHRISTMAS!!!!
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Mon Dec 24, 2007 2:43 pm    Post subject: Reply with quote

Rolling Eyes You at least remembered where you read it ^^
My memory is less good Razz

Merry Christmas,
plusminus Xmas-Smile

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
lujasone
Freshman
Freshman


Joined: 14 Feb 2008
Posts: 3

PostPosted: Wed Feb 20, 2008 7:34 am    Post subject: Fail to launch miniGMap Reply with quote

I meet error when I try to launch miniGMap as follows:
Application Error: lordhong.apps

An error has occurred in lordhong.apps. Unable to start activity ComponentInfo{lordhong.apps/lordhong.apps.miniGMap}:java.lang.NullPointerException.

Can anyone help to figure out the reason ? Thanks,

-Jason Lu
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2660
Location: College Park, MD

PostPosted: Wed Feb 20, 2008 10:27 am    Post subject: Reply with quote

Hello Jason,

are you using SDK-Version m5 Question

You'll have to make some adaptions, because lordhong made this code on SDK-Version m3.

On upgrading issues, have a look at these posts:
Arrow Right http://www.anddev.org/viewtopic.php?t=879
Arrow Right http://www.anddev.org/viewtopic.php?t=881

Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
lujasone
Freshman
Freshman


Joined: 14 Feb 2008
Posts: 3

PostPosted: Thu Feb 21, 2008 3:47 am    Post subject: It works now ! Reply with quote

It works now with some suggestion from plusminus. (m3->m5). Very Happy

plusminus, Thanks for your help !!

-Jason
Back to top
View user's profile Send private message
Display posts from previous:   
       anddev.org - Android Development Community | Android Tutorials | Index -> Map Tutorials All times are GMT + 1 Hour
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


© 2007, Android Development Community
All rights reserved.
Powered by phpBB.