Passing current location ( longitude and latitude ) in the Google Places API - android

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

Related

I have two latlong values. one for source and other for destination..In which format latlong value should pass to find distance between them

DIRECTION_URL_API = "https://maps.googleapis.com/maps/api/directions/json?"
DIRECTION_URL_API + "origin=" + origin + "&destination=" + destination + "&sensor=true" + "&mode=" +typeOpt+"&key=" + GOOGLE_API_KEY ;
I am using this format but its not working
Please suggest me :)
You can find distance following way
http://maps.googleapis.com/maps/api/directions/json?origin=21.1702,72.8311&destination=21.7051,72.9959&sensor=false&units=metric&mode=driving
origin=lat1,long1
destination=lat2,long2
Please use the below method to calculate the distance between two points
/**
* Returns Distance in kilometers (km)
*/
public static String distance(double startLat, double startLong, double endLat, double endLong) {
Location startPoint = new Location("locationA");
startPoint.setLatitude(startLat);
startPoint.setLongitude(startLong);
Location endPoint = new Location("locationA");
endPoint.setLatitude(endLat);
endPoint.setLongitude(endLong);
return String.format("%.2f", startPoint.distanceTo(endPoint) / 1000); //KMs
}
Method usage -
String mDistance = distance(startLat,
startLong,
endLat,endLng)).concat("km");

How to use Latitud and Longitud as a variable in Android?

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

Android: Google Maps - draw path between multiple points

What I want to do is this:
I receive a list of directions/paths (that the user will have to follow using my app).
I am having trouble drawing the path on the map. The directions/paths contains the name of the streets, the coordinates of the streets and the segments of the streets.
I cant figure out how to draw the path/route on the map and make the route update - for example when the user moves (on the way) an icon to move indicating the progress of the user or the line drawn for the route gets shorter this really doesn't matter that much. So can you point me to tutorials which I can refer to?
I've seen a lot so far, but most of them get the directions from Google maps or the lines drawn are just straight lines from Start point to end point and doesn't fit the streets at all.
To achieve this, follow the below steps
Get list of ArrayList markerPoints;
Create your markers for it
single path,
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
for multiple destination path, for example A-B-D-C etc
private List<String> getDirectionsUrl(ArrayList<LatLng> markerPoints) {
List<String> mUrls = new ArrayList<>();
if (markerPoints.size() > 1) {
String str_origin = markerPoints.get(0).latitude + "," + markerPoints.get(0).longitude;
String str_dest = markerPoints.get(1).latitude + "," + markerPoints.get(1).longitude;
String sensor = "sensor=false";
String parameters = "origin=" + str_origin + "&destination=" + str_dest + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
mUrls.add(url);
for (int i = 2; i < markerPoints.size(); i++)//loop starts from 2 because 0 and 1 are already printed
{
str_origin = str_dest;
str_dest = markerPoints.get(i).latitude + "," + markerPoints.get(i).longitude;
parameters = "origin=" + str_origin + "&destination=" + str_dest + "&" + sensor;
url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
mUrls.add(url);
}
}
return mUrls;
}
Call the above method from
List<String> urls = getDirectionsUrl(markerPoints);
if (urls.size() > 1) {
for (int i = 0; i < urls.size(); i++) {
String url = urls.get(i);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
}
the above code will call for to create multiple paths, like A-B, B-D, D-C etc
try following this tutorial. You should draw between user location and marker. On user side call function onLocationChange to get the actual position and redraw the line. http://wptrafficanalyzer.in/blog/driving-route-from-my-location-to-destination-in-google-maps-android-api-v2/
Follow this:Android Google Map V3 PolyLine cannot be drawn
It'll help.
You just need to parse the data received after hitting Google Directions API

Converting String to Double for use in LatLng/Google Maps

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.

how can we match two strings in android?

I trying to match hardcoded latitude an longitude with dynamic latitude and longitude, but its not showing correct output, can anyone help me to sort out this error
My code is
String Log = "-122.084095";
String Lat = "37.422005";
try {
if ((Lat.equals(latitude)) && (Log.equals(longitude))) {
AudioManager audiM = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audiM.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(getApplicationContext(),
"You are at home",
Toast.LENGTH_LONG).show();
} else {
AudioManager auMa = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
auMa.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(getApplicationContext(),
"You are at office ", Toast.LENGTH_LONG)
.show();
}
} catch (Exception e) {
e.printStackTrace();
}
it always goes for else part...
You don't want to use a String comparison here as you can't guarantee the level of accuracy with the real-time location.
The best way to handle this would be to determine the distance between the points and then determine if it's close enough for you to consider, approx, the same.
For this, we use distanceBetween or distanceTo
Docs are here and here
Examples can be found here. Here's one of those examples:
Location locationA = new Location("point A");
locationA.setLatitude(pointA.getLatitudeE6() / 1E6);
locationA.setLongitude(pointA.getLongitudeE6() / 1E6);
Location locationB = new Location("point B");
locationB.setLatitude(pointB.getLatitudeE6() / 1E6);
locationB.setLongitude(pointB.getLongitudeE6() / 1E6);
double distance = locationA.distanceTo(locationB);
The latitude and longitude are variables which vary from point to point, matter of fact they keep on changing while standing on the same spot, because it is not precise.
Instead of comparing the Strings, take a rounded value of the lat and long (in long or float ) and check those values within a certain range. That will help you out with the "Home" and "Office " thing.
For e.g :
String Log = "22.084095";
String Lat = "37.422005";
double lng=Double.parseDouble(Log);
double lat=Double.parseDouble(Lat);
double upprLogHome=22.1;
double lwrLogHome=21.9;
double upprLatHome=37.5;
double lwrLatHome=37.3;
// double upprLogOfc=;
// double lwrLogOfc=;
// double upprLatOfc=;
// double lwrLatOfc=;
if(lng<upprLogHome && lng>lwrLogHome && lat<upprLatHome &&lat>lwrLatHome )
{
System.out.println("You are Home");
}
/* else if(lng<upprLogOfc && lng>lwrLogOfc && lat<upprLatOfc &&lat>lwrLatOfc )
{
System.out.println("You are Home");
}*/
else
System.out.println("You are neither Home nor Ofc");
But for the negative lat long you have to reverse the process of checking.
your matching is okay but you probably should not check for a gps location like this.
You should convert the location to something where you can check that you are in 10m radius of the location.
A nicer way would be to leave the long/lat as doubles and compare the numbers.
if(lat > HOME_LAT - 0.1 && lat < HOME_LAT + 0.1 && ...same for lon... ){}
Try this,
Use google map api to pass lat and long value you will get formatted address. And also pass dynamic lat and lng value same google api you will get formatted address. And then match two formatted address you will get result. i suggest this way you can try this
Use this google api. http://maps.googleapis.com/maps/api/geocode/json?latlng=11.029494,76.954422&sensor=true
Reena, its very easy, Check out below code. You need to use "equalsIgnoreCase()" instead of
"equals".
if ((Lat.equalsIgnoreCase(latitude)) && (Log.equalsIgnoreCase(longitude))) {
should work
Example below :
// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}
You can print dynamice Latitute and Longitute to Logcat and check with hardcoded Latitute and Longitute

Categories

Resources