如何在Google地图中为多个纬度和经度坐标绘制折线。我需要动态地绘制至少20组纬度和经度的折线。
答案 0 :(得分:5)
来自Android documentation的示例:
GoogleMap map;
// ... get a map.
// Add a thin red line from London to New York.
Polyline line = map.addPolyline(new PolylineOptions()
.add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
.width(5)
.color(Color.RED));
只需根据需要多次拨打.add
。
答案 1 :(得分:5)
使用折线和arraylist
在地图中添加多个点ArrayList<LatLng> coordList = new ArrayList<LatLng>();
// Adding points to ArrayList
coordList.add(new LatLng(0, 0);
coordList.add(new LatLng(1, 1);
coordList.add(new LatLng(2, 2);
// etc...
// Find map fragment. This line work only with support library
GoogleMap gMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
PolylineOptions polylineOptions = new PolylineOptions();
// Create polyline options with existing LatLng ArrayList
polylineOptions.addAll(coordList);
polylineOptions
.width(5)
.color(Color.RED);
// Adding multiple points in map using polyline and arraylist
gMap.addPolyline(polylineOptions);
答案 2 :(得分:2)
只需创建一个函数来检索JSON折线:
private ArrayList<LatLng> getPolylines(String jsonStr) {
// file exists, it is the first boot
if (jsonStr != null) {
// linea init
LatLng polyline;
// array list of lines init
ArrayList<LatLng> polylines = new ArrayList<LatLng>();
// get json array
JSONArray jsonArray = JSON.getJSONArray(jsonStr, "polytag");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonPolyline;
try {
jsonPolyline = jsonArray.getJSONObject(i);
polyline = new LatLng(Double.valueOf(jsonPolyline.getString("lat")),
Double.valueOf(jsonPolyline.getString("lon")));
polylines.add(polyline);
} catch (JSONException e) {
Log.d(TAG, "JSONException reading polylines: " + e.getMessage());
} catch (Exception e) {
Log.d(TAG, "Exception reading polylines: " + e.getMessage());
}
}
return polylines;
}
return null;
}
然后获取此ArrayList并以这种方式填充它:
ArrayList<LatLng> polylines = getPolylines(linesJsonStr);
map.addPolyline(new PolylineOptions().addAll(polylines).width(2.0f).color(Color.RED));
希望它有所帮助!
答案 3 :(得分:0)
您可以遍历点数组,并为每个坐标将新的LatLng添加到折线选项,然后在循环之后将折线选项添加到折线。
val from = LatLng(it.data[0].lat, it.data[0].lng)
val to = LatLng(it.data.last().lat, it.data.last().lng)
map.addMarker(MarkerOptions().position(from).title("pickup location"))
map.addMarker(MarkerOptions().position(to).title("destination location"))
map.animateCamera(CameraUpdateFactory.newLatLngZoom(from, 13f))
var polylineOptions = PolylineOptions()
for (i in it.data){
polylineOptions.add(LatLng(i.lat, i.lng))
}
polylineOptions.width(5f).color(Color.RED)
map.addPolyline(
polylineOptions
)