【问题标题】:Incompatible types using LatLng Google Maps使用 LatLng Google Maps 的不兼容类型
【发布时间】:2026-02-24 14:20:07
【问题描述】:

第一次制作安卓应用程序,并试图将谷歌方向的折线添加到谷歌地图上。

已进口: com.google.android.gms.maps.model.LatLng

我想解码折线点。 尝试使用 PolylineEncoding 类中的decode,但这从以下位置导入: com.google.maps.model.LatLng

这会导致类型不兼容,那么如何确保使用兼容的类型?或者在不重写算法的情况下将此折线解码为特定 LatLng 类型的其他方法?

【问题讨论】:

  • 你想从一个地方到另一个地方的路线
  • @SSALPHAX 呀!我试图弄清楚我应该为此使用什么。现在使用 PolyUtil 解码它所以 n

标签: java android google-maps android-studio


【解决方案1】:

尝试在 drawPath() 方法中传递你的结果

 public void drawPath(String result) {
    if (line != null) {
        googleMap.clear();
    }
    googleMap.addMarker(new MarkerOptions().position(Dloca));
    //googleMap.addMarker(new MarkerOptions().position(loc));
    try {
        // Tranform the string into a json object
        final JSONObject json = new JSONObject(result);
        JSONArray routeArray = json.getJSONArray("routes");
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes
                .getJSONObject("overview_polyline");
        String encodedString = overviewPolylines.getString("points");
        List<LatLng> list = decodePoly(encodedString);

        for (int z = 0; z < list.size() - 1; z++) {
            LatLng src = list.get(z);
            LatLng dest = list.get(z + 1);
            line = googleMap.addPolyline(new PolylineOptions()
                    .add(new LatLng(src.latitude, src.longitude),
                            new LatLng(dest.latitude, dest.longitude))
                    .width(5).color(Color.BLUE).geodesic(true));
        }

        dialog.dismiss();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }

    return poly;
}

此代码将根据您的路线来源和目的地位置在谷歌地图中返回您的线路。

【讨论】:

  • 所以我想避免重写这个方法,因为它是地图 api 的一部分。我认为我的问题并不清楚,但我最初的问题是理解为什么 google 包使用不同的 LatLng 类型。最后我使用了类似的东西:import com.google.maps.android.PolyUtil import com.google.android.gms.maps.model.LatLng ... List&lt;LatLng&gt; directions = PolyUtil.decode(polylineString); PolylineOptions p = new PolylineOptions(); p.addAll(directions); googleMap.addPolyline(p); ...
最近更新 更多