androiddatabasesqliteandroid-mapsmapactivity

Get Latitude and Longitude from SQLite database for use in Android MapOverlay


If I store the Latitude and Longitude of a bunch of locations in a SQLite Database, how would I retrieve these values and place them each in an OverlayItem class for use in Google's Map code?

Database name: database

Table name: place

Fields in place Table:

How do I get the latitude and longitude data of each location and add it to an ArrayList itemOverlay?

Do you have any ideas or an example? Thanks you so much


Solution

  • You would want to do a query like this:

    SELECT title, description, latitude, longitude
    FROM place
    

    Which can be done in Android like this:

        /* 
           databaseObject = YourDbHelper#getReadableDatabase();
        */
        ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
        Cursor locationCursor = databaseObject.query("place", new String[]{
                "title", "description", "latitude", "longitude"}, null, null,
                null, null, null);
    
        locationCursor.moveToFirst();
    
        do {
            String title = locationCursor.String(locationCursor
                    .getColumnIndex("title"));
            String description = locationCursor.String(locationCursor
                    .getColumnIndex("description"));
            int latitude = (int) (locationCursor.getDouble(locationCursor
                    .getColumnIndex("latitude")) * 1E6);
            int longitude = (int) (locationCursor.getDouble(locationCursor
                    .getColumnIndex("longitude")) * 1E6);
    
            items.add(new OverlayItem(new GeoPoint(latitude, longitude), title,
                    description));
        } while (locationCursor.moveToNext());
    

    You need to multiply the values by 1E6 because Android uses an integer representation of the lat/long values. If you already took care of this when populating the database, skip the multiplication and use locationCursor.getInt(...).