Reputation: 45
I have latlng values in String .I want to convert That String into LatLng objects. likeLatLng latlng = new LatLng(lat, lng);
This is my data :
String latlan ="
[[13.041695199971244, 77.61311285197735],
[13.042000923637021, 77.61313531547785],
[13.041830750574812, 77.61335827410221],
[13.041507062142946, 77.61269208043814]]
";
Thanks in advance
Upvotes: 2
Views: 4715
Reputation: 16399
Parse your data as follows:
List<LatLng> coordinates = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(latlan);
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray latLong = jsonArray.getJSONArray(i);
double lat = latLong.getDouble(0);
double lon = latLong.getDouble(1);
coordinates.add(new LatLng(lat, lon));
}
} catch (JSONException e) {
e.printStackTrace();
}
System.err.println(Arrays.toString(coordinates.toArray()));
for (LatLng latLng : coordinates) {
//use the coordinates.
}
Upvotes: 8
Reputation: 508
private void doConvertToLatLan(){
String latlan = "[[13.041695199971244, 77.61311285197735], [13.042000923637021, 77.61313531547785], [13.041830750574812, 77.61335827410221], [13.041507062142946, 77.61269208043814]]";
latlan = latlan.replace("[[","[");
latlan = latlan.replace("]]","]");
latlan = latlan.replace("[","");
latlan = latlan.replace("],","@");
String[] latlanDParts = latlan.split("@");
ArrayList<LatLan> data = new ArrayList<>();
for (String value: latlanDParts) {
String[] llReplacedParts = value.split(",");
data.add(new LatLan(llReplacedParts[0], llReplacedParts[1]));
}
Log.d("Data",data.toString());
}
private class LatLan{
private String lat,lan;
public LatLan(String lat, String lan) {
this.lat = lat;
this.lan = lan;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLan() {
return lan;
}
public void setLan(String lan) {
this.lan = lan;
}
};
I hope this will helpful!
Upvotes: 1
Reputation: 2588
I would just use a bunch of splits and replaceAlls to divide it up and then use the LatLan constructor in a foreach loop.
String latlng = "[[13.041695199971244, 77.61311285197735], [13.042000923637021, 77.61313531547785], [13.041830750574812, 77.61335827410221], [13.041507062142946, 77.61269208043814]]";
String[] latlngParts = latlng.split("\\], \\[");
for (String ll: latlngParts) {
String llReplaced = ll.replaceAll("\\[", "").replaceAll("\\]", "");
String[] llReplacedParts = llReplaced.split(", ");
LatLng latlngObj = new LatLng(llReplacedParts[0], llReplacedParts[1]);
// Then add latlngObj to some collection of LatLng objects
}
Upvotes: 1