Android - 谷歌地图 - 如何在地图上显示多个标记?

时间:2016-07-25 08:21:56

标签: android google-maps

我想在Google地图上显示多个标记(可能是100个或更多)。我正在从 sqlite 中读取 lat lng 然后我将它们添加到谷歌地图上,但只显示一个标记

我是否必须使用主题 AsyncTask

这是我的代码:

public class StartActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    public SQLiteDatabase sql;
    public Cursor cursor;
    Context context;
    public static String PACKAGE_NAME;
    ArrayList<LatLng> markerPoints;
    LatLng newLatLng;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        context = getApplicationContext();
        DBS db = new DBS(context);
        PACKAGE_NAME = context.getApplicationContext().getPackageName();
        db.GetPackageName(PACKAGE_NAME);
        db.CreateFile();
        try {
            db.CreateandOpenDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
        sql = db.openDataBase();

        try {
            cursor = sql.rawQuery("SELECT _Lat,_Lng,_Date,_Time FROM Places where UserCode = 101", null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    do {
                        markerPoints = new ArrayList<LatLng>();
                        Structure_DB sdb = new Structure_DB();
                        sdb._Lat = cursor.getString(cursor.getColumnIndex("_Lat"));
                        sdb._Lng = cursor.getString(cursor.getColumnIndex("_Lng"));
                        sdb._Date = cursor.getString(cursor.getColumnIndex("_Date"));
                        sdb._Time = cursor.getString(cursor.getColumnIndex("_Time"));
                        newLatLng = new LatLng(Double.parseDouble(sdb._Lat), Double.parseDouble(sdb._Lng));
                        markerPoints.add(newLatLng);
                    } while (cursor.moveToNext());
                }
            }
        } catch (Exception e) {
        } finally {
            cursor.close();
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        Iterator<LatLng> iterator = markerPoints.iterator();
        while (iterator.hasNext()) {
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(iterator.next());
            mMap.addMarker(markerOptions);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您正在每次迭代初始化markerPoints

从do-while循环中删除markerPoints = new ArrayList<LatLng>();并在声明ArrayList<LatLng> markerPoints = new ArrayList<LatLng>();

上初始化它