【问题标题】:Allow only a certain number of markers in google maps在谷歌地图中只允许一定数量的标记
【发布时间】:2016-03-10 11:25:34
【问题描述】:

我正在使用 google maps (android studio),并试图限制单个用户可以固定的标记数量。我在网上找不到任何示例,唯一能找到的就是删除当前标记(下面的代码)。

我的目标是只允许用户固定 3 个标记。

     mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

        @Override
        public void onMapLongClick(LatLng arg0) {
            //if there is a marker already this if condition removes it
            if (marker != null) {
                marker.remove();
            }
            marker = mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_02))
                    .position(
                            new LatLng(arg0.latitude,
                                    arg0.longitude))
                    .draggable(true).visible(true));
        }
    });

【问题讨论】:

  • 地图有getScreenMarkers之类的方法吗?或者您可以将添加的所有标记存储在列表中。
  • 没有像 getScreenMarkers 这样的方法,我会将所有标记存储在列表中。 Shwet 的回答对我有用。

标签: java android google-maps android-studio google-maps-markers


【解决方案1】:
    int marker_count=0;   
     mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

                @Override
                public void onMapLongClick(LatLng arg0) {
                    if(marker_count<3){
    //if there is a marker already this if condition removes it

                   if (marker != null) {
                        marker.remove();
marker_count=marker_count-1;
                    }
marker_count=marker_count+1;
                    marker = mMap.addMarker(new MarkerOptions()
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_02))
                            .position(
                                    new LatLng(arg0.latitude,
                                            arg0.longitude))
                            .draggable(true).visible(true));
                }}
    else{
    //toast a message
    }
            });

【讨论】:

  • 感谢您的快速回复。这行得通。对其进行了一些编辑以禁用添加第四个标记而不是删除。
【解决方案2】:

稍微编辑了 Shvet 的 code。固定 3 个标记后,用户无法固定第四个,他会收到一条快速消息。

int markerCount = 0; //marker counter

mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

    @Override
    public void onMapLongClick(LatLng arg0) {
        if (markerCount < 3) {
            markerCount = markerCount+ 1;
            marker = mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
                    .position(new LatLng(arg0.latitude, arg0.longitude))
                    .draggable(true)
                    .visible(true));
        } else {
            Toast.makeText(getApplicationContext(), "Only 3 markers allowed!",
                    Toast.LENGTH_LONG).show();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-05-16
    • 1970-01-01
    • 2012-09-22
    • 2021-01-23
    • 1970-01-01
    • 2018-01-23
    • 2015-09-17
    • 2013-04-20
    • 2015-05-30
    相关资源
    最近更新 更多