【问题标题】:Drawing Polylines using multiple coordinates in Android Google Maps API在 Android Google Maps API 中使用多个坐标绘制折线
【发布时间】:2016-10-19 17:42:13
【问题描述】:

我在一个文件中有多个位置坐标。它以JSON 格式存储。我正在阅读它们并尝试使用for loop 进行绘制。

这些是开发者网站上给出的示例代码

PolylineOptions rectOptions = new PolylineOptions()
    .add(new LatLng(37.35, -122.0))
    .add(new LatLng(37.45, -122.0))  // North of the previous point, but at the same longitude
    .add(new LatLng(37.45, -122.2))  // Same latitude, and 30km to the west
    .add(new LatLng(37.35, -122.2))  // Same longitude, and 16km to the south
    .add(new LatLng(37.35, -122.0)); // Closes the polyline.

// Get back the mutable Polyline
Polyline polyline = myMap.addPolyline(rectOptions);

我正在尝试如下:-

        for(int i =0; i<contentAsJsonObject.size(); i++)
        {
            JSONObject json = contentAsJsonObject.get(i);
            try {

                    final String lat = json.getString("Lat");
                    final String lng = json.getString("Lng");

                if(i == 0)
                {

                    mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng))).title("Starting Point"));

                }

                String s = String.valueOf(i);
                mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng))).title("Location Point "+ s));
                mMap.addPolyline(new PolylineOptions().add(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng))).color(Color.BLUE).width(5));
                msg.Log(lat + lng);

            }catch (JSONException e)
            {
                msg.Log(e.toString());
            }

        }

如何绘制具有多个坐标的折线?

【问题讨论】:

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


    【解决方案1】:

    声明地图实例为全局变量,定义drawLine方法如下:

    public List<LatLng> routeArray = new ArrayList<LatLng>();
    
    for(int i =0; i<contentAsJsonObject.size(); i++) {
      JSONObject json = contentAsJsonObject.get(i);
      try {
        final String lat = json.getString("Lat");
        final String lng = json.getString("Lng");
        LatLng latLng = new LatLng(Double.parseDouble(lat.trim()),Double.parseDouble(lng.trim()));
        if (!routeArray.contains(latLng)){
           routeArray.add(lat);
        }
      } catch (Exception e) {
        e.printStackTrace();
        return;
      }
    }
    drawLine(routeArray);
    
    
    public void drawLine(List<LatLng> points) {
      if (points == null) {
        Log.e("Draw Line", "got null as parameters");
        return;
      }
    
      Polyline line = map.addPolyline(new PolylineOptions().width(3).color(Color.RED));
      line.setPoints(points);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 2014-03-09
      相关资源
      最近更新 更多