Open map at specific coordinates not working on Android - android

I'm building an application with the functionality of sending specific pre-determined (but dynamic) coordinates to the user's map app so he can trace a route to it.
Currently, I'm using:
String coordinates = String.format("geo:0,0?q=" + latitude + "," + longitude);
Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse(coordinates) );
startActivity( intent );
However, when it does open the map, instead of the requested location I get a "no results for [latitude], [longitude]" toast and my current location instead.
It's certainly not an issue with the coordinates themselves as manually searching for them work just fine and printing the request Uri show that it's correctly constructed. Surprisingly, only sending the first two digits of both coords sort of works and, while doesn't send me where I want to, does not give the toast error message.
Do I need to do any extra formatting when passing the values or some other thing?
I'm using them raw, -23.561261 and -46.681212 for example, am located in Brazil if that makes any difference and, yes, I do have to send the coordinates as sadly the data is inconsistent with the formatting of the actual addresses.
UPDATE: As it turns out, the code is fine, it works on my razr-i, however, in the Galaxy Express I used for the original tests, it's still a no go.
Any idea of what is going on? Both devices are running Android 4.1.2

Don't quite remember what the error was since it's been so long ago, but long story short, here's the working code:
String coordinates = "http://maps.google.com/maps?daddr=" + latitude + "," + longitude;
Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse(coordinates) );
startActivity( intent );

Your code is correct,
the values that you send are double?
double latitude = -23.561261;
double longitude = -46.681212;
String coordinates = String.format("geo:0,0?q=" + latitude + "," + longitude);
Intent intentMap = new Intent( Intent.ACTION_VIEW, Uri.parse(coordinates) );
startActivity( intentMap );
must be something similar to load directly in your browser the url:
http://www.google.com/maps?q=-23.561261+-46.681212

The problem is in locale. Your code will work on any phone if you call format() like this:
String coordinates = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);

Related

Create a circuit route by passing waypoints to GoogleMaps android

I am working on functionality where I send waypoints to Gmapsapp through Intent so that use can navigate to the destination by the custom waypoints that I send
I when I plot this route in my embedded Google Maps , I can see Circuit route , but when I see the same route in Gmapsapp , the Circuit is broken.
My code :
String srcAdd = "saddr="+latLngArrayList.get(0).latitude+","+latLngArrayList.get(0).longitude;
String desAdd = "&daddr="+latLngArrayList.get(latLngArrayList.size() - 1).latitude+","+latLngArrayList.get(latLngArrayList.size() - 1).longitude;
String wayPoints = "";
for (int j = 1; j < latLngArrayList.size() - 1; ++j) {
wayPoints =wayPoints+"+to:"+latLngArrayList.get(j).latitude+","+latLngArrayList.get(j).longitude;
}
String link="https://maps.google.com/maps?"+srcAdd+desAdd+wayPoints;
final Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(link));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
circuit route
no circuit route
I would suggest having a look at Google Maps URLs API that was launched in May 2017. This API provides universal cross-platform links that you can use in your applications to launch intents for Google Maps. One of the supported modes is directions mode. You can read about it here.
As you use Directions API and posted sample coordinates of waypoints, I was able to test the results in web service and in Google Maps URLs.
The web service results are tested in Directions calculator tool:
https://directionsdebug.firebaseapp.com/?origin=19.07598304748535%2C72.87765502929688&destination=19.07598304748535%2C72.87765502929688&waypoints=18.7284%2C73.4815%7C18.6876%2C73.4827%7C18.5839587%2C73.5125092%7C18.5369444%2C73.4861111%7C18.480567%2C73.491658
The route that we get via Directions API is the following:
The Google Maps URLs link for these waypoints is the following:
https://www.google.com/maps/dir/?api=1&origin=19.07598304748535,72.87765502929688&destination=19.07598304748535,72.87765502929688&waypoints=18.7284,73.4815%7C18.6876,73.4827%7C18.5839587,73.5125092%7C18.5369444,73.4861111%7C18.480567,73.491658&travelmode=driving
The route that you get using Google Maps URLs is shown in this screenshot.
As you can see both routes are the same, so Directions API and Google Maps URLs work as expected. I believe you should change your code for intents to use Google Maps URLs:
String srcAdd = "&origin=" + latLngArrayList.get(0).latitude + "," + latLngArrayList.get(0).longitude;
String desAdd = "&destination=" + latLngArrayList.get(latLngArrayList.size() - 1).latitude + "," + latLngArrayList.get(latLngArrayList.size() - 1).longitude;
String wayPoints = "";
for (int j = 1; j < latLngArrayList.size() - 1; j++) {
wayPoints = wayPoints + (wayPoints.equals("") ? "" : "%7C") + latLngArrayList.get(j).latitude + "," + latLngArrayList.get(j).longitude;
}
wayPoints = "&waypoints=" + wayPoints;
String link="https://www.google.com/maps/dir/?api=1&travelmode=driving"+srcAdd+desAdd+wayPoints;
final Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(link));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
In addition you can use dir_action=navigate parameter in order to open turn-by-turn navigation directly.

Google map direction intent with multiple location on route and starting point as current location, android

I want to start Google map intent for direction with current location as starting position, one location as entry position and other location as destination.
After googling for this, following is the closest query I came with
https://maps.google.com/maps?f=d&daddr=41.3951982,-72.855568 to: 41.279386, -72.825098
OR
"https://www.google.com/maps/dir//41.3951982,-72.855568/41.279386,-72.825098"
Both of them work good when I paste on browser, but not on my mobile device. I just get source and destination. Any ideas?
EDIT:
Actually the second one works. Unlike browser, it only shows starting location and first point, but has a full navigation route. :)
There isn't any google approved way of doing it (as far as I looked to documentation). But I found this solution working pretty good
private void navigate(List<LatLng> latLngs) {
String uri = "";
for (LatLng latLng : latLngs) {
if (TextUtils.isEmpty(uri)) {
uri = String.format(
"http://maps.google.com/maps?saddr=%s, %s",
String.valueOf(latLng.latitude).replace(",", "."),
String.valueOf(latLng.longitude).replace(",", ".")
);
} else {
if (!uri.contains("&daddr")) {
uri += String.format(
"&daddr=%s, %s",
String.valueOf(latLng.latitude).replace(",", "."),
String.valueOf(latLng.longitude).replace(",", ".")
);
} else {
uri += String.format(
"+to:%s, %s",
String.valueOf(latLng.latitude).replace(",", "."),
String.valueOf(latLng.longitude).replace(",", ".")
);
}
}
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
}
Google Maps app on Android doesn't support multiple destinations. You can try to draw on the map by using native Google Maps Android API. You can get the directions from Google Maps Directions API.

Google Place API doesn't find everywhere (everything)

I'm trying to develop my own map. I have got ahead till somewhere. Now i'm trying to add place filter on my app. So i reached and found this link
I implemented and it works. But the problem is it doesnt find all bus stations or all banks around me. I'm from Turkey and i thought maybe it could work well in USA but it connects to GPS so i couldn't try for different state (country).
Does anyone know, how i can handle with this?
Just temporarily use hard-coded values for latitude and longitude in order to test your code with any location you want.
Replace your code with this in order to test your code with San Francisco as a location:
#Override
public void onClick(View v) {
double testLat = 37.7942635; //added
double testLon = -122.3955861; //added
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + testLat + "," + testLon ); //modified
sb.append("&radius=5000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=YOUR_API_KEY");
// Creating a new non-ui thread task to download json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
Try with an emulator. I emulated my position with Genymotion, but it was quite long to install and setup everything.
You might first try to emulate your position with the official emulator, as it seems to be possible now. Check this out.

Is there a way to show road directions in Google Map API v2? [duplicate]

This question already has answers here:
Get driving directions using Google Maps API v2
(4 answers)
Closed 3 years ago.
I was looking for an answer using Google and here, and the only relevant posts I have found are:
Google Maps Android V2 and Direction API
Get driving directions using Google Maps API v2
but there is no answer there. So I have already mentioned it but I will say that again. I am looking for a solution for the Google Map API v2 using FragmentActivity and a SupportMagFragment and LatLng objects and not using MapView ,MapActivity and GeoPoint.
In addition I don't have the Overlay object to use so I can't paint the direction on the map, is there an alternative for that?
So is there a way to do that?
Try this solution here. You can get driving or walking direction on V2.
The Overlay is indeed something to forget.
Polylines can easily be drawn
https://developers.google.com/maps/documentation/android/lines#add_a_polyline
Just loop through yourr points after you parsed tjhe JSON response:
PolylineOptions rectOptions = new PolylineOptions()
.add(new LatLng(37.35, -122.0))
.add(new LatLng(37.45, -122.0)) // North of the previous point, but at the same longitude
.add(new LatLng(37.45, -122.2)) // Same latitude, and 30km to the west
.add(new LatLng(37.35, -122.2)) // Same longitude, and 16km to the south
.add(new LatLng(37.35, -122.0)); // Closes the polyline.
// Set the rectangle's color to red
rectOptions.color(Color.RED);
// Get back the mutable Polyline
Polyline polyline = myMap.addPolyline(rectOptions);
Your question title is much more general than your requirements, so I will answer this in a way that I think will benefit those viewing this question and hopefully meet your requirements in perhaps a different way.
If you are not showing directions in the context of a map already being a loaded fragment and something having been done to show directions over the map (which is probably similar to what the OP is doing), it's easier and I believe standard to do this with an Intent.
This launches a map pathing activity (through a separate application - where the app launched depends on the user's compatible apps, which by default is Google Maps) that plots directions from the origin address (String originAddress) to the
destination address (String destinationAddress) via roadways:
// Build the URI query string.
String uriPath = "https://www.google.com/maps/dir/";
// Format parameters according to documentation at:
// https://developers.google.com/maps/documentation/directions/intro
String uriParams =
"?api=1" +
"&origin=" + originAddress.replace(" ", "+")
.replace(",", "") +
"&destination=" + destinationAddress.replace(" ", "+")
.replace(",", "") +
"&travelmode=driving";
Uri queryURI = Uri.parse(uriPath + uriParams);
// Open the map.
Intent intent = new Intent(Intent.ACTION_VIEW, queryURI);
startActivity(activity, intent, null);
(Where activity is simply the currently active Activity - obtained through whatever means are appropriate in the current programming context).
The following code gets an address String from a LatLng object (which must then be processed for the URI query String as above):
/**
* Retrieves an address `String` from a `LatLng` object.
*/
private void getAddressFromLocation(
final StringBuilder address, final LatLng latlng) {
// Create the URI query String.
String uriPath =
"https://maps.googleapis.com/maps/api/geocode/json";
String uriParams =
"?latlng=" + String.format("%f,%f",
latlng.latitude, latlng.longitude) +
"&key=" + GOOGLE_MAPS_WEB_API_KEY;
String uriString = uriPath + uriParams;
// Issue the query using the Volley library for networking.
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JSONObject response = null;
// Required for JsonObjectRequest, but not important here.
Map<String, String> jsonParams = new HashMap<String, String>();
JsonObjectRequest request =
new JsonObjectRequest(Request.Method.POST,
uriString,
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response != null) {
String resultString =
response.getJSONArray("results")
.getJSONObject(0)
.getString("formatted_address");
// Assumes `address` was empty.
address.append(resultString);
} // end of if
// No response was received.
} catch (JSONException e) {
// Most likely, an assumption about the JSON
// structure was invalid.
e.printStackTrace();
}
} // end of `onResponse()`
}, // end of `new Response.Listener<JSONObject>()`
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(LOG_TAG, "Error occurred ", error);
}
});
// Add the request to the request queue.
// `VolleyRequestQueue` is a singleton containing
// an instance of a Volley `RequestQueue`.
VolleyRequestQueue.getInstance(activity)
.addToRequestQueue(request);
}
This request is asynchronous, but it can be made synchronous.
You will need to call toString() on the actual parameter passed to address to obtain originAddress.
Q:I was looking for an answer using Google and here, and the only
relevant posts i have found are: Google Maps Android V2 and Direction
API Google map API v2 - get driving directions
Answer: Your saying, "but there is no answer there." is not absolutely right. In this site, you can find just only a few clues about that. I think you will not get the perfect code and concrete implement KNOW-HOWs here. In fact, many developers want to make the app to display the routing or directions on Google Maps. But I think there is no solution to get directions just only with the pure Google Maps API v2.
Q: So I have already mentioned it but I will say that again. I am
looking for a solution for the Google Map API v2 using
FragmentActivity and a SupportMagFragment and LatLng objects and not
using MapView ,MapActivtiy and GeoPoint.
Answer: Here are a few good sample tutorials (click here). You can find what you want.
Q: In addition i don't have the Overlay object to use so i can't paint
the direction on the map, is there an alternative for that? So is
there a way to do that?
Answer: In the Google Maps API v2, the annoying Overlay and so on are not any more required. For this, you can find the answer in my linked site above.

How to tell if a Streetview exists before launching Streetview intent

Launching a Streetview intent for a location doesn't guarantee that a Streetview exists for that location. If the Streetview doesn't exist, the user just sees a black screen that spins. Is there a way to programmatically check if it exists before launching the Streetview intent?
Use PackageManager and queryIntentActivities() with your Intent. If you get back a list of 0 matching activities, you know nothing on the device will handle your request.
A way to do that would be to use Google Street View Image API to check whether Google Street View exist or not.
https://developers.google.com/maps/documentation/streetview/
It returns an image with a different file size when Street View at a particular co-ordinates exist,than when it doesn't
http://maps.googleapis.com/maps/api/streetview?size=400x400&location=40.720032,%20-73.988354&fov=90&heading=235&pitch=10&sensor=false
You can compare these images and check if it exist or not.
I've not checked the Android API but with the JavaScript API there is a StreetViewService class with a getPanoramaByLocation method. If there is no Street View at that location, it returns NO_RESULTS.
i ll give you a snippet of my solution for checking if a streetview exists from my googe image api streetview image integration - guess you can use the StreetViewStatus.Ok boolean for ordinary streetview too.
streetViewService.getPanoramaByLocation(latLng, STREETVIEW_MAX_DISTANCE, function (streetViewPanoramaData, status) {
if (status === google.maps.StreetViewStatus.OK) {
var img = document.createElement("IMG");
img.src = 'http://maps.googleapis.com/maps/api/streetview?size=160x205&location='+ lat +','+ lng +'&sensor=false&key=AIzaSyC_OXsfB8-03ZXcslwOiN9EXSLZgwRy94s';
var oldImg = document.getElementById('streetViewImage');
document.getElementById('streetViewContainerShow').replaceChild(img, streetViewImage);
} else {
var img = document.createElement("IMG");
img.src = '../../images/ProfilnoProfilPicture.jpg';
img.height = 205;
img.width = 160;
var oldImg = document.getElementById('streetViewImage');
document.getElementById('streetViewContainerShow').replaceChild(img, streetViewImage);
}
});

Categories

Resources