You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android集成Google Map:如何消除无用的直线路径?

Google Map无用直线路径无法消除的原因分析

问题描述

当前Google Map中出现无用的直线路径,需求是完全消除这些直线,仅保留标记点。数据通过Rest API获取,期望输出仅包含标记点的地图。

相关代码

onMapReady(@NonNull GoogleMap map) {
        googleMap = map;
        googleMap.getUiSettings().setMapToolbarEnabled(false);
        googleMap.getUiSettings().setZoomControlsEnabled(false);

        routePoints = new ArrayList<>();
        noRoutePoints = new ArrayList<>();

        String idTappaSelezionata = MainActivity.idUltimaTappaSelezionata;

        if (idTappaSelezionata != null) {
            mapView.setVisibility(View.GONE);

            StringRequest getPercorsoRequest = new StringRequest(Request.Method.POST, Config.GET_PERCORSO_URL,
                    response -> {
                        Logger.show("Mappa getData response: " + response + " | Url: " + Config.GET_PERCORSO_URL);

                        try {
                            JSONObject responseObject = new JSONObject(response);
                            JSONArray percorsoArray = responseObject.getJSONArray("percorso");

                            if (percorsoArray.length() == 0) {
                                clearRoutes();
                            } else {
                                parseAndDisplayRoute(percorsoArray);
                            }

                            mapView.setVisibility(View.VISIBLE);
                        } catch (JSONException e) {
                            // handle exception
                        }
                    },
                    error -> {
                        // handle error
                    }) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<>();
                    params.put("user_id", MainActivity.userLoggedId);
                    params.put("id_tappa", idTappaSelezionata);
                    params.put("id_via", MainActivity.idUltimaViaSelezionata);
                    return params;
                }
            };

            SingletonVolley.getInstance(getActivity()).addToRequestQueue(getPercorsoRequest);
        } else {
            showNoRouteDialog();
        }
    }

    private void clearRoutes() {
        getActivity().runOnUiThread(() -> {
            routePoints.clear();
            noRoutePoints.clear();
        });
    }

    private void parseAndDisplayRoute(JSONArray percorsoArray) throws JSONException {
        for (int i = 0; i < percorsoArray.length(); i++) {
            Gson gson = new Gson();
            String tmpPercorso = percorsoArray.getJSONObject(i).toString();
            Percorso newP = gson.fromJson(tmpPercorso, Percorso.class);

            if ("rosso".equals(newP.getColore())) {
                routePoints.add(new LatLng(newP.getLatitude(), newP.getLongitude()));
            } else if ("blu".equals(newP.getColore())) {
                noRoutePoints.add(new LatLng(newP.getLatitude(), newP.getLongitude()));
            }
        }

        getActivity().runOnUiThread(() -> {
            if (!routePoints.isEmpty()) {
                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(routePoints.get(0), 14));
            }

            if (routePoints.size() > 1 && noRoutePoints.size() > 1) {
                addPolylines();
            }

            addMarker();
            setPolylineClickListener();
        });
    }

    private void addPolylines() {
        List<LatLng> percorso = PolyUtil.simplify(routePoints, 0.0001); // Adjusted tolerance

        PolylineOptions percorsoPolyline = new PolylineOptions()
                .addAll(percorso)
                .clickable(true)
                .width(10)
                .color(Color.RED);

        googleMap.addPolyline(percorsoPolyline);

       // List<LatLng> simplifiedNoRoute = PolyUtil.simplify(noRoutePoints, 0.0001); // Adjusted tolerance

        /*PolylineOptions polylineOptionsRosso = new PolylineOptions()
                .addAll(simplifiedRoute)
                .clickable(true)
                .width(10)
                .color(Color.RED);

        googleMap.addPolyline(polylineOptionsRosso);

        PolylineOptions polylineOptionsBlu = new PolylineOptions()
                .addAll(simplifiedNoRoute)
                .clickable(true)
                .width(10)
                .color(Color.BLUE);

        googleMap.addPolyline(polylineOptionsBlu);*/



        getExperiences(googleMap);
    }

    private void addMarker() {
        LatLng markerMe = routePoints.get(0);
        int customMarkerHeight = 100;
        int customMarkerWidth = 100;
        BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.me);
        Bitmap customMarkerBitmap = Bitmap.createScaledBitmap(bitmapDrawable.getBitmap(), customMarkerWidth, customMarkerHeight, false);
        BitmapDescriptor customMarkerMe = BitmapDescriptorFactory.fromBitmap(customMarkerBitmap);

        MarkerOptions markerOp = new MarkerOptions()
                .position(markerMe)
                .icon(customMarkerMe)
                .title("Marker " + getId());

        googleMap.addMarker(markerOp);
    }

    private void setPolylineClickListener() {
        googleMap.setOnPolylineClickListener(polyline -> {
            List<LatLng> path = polyline.getPoints();
            String navigationUri = "http://maps.google.com/maps?daddr=" + path.get(path.size() - 1).latitude + "," + path.get(path.size() - 1).longitude;
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(navigationUri));
            intent.setPackage("com.google.android.apps.maps");
            startActivity(intent);
        });
    }

    private void showNoRouteDialog() {
        mapView.setVisibility(View.GONE);

        String message = "Non è stato selezionato nessun percorso. Premere OK per scegliere un percorso.";
        androidx.appcompat.app.AlertDialog.Builder dialog = new androidx.appcompat.app.AlertDialog.Builder(getActivity());
        dialog.setTitle("Le Vie di Francesco");
        dialog.setMessage(message);

        dialog.setPositiveButton("OK", (dialogInterface, i) -> {
            ((MainActivity) getActivity()).caricaFragment("menu_home", new Vie(), "Vie");
        });
        dialog.setCancelable(false);
        dialog.show();
    }

问题根源

代码里的直线路径是主动添加的,问题出在以下两处:

  1. parseAndDisplayRoute方法中,当routePoints.size() > 1 && noRoutePoints.size() > 1时,会调用addPolylines方法;
  2. addPolylines方法里明确执行了googleMap.addPolyline(percorsoPolyline),这段代码就是在地图上绘制红色直线路径的逻辑,完全符合你看到的无用直线特征。

解决方案

要完全消除直线路径,只需要移除绘制折线的相关代码:

  1. 在parseAndDisplayRoute的UI线程代码块中,删除调用addPolylines()的逻辑,同时删除setPolylineClickListener()的调用(因为不需要折线点击事件了);
  2. 可以直接删除addPolylines和setPolylineClickListener方法,避免冗余代码。

修改后的parseAndDisplayRoute关键代码片段:

getActivity().runOnUiThread(() -> {
    if (!routePoints.isEmpty()) {
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(routePoints.get(0), 14));
    }

    // 移除addPolylines()调用
    addMarker();
    // 移除setPolylineClickListener()调用
});

内容的提问来源于stack exchange,提问作者Lucifer85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 12:24:56