How to set marker in google maps after button click? - android

I am trying to set a marker in google maps by giving the latitude and longitude of a certain place after finding places by using this:
public void findPlace() {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
.build();
try {
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.setFilter(typeFilter)
.build(getActivity());
getActivity().startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
//to add marker for destination location
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
From this i get the place and i am using the following to get lat and long of the place searched:
Place place = PlaceAutocomplete.getPlace(MainActivity.this, data);
Log.e("lat and long", place.getLatLng().latitude + place.getLatLng().longitude )
after this i am trying to set marker to that lat and long using this method i created :
protected Marker createMarker(double latitude, double longitude) {
Logger.e("inside" ,"create marker");
return mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.anchor(0.5f, 0.5f)
.title("Destination")
.snippet("Snippet Destination").icon(BitmapDescriptorFactory.fromResource(R.drawable.black)));
}
and this method seems to work only inside onverride method onMapReady.
How can I use it after button click?

Call below method when you want put marker on map.
public Marker placeMarker(EventInfo eventInfo) {
Marker m = getMap().addMarker(new MarkerOptions().position(eventInfo.getLatLong()).title(eventInfo.getName()));
return m;
}

Related

How to load Android Direction API results in external Google Maps app?

I am using Google Directions API to get routes between two locations with Way Points.
Currently what I am doing is getting direction details between two locations using Direction API and showing the result in Google Maps integrated inside my application. It works well as expected. This is how I did it:
private DirectionsResult getDirectionsDetails(String origin,String destination,TravelMode mode) {
Log.i("testtt"," Origin "+origin+" Destination "+destination);
DateTime now = new DateTime();
try {
return DirectionsApi.newRequest(getGeoContext())
.mode(mode)
.origin(origin)
.waypoints(waypoints.toArray(new String[0]))
.destination(destination)
.departureTime(now)
.await();
} catch (InterruptedException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (com.google.maps.errors.ApiException e) {
e.printStackTrace();
return null;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
setupGoogleMapScreenSettings(googleMap);
DirectionsResult results = getDirectionsDetails(origin,destination,TravelMode.DRIVING);
if (results != null) {
addPolyline(results, googleMap);
positionCamera(results.routes[overview], googleMap);
addMarkersToMap(results, googleMap);
}
}
private void setupGoogleMapScreenSettings(GoogleMap mMap) {
mMap.setBuildingsEnabled(true);
mMap.setIndoorEnabled(true);
mMap.setTrafficEnabled(true);
UiSettings mUiSettings = mMap.getUiSettings();
mUiSettings.setZoomControlsEnabled(true);
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(true);
mUiSettings.setScrollGesturesEnabled(true);
mUiSettings.setZoomGesturesEnabled(true);
mUiSettings.setTiltGesturesEnabled(true);
mUiSettings.setRotateGesturesEnabled(true);
}
private void addMarkersToMap(DirectionsResult results, GoogleMap mMap) {
mMap.addMarker(new MarkerOptions().position(new LatLng(results.routes[overview].legs[overview].startLocation.lat,results.routes[overview].legs[overview].startLocation.lng)).title(results.routes[overview].legs[overview].startAddress));
mMap.addMarker(new MarkerOptions().position(new LatLng(results.routes[overview].legs[overview].endLocation.lat,results.routes[overview].legs[overview].endLocation.lng)).title(results.routes[overview].legs[overview].endAddress).snippet(getEndLocationTitle(results)));
}
private void positionCamera(DirectionsRoute route, GoogleMap mMap) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(route.legs[overview].startLocation.lat, route.legs[overview].startLocation.lng), 12));
}
private void addPolyline(DirectionsResult results, GoogleMap mMap) {
List<LatLng> decodedPath = PolyUtil.decode(results.routes[overview].overviewPolyline.getEncodedPath());
mMap.addPolyline(new PolylineOptions().addAll(decodedPath));
}
But what I want is I want to load this direction result in the external Google Maps app. What I am asking is is there any way to pass the DirectionsResult object to Google Maps application via Intent so that it will show the routes in the app.
Reason why I want this is to avoid integrating Google Maps API to the project as it is not completely free anymore.
Pricing details
As I can see in your code, that you are not performing any calculations on the DirectionsDetails given by DirectionsApi you can open the pass your location coordinates in google maps.
By default, Google maps always loads the best available route according to current traffic and time:
String geoUri = "http://maps.google.com/maps?q=loc:" + lat + "," + lng + " (" + mTitle + ")";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(geoUri));
context.startActivity(intent);
If you want to add waypoints in between your source and destination you can have a look at this answer.
If you want, you can find the route through DirectionsApi and process the data for your internal analytics for eg. approx time to travel between his location and new location, distance etc.

How to show multiple Location on Google map?

i have to show multiple location on the Native Google Map Application (MapView is not implemented in our application ).i have all the lat- long of all the geo Points . how can i pass the intent to show the multiple points on Native Google Map Application.
i know to show a point on Google map using the following Code.
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
please suggest how to do the needful changes.
Thanks :)
You can pass the names of the places that you want to show in the Map from the other Activity to the present Activity and then implement Markers to show them in the Map. For this you have to implement Google Map in the present Activity and I hope you have done that. :)
The below code shows multiple locations on a Google Map:
private void AddMarkers(GoogleMap googleMap)
{
try {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
Geocoder geocoder = new Geocoder(context);
Origin_Map = extras.getString(MainActivity.ORIGIN_MAP);
Destination_Map = extras.getString(MainActivity.DESTINATION_MAP);
Addr_Origin = geocoder.getFromLocationName(Origin_Map, 1);
Addr_Dest = geocoder.getFromLocationName(Destination_Map, 1);
if (Addr_Origin.size() > 0) {
latitude_origin = Addr_Origin.get(0).getLatitude();
longitude_origin = Addr_Origin.get(0).getLongitude();
}
if (Addr_Dest.size() > 0) {
latitude_destination = Addr_Dest.get(0).getLatitude();
longitude_destination = Addr_Dest.get(0).getLongitude();
}
Marker m1 = googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude_origin, longitude_origin)).title(Origin_Map).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
Marker m2 = googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude_destination, longitude_destination)).title(Destination_Map).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
} catch (Exception e) {
e.printStackTrace();
}
}
And call this method once your map is ready!
#Override
public void onMapReady(GoogleMap googleMap)
{
AddMarkers(googleMap);
}
Hope this helps!!
Judging by this it is not possible. Also the question is a duplicate of this.

Choose from map with android marshmallow

Now I'm using android map clicklistener to allow user to choose location from map. When the click the map the chosen location latitude and longitude are printed correctly in the toast, then I send this data to another fragment through bundle.
On android marshmallow devices it always transferred with null value, even it's working properly with all other versions.
I don't know what is the problem, so I'll be blessed for any help
Here is my code
try {
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate Update = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(Update);
final Marker TP = map.addMarker(new MarkerOptions().position(latLng).title(""));
TP.setDraggable(true);
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
Toast.makeText(getActivity(), point.toString(), Toast.LENGTH_SHORT).show();
String latMap = String.valueOf(point.latitude);
String lngMap = String.valueOf(point.longitude);
((MainActivity)getActivity()).aqarLat = String.valueOf(point.latitude);;
((MainActivity)getActivity()).aqarLong = String.valueOf(point.longitude);
myBundle = new Bundle();
myBundle.putString("latMap" , latMap);
myBundle.putString("lngMap" , lngMap);
sharedPreferences.edit().putString("latMap", String.valueOf(point.latitude)).commit();
sharedPreferences.edit().putString("longMap", String.valueOf(point.longitude)).commit();
TP.setPosition(point);
}
});
} catch (Exception e) {
e.printStackTrace();
}
Thanks in advance

Controlling markers Deployment.?

I am building an android app in which i have to do tracking of a user from one date/time to another and deploy makers using polylines one by one?
In response from a server i am receiving multiple lat/langs in a list. Now i want to deploy them one by one like a video is being played i know how to add markers i just want to control there deployment.E.g Marker A is deployed after 2 secs marker B should be deployed and joining with marker A with a poly-line and so do markers C,D. etc. How should i be able to achieve that. Timer, Threads? Any help or references,algos, would be great although i have searched such examples i couldn't find it yet.
Thanks in advance
You can use Handler to perform this task.
I am posting an example for you, I have not run it but I hope It will run successfully:
private final Handler mHandler = new Handler(Looper.getMainLooper());
private List<LatLng> mLatLngs;
private PutMarkerRunnable mRunnable;
private int mNoOfMarkersPlaced = -1;
private void showMarkers(List<LatLng> latLngs) {
mLatLngs = latLngs;
mHandler.post(mRunnable);
}
private class PutMarkerRunnable implements Runnable {
#Override
public void run() {
// write code to add marker
map.addMarker();
mNoOfMarkersPlaced++;
if (mNoOfMarkersPlaced != mLatLngs.size()) {
// scheduling next marker to be placed after 3 seconds
mHandler.postDelayed(mRunnable, 3000);
}
}
}
Ok thanks community.. But i have been finally able to do this through. Mark it correct because this really worked for me!
First we animate our camera using..
CameraPosition cameraPosition =
new CameraPosition.Builder()
.target(new LatLng(0,0))
.bearing(45)
.tilt(90)
.zoom(googleMap.getCameraPosition().zoom)
.build();
googleMap.animateCamera(
CameraUpdateFactory.newCameraPosition(cameraPosition),
ANIMATE_SPEEED_TURN,
new CancelableCallback() {
#Override
public void onFinish() {
}
#Override
public void onCancel() {
}
}
);/**
*
* Callback that highlights the current marker and keeps animating to the next marker, providing a "next marker" is still available.
* If we've reached the end-marker the animation stops.
*
*/
CancelableCallback simpleAnimationCancelableCallback =
new CancelableCallback(){
#Override
public void onCancel() {
}
#Override
public void onFinish() {
if(++currentPt < markers.size()){
CameraPosition cameraPosition =
new CameraPosition.Builder()
.target(targetLatLng)
.tilt(currentPt<markers.size()-1 ? 90 : 0)
//.bearing((float)heading)
.zoom(googleMap.getCameraPosition().zoom)
.build();
googleMap.animateCamera(
CameraUpdateFactory.newCameraPosition(cameraPosition),
3000,
simpleAnimationCancelableCallback);
highLightMarker(currentPt);
}
}
};
A bearing can be calculated between 2 android.location.Location objects. As we’re working with com.google.android.gms.maps.model.LatLng objects here, we first need to convert them into Location objects.
private Location convertLatLngToLocation(LatLng latLng) {
Location location = new Location("someLoc");
location.setLatitude(latLng.latitude);
location.setLongitude(latLng.longitude);
return location;
}
Once we have 2 Location objects, we can calculate the bearing between the 2. This is what we need to put on the Camera when transitioning to the target (the endLocation).
private float bearingBetweenLatLngs(LatLng beginLatLng,LatLng endLatLng) {
Location beginLocation = convertLatLngToLocation(beginLatLng);
Location endLocation = convertLatLngToLocation(endLatLng);
return beginLocation.bearingTo(endLocation);
}
We’ll use that number to calculate the coordinates of the intermediate point. Once we have those coordinates, we set our tracking marker to that new position.
long elapsed = SystemClock.uptimeMillis() - start;
double t = interpolator.getInterpolation((float)elapsed/ANIMATE_SPEEED);
double lat = t * endLatLng.latitude + (1-t) * beginLatLng.latitude;
double lng = t * endLatLng.longitude + (1-t) * beginLatLng.longitude;
LatLng intermediatePosition = new LatLng(lat, lng);
trackingMarker.setPosition(intermediatePosition);
We’ll also update our polyline with the new marker position, creating a trailing effect on the polyline.
private void updatePolyLine(LatLng latLng) {
List<LatLng> points = polyLine.getPoints();
points.add(latLng);
polyLine.setPoints(points);
}

How to draw driving route from current location to destination by google map api lastest version (google play service 8.3)

previously I use GmapV2 from Android: How to draw route directions google maps API V2 from current location to destination. But now it's not work I got error about that class. How to fix that class?
This code will draw the line from origin to destination.
#Override
public void onDirectionSuccess(Direction direction, String rawBody) {
Log.d("Status", "Success");
Log.d("Direction", "" + direction);
mMap.addMarker(new MarkerOptions().position(origin));
mMap.addMarker(new MarkerOptions().position(destination));
if (waypoints != null){
for (int i = 0; i < waypoints.size(); i++){
mMap.addMarker(new MarkerOptions().position(waypoints.get(i)));
}
}
ArrayList<LatLng> directionPositionList = direction.getRouteList().get(0).getLegList().get(0).getDirectionPoint();
mMap.addPolyline(DirectionConverter.createPolyline(this, directionPositionList, 5, Color.BLUE));
Log.d("Status", "Success 2");
showRoute.setVisibility(View.GONE);
}

Categories

Resources