更新标记的位置而不添加新标记

时间:2014-07-14 13:01:51

标签: android google-maps-android-api-2 marker

如何在Android中的Google Maps v2中更新我的标记位置而不添加新标记? 每当我的位置发生变化时,我都必须在谷歌地图中更新用户的位置,但它总是在地图上创建一个新点,如何避免这种行为?

以下是我如何更新

public void onLocationChanged(Location location) {
    this.localizacao = location;
    loc = location;
    if (mAdapter.getCount() == 0){
        getAdvsFromServer();
    }

    LatLng me = new LatLng(location.getLatitude(), location.getLongitude());

    if (eu != null){
        Log.d("marker_eu", "removed");
        eu.remove();
    }
    eu = map.addMarker(new MarkerOptions().position(me).title("Eu"));
    Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_maps_indicator_current_position);
    eu.setIcon(BitmapDescriptorFactory.fromBitmap(bm));
    map.moveCamera(CameraUpdateFactory.newLatLng(me));
    //map.moveCamera(CameraUpdateFactory.newLatLngZoom(me, 13));
}

更新: 这样它总是创造一个新点:

        public void onLocationChanged(Location location) {
            this.localizacao = location;
            loc = location;
            if (mAdapter.getCount() == 0){
                getAdvsFromServer();
            }

            if (ac != null){
                ac.setLayoutLocalizacaoVisible(View.GONE, View.VISIBLE);
            }

            LatLng me = new LatLng(location.getLatitude(), location.getLongitude());

//          if (eu != null){
//              Log.d("marker_eu", "removed");
//              eu.remove();
//          }

            if (eu == null){
                eu = map.addMarker(new MarkerOptions().position(me).title("Eu"));
                Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_maps_indicator_current_position);
                eu.setIcon(BitmapDescriptorFactory.fromBitmap(bm));
                map.moveCamera(CameraUpdateFactory.newLatLngZoom(me, 13));
            }else {
                eu.setPosition(me);
                map.moveCamera(CameraUpdateFactory.newLatLng(me));
            }

2 个答案:

答案 0 :(得分:2)

每次更改位置时都不应添加新标记,而是可以直接将新位置设置为现有标记。

例如:

marker.setPosition(new LatLng(lat, lng));

答案 1 :(得分:0)

如果您的活动在运行此方法时正在创建新标记,则eu以某种方式被清除或null进入if语句。 eu.setPosition(me);不会创建另一个标记,只需更改标记的位置而不更改任何其他属性。

如果您确定新标记未在代码中的其他位置创建,请在进入if语句之前检查eu的状态,并通过回溯找出该标记为空的原因。检查标记的位置以在执行后验证位置。使用以下内容并观看logcat。

System.out.println(eu);