如何将String值转换为LatLng()对象?

时间:2017-10-03 13:04:32

标签: java android google-maps

我在String中有latlng值。我想将该String转换为LatLng对象。像LatLng latlng = new LatLng(lat, lng);

这是我的数据:

String latlan =" 
    [[13.041695199971244, 77.61311285197735], 
    [13.042000923637021, 77.61313531547785], 
    [13.041830750574812, 77.61335827410221], 
    [13.041507062142946, 77.61269208043814]]
";

提前致谢

4 个答案:

答案 0 :(得分:5)

按如下方式解析数据:

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.
}

答案 1 :(得分:0)

我只是使用一堆splits和replaceAlls来分割它,然后在foreach循环中使用LatLan构造函数。

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
}

答案 2 :(得分:0)

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;
        }
    };

我希望这会有所帮助!

答案 3 :(得分:0)

如果只有一个值,它将起作用。

LatLng newlatlng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));