【问题标题】:Update position of a marker without adding a new one更新标记的位置而不添加新标记
【发布时间】:2014-07-14 13:01:51
【问题描述】:

如何在不添加新标记的情况下更新我在 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));
            }

【问题讨论】:

  • 在 onLocationChanged() 中尝试map.clear();
  • map.clear() 将清除比我想要的更多。我以前试过这个,只是让应用程序崩溃。我只是不知道为什么不删除该点,因为正在调用该方法。

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


【解决方案1】:

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

例如:

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

【讨论】:

  • 好的,但如果你仔细看,我会删除旧的。
  • @WitaloBenicio 你有没有在你的问题中提到过这个东西,你为什么要删除并再次添加?
  • 这是因为我试图只通过 setPosition() 更新位置并且它正在创建一个新的点。
【解决方案2】:

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

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

System.out.println(eu);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-30
    • 2021-08-31
    • 2019-08-29
    • 2022-01-06
    • 2012-01-28
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多