首页 > 解决方案 > 如何从字符串值中获取纬度?

问题描述

位置值是从我们的服务器获取的,现在我以字符串格式定义新位置,之后我想获取经度和纬度,但它是 0.0。代码是这样的。

String location = "lat\/lng: (28.6988812,77.1153696)";
Location loc = new Location(location);
double lat = loc.getLatitude();
double longitude = loc.getLongitude();

标签: androidlocation

解决方案


您可以使用正则表达式从服务器获得的位置字符串中提取纬度和经度。像这样:

Double latitude = 0., longitude = 0.;

    //your location
    String location = "lat/long: (28.6988812,77.1153696)";
    //pattern
    Pattern pattern = Pattern.compile("lat/long: \\(([0-9.]+),([0-9.]+)\\)$");
    Matcher matcher = pattern.matcher(location);
    if (matcher.matches()) {
        latitude = Double.valueOf(matcher.group(1));
        longitude = Double.valueOf(matcher.group(2));
    }

如果你需要一个 Location 对象:

Location targetLocation = new Location("");//provider name is unnecessary
targetLocation.setLatitude(latitude);//your coords of course
targetLocation.setLongitude(longitude);

感谢这个答案


推荐阅读