如何从字符串值中获取纬度?
How to get Latitude from string value?
Location 值是从我们的服务器获取的,采用字符串格式,现在我定义了新的位置,之后我想获取经度和纬度,但它是 0.0。
代码是这样的
String location = "lat\/lng: (28.6988812,77.1153696)";
Location loc = new Location(location);
double lat = loc.getLatitude();
double longitude = loc.getLongitude();
根据 Android 文档,您需要在构造函数中传递位置提供程序。
参考 https://developer.android.com/reference/android/location/Location.html#Location(java.lang.String)
您需要解析从您的服务器获取的字符串 ("lat/lng: (28.6988812,77.1153696)"),提取纬度和经度并使用 setLatitude() 和 setLongitude() 函数将这些值传递给您的位置对象。
您可以使用正则表达式从从服务器获得的位置字符串中提取纬度和经度。像这样:
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 targetLocation = new Location("");//provider name is unnecessary
targetLocation.setLatitude(latitude);//your coords of course
targetLocation.setLongitude(longitude);
多亏了这个answer
Location 值是从我们的服务器获取的,采用字符串格式,现在我定义了新的位置,之后我想获取经度和纬度,但它是 0.0。 代码是这样的
String location = "lat\/lng: (28.6988812,77.1153696)";
Location loc = new Location(location);
double lat = loc.getLatitude();
double longitude = loc.getLongitude();
根据 Android 文档,您需要在构造函数中传递位置提供程序。 参考 https://developer.android.com/reference/android/location/Location.html#Location(java.lang.String)
您需要解析从您的服务器获取的字符串 ("lat/lng: (28.6988812,77.1153696)"),提取纬度和经度并使用 setLatitude() 和 setLongitude() 函数将这些值传递给您的位置对象。
您可以使用正则表达式从从服务器获得的位置字符串中提取纬度和经度。像这样:
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 targetLocation = new Location("");//provider name is unnecessary
targetLocation.setLatitude(latitude);//your coords of course
targetLocation.setLongitude(longitude);
多亏了这个answer