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)
Related
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
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.
I'm developing an Android app which is using Google Places API.
Once I get all the places result, I want to sort it according to the algorithm.
Which is, the places result will only being put into the Hash Map if the algorithm is >= 0.
But the problem now is, when I run it, the algorithm result in the for loop did not change during the looping.
My algorithm is:
balance = user_hour-visi-duration.
balance = 240-60-20 = 160
Let's say the balance is 160, it will remain 160 until the for loop ended.
I wanted each time of the looping, the value of balance will decreased untill negative value.
FYI, balance variable is not a local variable.
Does anybody know how to solve this?
Here is the part of the code.
// loop through each place
for (Place p : nearPlaces.results) {
balance = user_hour - duration - visit;
HashMap<String, String> map = new HashMap<String, String>();
//////////////////////////////////////////////////////////////////
googlePlaces = new GooglePlaces();
try {
placeDetails = googlePlaces.getPlaceDetails(p.reference);
} catch (Exception e) {
e.printStackTrace();
}
if(placeDetails != null){
String statuss = placeDetails.status;
// check place deatils status
// Check for all possible status
if(statuss.equals("OK")){
lat = gps.getLatitude();
lang = gps.getLongitude();
double endlat = placeDetails.result.geometry.location.lat;
double endlong = placeDetails.result.geometry.location.lng;
Location locationA = new Location("point A");
locationA.setLatitude(lat);
locationA.setLongitude(lang);
Location locationB = new Location("point B");
locationB.setLatitude(endlat);
locationB.setLongitude(endlong);
double distance = locationA.distanceTo(locationB)/1000;
Double dist = distance;
Integer dist2 = dist.intValue();
//p.distance = String.valueOf(dist2);
p.distance = String.valueOf(balance);
dist3 = p.distance;
}
else if(status.equals("ZERO_RESULTS")){
alert.showAlertDialog(MainActivity.this, "Near Places",
"Sorry no place found.",
false);
}
}
///////////////////////////////////////////////////////////////
if (balance > 0){
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
map.put(KEY_DISTANCE, p.distance);
// adding HashMap to ArrayList
placesListItems.add(map);
}
else {
//
}
}//end for loop
What exactly are you trying to do here?
You have balance = user_hour - duration - visit; on the first line after your for loop. I cannot see where user_hour, duration or visit is declared, but I'm assuming it's outside the loop. This means it will always be the same value for each Place in nearPlaces.results. If this code is genuinely how you want it, you might as well declare it before the loop as you are pointlessly re-calculating it for every Place.
You also never do anything with balance except to print it out or set another value to it, so it's tricky to work out what you're expecting to happen.
I'm getting latitude and longitude as strings from a Google Places URL. Now I'd like to place a pin on a map using the obtained coordinates. Something is goofy because I'm trying to parse the strings into integers for the GeoPoint, and the results show as 0,0 so the pin is placed off the coast of Africa. Here's my code:
int lati5Int, longi5Int;
String latiString = in.getStringExtra(TAG_GEOMETRY_LOCATION_LAT);
String longiString = in.getStringExtra(TAG_GEOMETRY_LOCATION_LNG);
TextView getLatiStringtv.setText(latiString);
TextView getLongiStringtv.setText(longiString);
try {
lati5Int = Integer.parseInt(getLatiStringtv.getText().toString());
longi5Int = Integer.parseInt(getLongiStringtv.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
// shows that the ints are zeros
doubleLatiTV.setText(Integer.toString(lati5Int));
doubleLongiTV.setText(Integer.toString(longi5Int));
//--- GeoPoint---
newPoint = new GeoPoint(lati5Int,longi5Int);
mapController.animateTo(newPoint);
mapController.setZoom(17);
//--- Place pin ----
marker = getResources().getDrawable(R.drawable.malls);
OverlayItem overlaypoint = new OverlayItem(newPoint, "Boing", "Whattsup");
CustomPinpoint customPin = new CustomPinpoint(marker, SMIMap.this);
customPin.insertPinpoint(overlaypoint);
overlayList.add(customPin);
I think the error is in the parsing of the integers:
lati5Int = Integer.parseInt(getLatiStringtv.getText().toString());
longi5Int = Integer.parseInt(getLongiStringtv.getText().toString());
I think the parsing sees the decimal point in the coordinates and freaks out. So how can I parse the coordinate strings into integers so that the GeoPoint will see them as correctly formatted coordinates like: 30.487263, -97.970799
GeoPoint doesn't want to see them as 30.487263, -97.970799. It wants them as the integers 30487263, -97970799. So like A.A said, parse as double first, multiply by E6, then cast to int.
So maybe something like:
lati5Int = Double.parseDouble(getLatiStringtv.getText().toString());
latiE6 = (int) (lati5Int*1000000);
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