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);
Related
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)
Problem : My remote server returns 10 multiple value for a request.i parsed my response and using for loop i added markers(here i added info to title and snippet) on a map.(here i want to add extra data to marker so that i can access it in on info window click event)
in infoWindowClickListener i want to access that extra data.
How to add extra data to marker/ how to access ph data for a particular marker click(other wise i will get last value of ph in all markers).
i tried like this.
private class HttpGetTask extends AsyncTask<Void, Void, String>
{
//URL and http stuff
}
#Override
protected void onPostExecute(String result) {
try {
json = new JSONArray(result);
for (int i = 0; i < json.length(); i++) {
Log.v("Response", result);
final JSONObject e = json.getJSONObject(i);
String point = e.getString("point");
Log.v("POINT", point);//Checking points
String phone1 = e.getString("ph");
Log.v("PH", phone1);//Checking phone numbers
String[] point2 = point.split(",");//Splitting points
double lat1 = Double.parseDouble(point2[0]);
double lng1 = Double.parseDouble(point2[1]);
Log.v("LLDN", "" + lat1 + "&" + lng1);
//Adding multiple markers
//can i add extra information here along with title and snippet
gMap.addMarker(new MarkerOptions()
.title(e.getString("name"))
.snippet(
e.getString("LS")+""+e.getString("ph") )
.position(new LatLng(lng1, lat1))
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.pmr)));
}
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
is it possible to attach extra value to a marker, along with title and snippet.?
or am i parsing in wrong way.?
While #worawee.s's will work perfectly fine, there is a more elegant solution that can allow you to add additional informations to a Marker object. So to solve this, you can use Marker's setTag (Object tag) method:
You can use this property to associate an arbitrary Object with this marker. For example, the Object can contain data about what the marker represents. This is easier than storing a separate Map. As another example, you can associate a String ID corresponding to the ID from a data set.
Not the best solution but this what I do in my application.
create markersMap as a private field in your activity/fragment.
private Map<Marker, ExtraDataObj> markersMap = new HashMap<Marker, ExtraDataObj>();
When you generate marker also put the marker and extra data in your markersMap
ExtraDataObj extraDataObj = new ExtraDataObj();
// extract and store all data you want in the extraDataObj
....
...
..
Marker marker = gMap.addMarker(new MarkerOptions()
.title(e.getString("name"))
.snippet(
e.getString("LS")+""+e.getString("ph") )
.position(new LatLng(lng1, lat1))
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.pmr)));
markersMap.put(marker, extraDataObj);
in your onInfoWindowClick get extra data from the markersMap
ExtraDataObj extraDataObj = markersMap.get(arg0)
I have a huge list in an XML tag like so:
<coor> -123.3858,41.34119,0
-123.3856,41.34109,0
-123.3852,41.34121,0
-123.3848,41.34139,0</coor>
and need it like this:
new LatLng(-123.3858,41.34119),
new LatLng(-123.3856,41.34109),
new LatLng(-123.3852,41.34121),
new LatLng(-123.3848,41.34139),
to work with google maps v2 android.
I've done a string replace on the coordinates and am getting the correct results like so:
String ll = "),new LatLng(";
coor = coor.replaceAll(",0", ll);
replacing the ,0 for the new LatLng(... I am not figuring out how to change the large string of latlng text into latlng locations to put into my polygon:
PolygonOptions perimeteres = new PolygonOptions().add(coor);
Is there way to do this? Or do I need to separate each out and make them individual latlng?
EDIT::::
String[] splitData = coor.split(",0");
for (String eachSplit : splitData) {
if (!eachSplit.endsWith(",0")) {
//Log.e("EACH",eachSplit);
Log.v("e","new LatLon("+eachSplit+");");
}
}
This is getting me a little closer...
You are going completely in the wrong direction, this
String ll = "),new LatLng(";
coor = coor.replaceAll(",0", ll);
is not the same as
new LatLng(-123.3858,41.34119)
the first gives you a string which does nothing for you, the second is an object which is what you need.
Edit
you need to remove the 0 from the coordinates then you do a string split on the , so you have an array of latitudes and longitudes.
then create a List<LatLng> which is what you need to create a polygon of points
and loop through your points
for(int j=0;j<locationAry.length;j++){
if(j%2 == 0){
lon = Float.parseFloat(locationAry[j+1]);
lat = Float.parseFloat(locationAry[j]);
}
}
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.
My Problem is I have 4 Location's Latitude and Longitude into my local database, I am fetching those data and use for draw route path in android but problem is first to second location route is not display on mapview other second to third and third to fourth route path is display on mapview. Sorry for bad English communication.
i am getting code from following link for draw route path.
MapRoute Example
and call drawing class using following function:-
public void drawpath(){
mDb.open();
Cursor cr = mDb.getAllTitles();
cr.moveToFirst();
if (cr.getCount() > 0) {
for (int i = 0; i <= cr.getCount()/2; i++) {
fromlat = Double.parseDouble(cr.getString(1));
fromlng = Double.parseDouble(cr.getString(2));
cr.moveToNext();
tolat = Double.parseDouble(cr.getString(1));
tolng = Double.parseDouble(cr.getString(2));
String url = RoadProvider
.getUrl(fromlat, fromlng, tolat, tolng);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
}
cr.close();
mDb.close();
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345"));
startActivity(intent);
It is happening because you are using cr.getCount()/2.
When you will have even number of count then it will work not work fine
For example if you have 4 number of rows then you cr.getCount()/2 = 2
so your loop will continue from 0 to 2 means 3 times.
Actually it should be continue 2 times as your coding.
Now lat take a odd numbers say 5 so cr.getCount()/2 = 2 because i is the integer value so your loop will work total 3 times.
So you have different mechanism.
Like try to add all the lat and long in the arraylist and then after loop complete.
Make a loop of the size of that arrayList and create a path.May be for that you required two additional variable to store the previous lat and long.