How to implement Google Directions API for unknown destination? - android

I'm a beginner in android studio and I'm currently create cycling apps for my final project. in these apps I need to implement Maps and Direction API. I search for tutorials, but they all set the destination. and in my apps the destination is unknown.
it's possible if I display the current location (automatic) and draw a line in Maps while the user is riding, please give a tutorial too? And it's possible if I use a Free API Key for this project?
thank you ...

First, This direction API is not free.
2nd you need to provide start and endpoint for direction API routes.
You can use the current location as your start point and if you have no destination then where do you want to draw a line? Means from your current location to where?
or If you want to draw a tracking line from your starting position to your current position then you don't need Direction API, you just need Live location tracking and can draw Polylines on your map using current location. Following is the code for your help.
To get this library into our app, we need to add the following to our build.gradle file.
implement 'com.google.maps:google-maps-services:0.1.20'
// Initialize Geo Context First
private GeoApiContext getGeoContext() {
GeoApiContext geoApiContext = new GeoApiContext();
return geoApiContext.setQueryRateLimit(3)
.setApiKey(getString(R.string.directionsApiKey))
.setConnectTimeout(1, TimeUnit.SECONDS)
.setReadTimeout(1, TimeUnit.SECONDS)
.setWriteTimeout(1, TimeUnit.SECONDS);
}
// This code will fetch the result from Google direction api from origin to destination
DateTime now = new DateTime();
DirectionsResult result = DirectionsApi.newRequest(getGeoContext()).mode(TravelMode.DRIVING).origin(origin)
.destination(destination)
.departureTime(now).await();
// You can use this method to add marker on the map
private void addMarkersToMap(DirectionsResult results, GoogleMap mMap) {
mMap.addMarker(new MarkerOptions().position(new LatLng(results.routes[0].legs[0].startLocation.lat, results.routes[0].legs[0].startLocation.lng)).title(results.routes[0].legs[0].startAddress));
mMap.addMarker(new MarkerOptions().position(new LatLng(results.routes[0].legs[0].endLocation.lat, results.routes[0].legs[0].endLocation.lng)).title(results.routes[0].legs[0].startAddress).snippet(getEndLocationTitle(results)));
}
// Use this method to draw polyline/routes on your map
private void addPolyline(DirectionsResult results, GoogleMap mMap) {
List<LatLng> decodedPath = PolyUtil.decode(results.routes[0].overviewPolyline.getEncodedPath());
mMap.addPolyline(new PolylineOptions().addAll(decodedPath));
}

Related

Is it possible to check if a point is inside a polygon from geojson?

I have a geojson with some polygons, added it as a source and created a layer to show those features on the mapbox map.
Since I am using this method: (Edit from the sample souce: MapboxGLAndroidSDKTestApp)
final PointF pixel = mapboxMap.getProjection().toScreenLocation(point);
List<Feature> fList = mapboxMap.queryRenderedFeatures(pixel, "polygons");
for(Feature feature:fList){
Log.d(TAG,"FeatureInfo: "+feature.toJson());
}
I can check if the marker is inside one of those polygons by passing the marker position to it.
But when I move my camera far away to the marker, the polygon is not rendered and the checker is not work anymore.
So my question is, is there any way to check if the marker is inside the polygon, which no matter where is my camera pointing at?
To check a point whether lies or not inside a polygon on mapbox
can use turf.js library http://turfjs.org/
This is the way in which you don't need to plot point or polygon on the mapbox(without plotting).
var point = turf.point([-75.343, 39.984]);
// here first is lng and then lat
var polygon = turf.polygon([[
[-2.275543, 53.464547],
[-2.275543, 53.489271],
[-2.215118, 53.489271],
[-2.215118, 53.464547],
[-2.275543, 53.464547]
]], { name: 'poly1'});
// here first is lng and then lat
now you can use inside method from turf lib
i.e turf.inside(point, polygon); // return boolean True/False
Use TurfJoins.inside(yourPoint, yourPolygon)

Load a custom google map to android

I'm new to android development.
I need to load a custom google-map someone made in google maps (a map with marks and information).
My question is how to load this map on a android app (and not just creating a new map and manually adding all the markers and information -- because than each time client wants to change something in the map he will need to change it in 2 places).
I know i can just make a webview but than i can't access the location and focus on users location -- is there any other way?
Thanks for the help!
You can take the location of your indicated region and add the markers manually if there isn't place to mark.
static final LatLng MELBOURNE = new LatLng(-37.813, 144.962);
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
https://developers.google.com/maps/documentation/android-api/marker

How to add the marker on the map after camera animation has finished

I am trying to draw the marker showing the user's current location although I have enabled setMycurrentLocation in map while initializing it, so I am getting the the latitude and longitude of current location . Now what I am doing is showing marker at the current location . this is how I am doing it
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15), 8000, new GoogleMap.CancelableCallback() {
#Override
public void onFinish() {
Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
public void run() {
addMarker(googleMap.getLocation.getLatitude(), googleMap.getLocation.getLatitude());
and my addMarker function goes like this
private void addMarker(Double Lat, Double Long) {
/** Make sure that the map has been initialised **/
if (null != googleMap) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(Lat, Long))
.title("You")
.draggable(true)
);
}
}
So this peace of code of adding marker only works if I try it using out side of onfinished function of map animation , but
some times it gives me a null as sometimes it is unable to get the location from map.
So I tried it to put this exactly after when the camera stop animation.
but in my case it is not working , Any idea ? or what else other way I
can do to add marker when the camera stop animation .?
As from comments and code, it seems you want to have multiple markers of the user location on the map, but the code you are using for obtaining user location is not ok (I can't find googleMap.getLocation and maybe the code is not complete).
The method getMyLocation() of google maps is deprecated:
https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.html#getMyLocation()
This method is deprecated.
use
com.google.android.gms.location.FusedLocationProviderApi instead.
FusedLocationProviderApi provides improved location finding and power
usage and is used by the "My Location" blue dot. See the
MyLocationDemoActivity in the sample applications folder for example
example code, or the Location Developer Guide.
The link points to https://developers.google.com/maps/documentation/android/location
Which then ports you tu use FusedLocationProvider. You have to look at that guides to obtain user location. When you have done it, you can put that code in the onFinish callback.
If you need help for fused location provider maybe you should check for already existent questions or open a new one with the appropriate tags!

Clickable Polylines Google Maps API Android

I would like to click a spot on a Google maps v2 android map. If the clicked point intersects a point on a polyline path, then display the polyline. I do not see any documented clickable events for polylines in android. I tried to extend the current Polyline object (marked final)
What other options do I have?
You can use library:
https://github.com/googlemaps/android-maps-utils
And detect clicks to polyline using next method (in OnMapClickListener):
PolyUtil.isLocationOnPath(point, polyline.getPoints(), isGeodesic, tolerance);
With the recent update of the maps api, v8.4, introduces clickable Polyline
As mentioned in the doc:
Use the OnPolylineClickListener to listen to click events on a
clickable polyline. To set this listener on the map, call
googleMap.setOnPolylineClickListener(...). When
a user clicks on a polyline, you will receive an
onPolylineClick(Polyline) callback.
gradle-dependency:
compile 'com.google.android.gms:play-services-maps:8.4.0'
implement callback: GoogleMap.OnPolylineClickListener
initialize Polyline:
Polyline polyline = googleMap.addPolyline(options);
polyline.setClickable(true);
...
receive events
#Override
public void onPolylineClick(Polyline polyline) {
....
}
Happy coding :)
Register an OnMapClickListener. Determine if a given click is on your line yourself. If it is, do whatever it was you wanted to do in this case.
I had a similar issue where I could not process click events on polylines. I was using Xamarin for Android which is C# but the functionality is largely the same as the Android Java Libraries in this case.
In the end, I ended up doing what seemed to be the only option.
This involved processing all of the midpoints of my polylines(of which there were around 1300). On every OnMapClick, I took the LatLng of the click event and performed a distance formula between it and the midpoint of all polylines in the static List<PolylineOptions>. I then attached a map marker to the closest polyline.
From a tap on a polyline, it pops up a marker in about a quarter of a second.
I imagine the implemented marker click events from the Google Maps API work in a similar way.
Here is the for loop that handles finding the closest point to a click.
int i = 0;//create an indexer for the loop
double shortestDist = 100;//set an initial very large dist just to be safe
int myIndex = 0;//set variable that will store the running index of the closest point
foreach (PolylineOptions po in myPolylines) {
var thisDist = Distance (point, midPoint (po.Points [0].Latitude, po.Points [0].Longitude, po.Points [1].Latitude, po.Points [1].Longitude));//calculate distance between point and midpoint of polyline
if (thisDist < shortestDist) {
shortestDist = thisDist;//remember current shortest distance
myIndex = i;//set closest polyline index to current loop iteration
}
i++;
}
I know it isn't the prettiest code but it gets the job done. I didn't see a real answer to this anywhere on the internet so here it is. It could probably be made more efficient by calculating the midpoints beforehand and storing them in an equally sized list and then not having to call the midpoint formula for each polyline on every map click but it works really fast already.
EDIT
I do my testing on a galaxy s3 by the way, so I think it's not too inefficient.
If you are using com.google.android.gms:play-services-maps:8.4.0 then it includes polylines click listener
googleMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener()
{
     #Override
     public void onPolylineClick(Polyline polyline)
      {
          //do your work selected polyline
     }
});
PolylineOptions line = new PolylineOptions();
Polyline polyline = googleMap.addPolyline(line);
polyline.setClickable(true);

Embed google map from a link in android

I have a map in this link . and I am following this tutorial on google maps
http://www.vogella.com/articles/AndroidGoogleMaps/article.html
but what I can't understand is how to make the map open on the location I have here in this link
https://maps.google.com/?ll=26.293723,50.186512&spn=0.004146,0.007639&t=m&safe=on&z=17
sorry if this seems trivial, I am just new to android
Thanks in advance
First of all, i would recommend you to stop reading that tutorial because the Google Maps API version it uses is deprecated.
That said, and specially if you are starting from scratch, i would start reading the new Google Maps Android API V2 documentation.
According to the URL you have posted, the location you want to go is 26.293723, 50.186512 with a Zoom level of 17. Don't know what the spn parameter is.
You can accomplish this by setting the camera position on the GoogleMap object, using the newCameraPosition method:
GoogleMap map = // <Get it from your fragment>
LatLng point = new LatLong( 26.293723, 50.186512);
CameraPosition position = new CameraPosition( 0, point, 0, 17F );
map.newCameraPosition(position);
You can also do it with a nice flying animation with the method newLatLngZoom:
GoogleMap map = // <Get it from your fragment>
LatLng point = new LatLong( 26.293723, 50.186512);
map.newLatLngZoom(point, 17F);
From the link I notice you have the lat-long values of the location. Pass your latitude and longitude as extras to the activity in which you display the Map. Use these values to create a GeoPoint which you can pass to setCenter() and/or animateTo() using your MapController.
controller.setCenter(geoPoint);
controller.animateTo(geoPoint);
Here's more info on how to use these methods.

Categories

Resources