Reputation: 150
I have multiple location coordinates in a file. It is stored in a JSON
Format. I am reading them and trying to draw using the for loop
.
These is the sample code given on the developer website
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);
I am trying as below:-
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());
}
}
How can I draw polyline with multiple coordinates?
Upvotes: 0
Views: 3868
Reputation: 462
Declare map instance as global variable, define drawLine
method as below:
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);
}
Upvotes: 3