I need to convert a String value into a LatLng value for use in a GoogleMaps fragment in an Android app. The string value will likely come in the form of "-45.654765, 65.432892".
I've tried two different ways of doing this, and both have resulted in errors. First, I've tried using split() and putting the results into a String[], then accessing each using parseDouble(), as follows:
String[] geo = GEO.split(",");
double lati = Double.parseDouble(geo[0]);
double lngi = Double.parseDouble(geo[1]);
LOCATION = new LatLng(lati, lngi);
This yields an ArrayIndexOutOfBoundsException caused by double lati = Double.parseDouble(geo[0]);. I'm not really sure why.
I've also tried using StringTokenizer, as follows:
StringTokenizer tokens = new StringTokenizer(GEO, ",");
String lat = tokens.nextToken();
String lng = tokens.nextToken();
double lati = Double.parseDouble(lat);
double lngi = Double.parseDouble(lng);
LOCATION = new LatLng(lati, lngi);
This yields a NoSuchElementException pointing to String lng = tokens.nextToken();.
In both cases, the String I am working on, GEO, is public static final and passed from another activity via intent, where it is currently just hardcoded as "43.75,-70.15".
LOCATION is public static and is a LatLng variable initialized as null.
Can anyone point me in the right direction? This seems really simple so I'm even more confused than usual...
EDIT:
The data originates in a different activity where it is passed via intent. The activity that receives the intent has GEO defined as follows:
public static final String GEO = "geo";
And the intent from the previous activity puts geo in like this:
bundle.putString(PlaceActivity.GEO, geo);
You should have
String loc = getIntent().getExtras().getString(PlaceActivity.GEO);
String[] geo = loc.split(",");
You could just use a very basic substring:
int index = GEO.indexOf(",");
String lat = GEO.substring(0, index).trim();
String lng = GEO.substring(index+1).trim();
double lati = Double.parseDouble(lat);
double lngi = Double.parseDouble(lng);
LOCATION = new LatLng(lati, lngi);
Sorry, untested.
Related
In my app, I am trying to have people mark their locations, and have it brought back through Firebase.
This is my code for grabbing the latLng:
final LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
I then send the string value of latLng to another activity so it gets sent to the databse:
Intent co_intent = new Intent(MapsActivity.this, ServerImage.class);
co_intent.putExtra("pelatlng",String.valueOf(latLng));
MapsActivity.this.startActivity(co_intent);
When I do this, the coordinates gets saved in the Database like this(fake coordinates for obvious reasons):
Markers:
coordinates: "lat/lng:(35.000000,119.0000000)"
I then got the Databse value so I could bring back the coordinates:
mDatabaseMarker=FirebaseDatabase.getInstance().getReference().child("Markers");
Now I am trying to put the saved markers through ChildEventListener like this:
refDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
);
mMap.addMarker(new MarkerOptions()
.position(?)
}
However, I don't know what to put for the marker position.
I could get the value back as a String just fine, but having trouble putting the marker on that location. Thanks for the help.
Initially Split values inside brackets as below:
String example = "lat/lng:(35.000000,119.0000000)";
Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(example);
while(m.find()) {
from_lat_lng = m.group(1) ;
}
Once you have String with lat,lon Split it and parse it to double.
String[] gpsVal = from_lat_lng.split(",");
double lat = Double.parseDouble(gpsVal[0]);
double lon = Double.parseDouble(gpsVal[1]);
After this you can use lat,lon in your marker as below:
Marker a = gMap.addMarker(new MarkerOptions().zIndex(100)
.position(new LatLng(lat,lon))
I have an SQLITE3 database where I defined lat and long as text.
I need to use those lat, and long as the final destination in a map.
The intent is defined as:
if(locationMap != null){
Intent theIntent = new Intent(getApplication(), displayMap.class);
theIntent.putExtra("_Id", locationMap.get("_Id"));
theIntent.putExtra("locCode", locationMap.get("locCode"));
theIntent.putExtra("locDesc", locationMap.get("locDesc"));
theIntent.putExtra("locLat", locationMap.get("locLat"));
theIntent.putExtra("locLong", locationMap.get("locLong"));
theIntent.putExtra("locTelephone", locationMap.get("locTelephone"));
theIntent.putExtra("locComments", locationMap.get("locComments"));
startActivity(theIntent); // display map with coordinates
}
In the next activity I recover the values in the On create method:
// Parameters
String locCode = i.getStringExtra("locCode");
String locDesc = i.getStringExtra("locDesc");
String locLat = i.getStringExtra("locLat");
String locLong = i.getStringExtra("locLong");
String locTelephone = i.getStringExtra("locTelephone");
String locComments = i.getStringExtra("locComments");
String Text = "Current location is: " +
i.getStringExtra("locLat");
Toast.makeText( getApplicationContext(),Text,
Toast.LENGTH_SHORT).show();
System.out.println("locCode: " + locCode);
System.out.println("LocDesc: " + locDesc);
System.out.println("LocLat: " + locLat);
System.out.println("LocLong: " + locLong);
System.out.println("LocTelephone: " + locTelephone);
System.out.println("LocComment: " + locComments);
getLocation(ORIGIN);
setContentView(R.layout.map);
if (mLastSelectedMarker != null && mLastSelectedMarker.isInfoWindowShown()) {
// Refresh the info window when the info window's content has changed.
mLastSelectedMarker.showInfoWindow();
}
setUpMapIfNeeded();
}
I need to use those locLat and Loclong instead of the numbers:
public class displayMap extends FragmentActivity implements
OnMarkerClickListener,
OnInfoWindowClickListener {
public LatLng ORIGIN = new LatLng(34.02143074239393, -117.61349469423294);
public LatLng DESTINY = new LatLng(34.022365269080886, -117.61271852999926);
private GoogleMap mMap;
private Marker mDestiny;
private Marker mOrigin;
private Marker mLastSelectedMarker; // keeps track of last selected marker
I've tried transforming the text to double and It won't allow me to.
I've tried many solutions I found on stack overflow, but no luck yet.
I appreciate any help
Thanks in advance.
You need to parse the latitude and longitude from String to double to use in new LatLng();
double latitude = Double.parseDouble(locLat);
double longitude = Double.parseDouble(locLong);
and then,
public LatLng ORIGIN = new LatLng(latitude, longitude);
you need cast them into double. As GPRathour says.
Change the type of Lat Long Text to REAL in your SQL Lite,
when inserting values use this
values.put(Latitude_Column, ORIGIN.latitude);
values.put(Longitude__Column,ORIGIN.longitude);
And for retrieving values
LatLng origin = new LatLng(cursor.getDouble(cursor.getColumnIndex(Latitude_Column)),cursor.getDouble(cursor.getColumnIndex(Longitude__Column)));
No need to parsing values
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);
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.
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)
am trying to integrate Google Places API into my app.
Now I am finding out my current location of the Phone, how do I embed the longitude and latitude which I have got into the following URL instead of "location=34.0522222,-118.2427778"
"https://maps.googleapis.com/maps/api/place/search/xml?location=34.0522222,-118.2427778&radius=500&types=restaurants&sensor=false&key=Your_API_Key"
Do you mean how do you do string manipulation such as (untested):
int latitude = ...;
int longitude = ...;
String preamble = "https://maps.googleapis.com/maps/api/place/search/xml?location=";
String postamble = "&radius=500&types=restaurants&sensor=true&key=";
String key = "Your_api_key";
String latStr = latitude + "";
String longStr = longitude + "";
String url = preamble + latStr + "," + longStr + postamble + key;
$lat = location[0];
$long = location[1];
Should work, but I use json for geting long and lat from google. Is better. I can check it again if not working.
Here is better json solution:
http://maps.googleapis.com/maps/api/geocode/json?address=Atlantis&sensor=true&oe=utf-8
You should change Atlantis to address
I have a map and I want to be able add in a location from a string and have it add a marker on that location. so far I have some code that that I thought might work but i keep getting errors. I will post the code.
First Activity
LON = (EditText) findViewById (R.id.LON);
LAT = (EditText) findViewById (R.id.LAT);
SL = (Button) findViewById (R.id.SL);
SL.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent intent = new Intent (SetLocation.this,GarageSellerActivity.class);
intent.putExtra("lonstring", LON.getText().toString());
intent.putExtra("latstring", LAT.getText().toString());
startActivity(intent);
}
});
The first activity has no errors and works as far as going to the next activity.
Second Activity
private String LONString;
private String LATString;
//**Turns longitude EditText into a string**\\
LONString = getIntent().getExtras().getString("lonstring", "");
//**Turns latitude EditText into a string.**\\
LATString = getIntent().getExtras().getString("latstring", "");
GeoPoint point1 = new GeoPoint(LONString,+LATString);
OverlayItem overlayitem1 = new OverlayItem(point1, "Sekai, konichiwa!", "I'm in Japan!");
itemizedoverlay1.addOverlay(overlayitem1);
mapOverlays2.add(itemizedoverlay1);'
I have errors on both .getString and on LONString and LATString inside the geopoints. Any help is appreciated.
-Thanks
You need to pass Longitude and Latitude as Integers, not Strings. Just convert them when you pass them to GeoPoint. Like this:
GeoPoint point1 = new GeoPoint(Integer.parseInt(LONString), Integer.parseInt(LATString));
You might want to do some filtering in your input as well to make sure they're not passing anything nasty.