Reputation: 33
If I am retrieving a string variable of something like this (34872.1297,41551.7292), so it would be "(34872.1297,41551.7292)", how do I convert this string variable to Point(Geolocation) ?
For example, this sets the point value, but I want the values to be retrieved
Point point = new Point(34872.1297,41551.7292);
Upvotes: 0
Views: 1121
Reputation: 1222
An issue with storing the geo coordinates as a Point object is that Point actually requires the two values to be of integer type. So you would lose information.
So you could extract and type cast the coordinates to be integers (but lose information):
String geo = "(34872.1297,41551.7292)";
// REMOVE BRACKETS, AND WHITE SPACES
geo = geo.replace(")", "");
geo = geo.replace("(", "");
geo = geo.replace(" ", "");
// SEPARATE THE LONGITUDE AND LATITUDE
String[] split = geo.split(",");
// ASSIGN LONGITUDE AND LATITUDE TO POINT AS INTEGERS
Point point = new Point((int) split[0], (int) split[1]);
Alternatively, you could extract them as floats, and store them in some other data type off your choice.
String geo = "(34872.1297,41551.7292)";
// REMOVE BRACKETS, AND WHITE SPACES
geo = geo.replace(")", "");
geo = geo.replace("(", "");
geo = geo.replace(" ", "");
// SEPARATE THE LONGITUDE AND LATITUDE
String[] split = geo.split(",");
// ASSIGN LONGITUDE AND LATITUDE TO POINT AS INTEGERS
Float long = (float) split[0];
Float lat = (float) split[1];
EDITED: changed geo.split(":") to geo.split(",") in the code () (Thanks Jitesh)
Upvotes: 1
Reputation: 1426
What you are looking for is how to split a string, and there are a few excellent examples on SO for you to peruse.
In your case, this will work:
String yourString = "(34872.1297,41551.7292)";
// Strip out parentheses and split the string on ","
String[] items = yourString.replaceAll("[()]", "").split("\\s*,\\s*"));
// Now you have a String[] (items) with the values "34872.1297" and "41551.7292"
// Get the x and y values as Floats
Float x = Float.parseFloat(items[0]);
Float y = Float.parseFloat(items[1]);
// Do with them what you like (I think you mean LatLng instead of Point)
LatLng latLng = new LatLng(x, y);
Add checks for null values and parse exceptions etc.
Upvotes: 1