【问题标题】:Get Latitude and Longitude from SQLite database for use in Android MapOverlay从 SQLite 数据库获取纬度和经度以用于 Android MapOverlay
【发布时间】:2013-09-11 03:52:09
【问题描述】:

如果我将一堆位置的纬度和经度存储在 SQLite 数据库中,我将如何检索这些值并将它们分别放置在 OverlayItem 类中以便在 Google 的地图代码中使用?

数据库名称:database

表名:place

place 表中的字段:

  • id
  • title
  • description
  • latitude
  • longitude

如何获取每个位置的经纬度数据并将其添加到ArrayList itemOverlay?

你有什么想法或例子吗?非常感谢你

【问题讨论】:

    标签: android database sqlite android-maps mapactivity


    【解决方案1】:

    你会想要做这样的查询:

    SELECT title, description, latitude, longitude
    FROM place
    

    这可以像这样在 Android 中完成:

        /* 
           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());
    

    您需要将这些值乘以 1E6,因为 Android 使用整数表示纬度/经度值。如果您在填充数据库时已经考虑到这一点,请跳过乘法并使用locationCursor.getInt(...)

    【讨论】:

    • 一种可能稍微更有效的方法是将Cursor交给ItemizedOverlay并让它实现size()(从Cursor返回getCount())和getItem()(在moveToPosition() 调用之后从Cursor 返回创建OverlayItem 的结果)。这样可以节省您自己的ArrayList。但是您的方法也可以,如果Cursor 可能在地图仍在使用时关闭,这一点尤其重要。
    • 我同意马克。我曾讨论过发布该代码,但即使从数据库中获取数据,用户似乎也迷失了方向,因此这个通用代码似乎是一个更好的选择。一旦他们弄清楚我在这里做了什么,他们应该能够将代码重构为getItem()。你也对,如果你有静态数据,发布的代码会更好,在这种情况下没有理由保持开放的Cursor
    • 非常感谢。它运作良好。但是我在地图上没有得到我想要的确切点……我不知道为什么。引脚移动到下一个城市,彼此之间的距离延长 2 或 3 倍 这是我存储在我的数据库类型中的示例字符串纬度 = 18.481941 经度 = 98.551844 ...我想念哪个?无论如何,非常感谢您的帮助
    • 对不起,愚蠢的问题..我已经知道原因..我输入了错误的纬度和经度:b
    • @April 你完成了这种类型的演示然后给我我也需要你。
    猜你喜欢
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    相关资源
    最近更新 更多