How to draw path between two marker? - android

I am using osm in my android application. And i have to show a path between two marker.I have used path overlay but line not draw.
Anyone knows how to draw line between two marker in android osm map ?

I got the solution — here is the answer:
new Thread(new Runnable()
{
public void run()
{
RoadManager roadManager = new OSRMRoadManager();
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
GeoPoint startPoint = new GeoPoint(source_lat, source_longi);
waypoints.add(startPoint);
GeoPoint endPoint = new GeoPoint(desti_lat,desti_longi);
waypoints.add(endPoint);
try
{
road = roadManager.getRoad(waypoints);
}
catch (Exception e)
{
e.printStackTrace();
}
runOnUiThread(new Runnable()
{
public void run()
{
if (road.mStatus != Road.STATUS_OK)
{
//handle error... warn the user, etc.
}
Polyline roadOverlay = RoadManager.buildRoadOverlay(road, Color.RED, 8, context);
map.getOverlays().add(roadOverlay);
}
});
}
}).start();
And I am using two JAR files: slf4j-android-1.5.8.jar and osmdroid-android-4.2.jar, and osmbonuspack library.

You can use the open source route planner GraphHopper (where I'm the author of) which works offline on Android and iOS. See the Android documentation, which uses mapsforge and the code is here:
mapView = new MapView(this);
...
mapView.getLayerManager().getLayers().add(createPolyline(resp));
Or you can use it via online connection too, here are JavaScript and Java clients.

float[] arr=new float[5];
android.location.Location.distanceBetween(latitude,longitude,(Double.parseDouble(bn.getString("lat"))),(Double.parseDouble(bn.getString("lon"))),arr);
System.out.println("distance"+arr[0]);
if(arr[0]>5){
if(isNetworkAvailable()){
if(latitude!=0){
findDirections( latitude, longitude,Double.parseDouble(bn.getString("lat")),Double.parseDouble( bn.getString("lon")), GMapV2Direction.MODE_DRIVING );
}else
Toast.makeText(getApplicationContext(), "sorry can't access your current location",1500).show();
}
public void findDirections(double fromPositionDoubleLat, double fromPositionDoubleLong, double toPositionDoubleLat, double toPositionDoubleLong, String mode)
{
Map<String, String> map = new HashMap<String, String>();
map.put(GetDirectionsAsyncTask.USER_CURRENT_LAT, String.valueOf(fromPositionDoubleLat));
map.put(GetDirectionsAsyncTask.USER_CURRENT_LONG, String.valueOf(fromPositionDoubleLong));
map.put(GetDirectionsAsyncTask.DESTINATION_LAT, String.valueOf(toPositionDoubleLat));
map.put(GetDirectionsAsyncTask.DESTINATION_LONG, String.valueOf(toPositionDoubleLong));
map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE, mode);
GetDirectionsAsyncTask asyncTask = new GetDirectionsAsyncTask(this);
asyncTask.execute(map);
}
public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) {
PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.RED);
for(int i = 0 ; i < directionPoints.size() ; i++)
{
rectLine.add(directionPoints.get(i));
}
if (newPolyline != null)
{
newPolyline.remove();
}
newPolyline = map.addPolyline(rectLine);
Display display = getWindowManager().getDefaultDisplay();
latlngBounds = createLatLngBoundsObject(new LatLng(latitude, longitude),new LatLng(Double.parseDouble(bn.getString("lat")),Double.parseDouble( bn.getString("lon"))));
map.animateCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, display.getWidth(), display.getHeight(), 150));
}
private LatLngBounds createLatLngBoundsObject(LatLng firstLocation, LatLng secondLocation)
{
if (firstLocation != null && secondLocation != null)
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(firstLocation).include(secondLocation);
return builder.build();
}
return null;
}

Related

Delete polyline behind Current Location Marker Like Uber android [duplicate]

I have googleMap (v2) with polyline that presents a route between the user current location and the destination point. Now, I want to update the polyline according to the user moving.
I tried to redrawing the whole polyline when location is changed but the polyline is flickering.
I didn't find any appropriate function in the PolylineOptions class (the function add() is only to add a vertex but not to update or remove)
do you have any idea how to update the polyline ???
thank you for giving your time.
The only way as of version 3.1.36:
List<LatLng> points = polyline.getPoints();
points.add(newPoint);
polyline.setPoints(points);
Hopefully the API will be enhanced in later versions.
*I have already done working on updating polyline path without removing the polyline. We can do this by changing the points of that polyline. Check below code.
This is the logic of setting new points to polyline.
/*Here the routes contain the points(latitude and longitude)*/
for (int i = 0; i < routes.size(); i++) {
Route route = routes.get(i);
if(polyline_path != null){
polyline_path.setPoints(route.points);
}
}
Detail Explanation:
private GoogleMap map_object;
private Marker marker_driver;
private Marker marker_drop_off;
private Polyline polyline_path;
private PolylineOptions polylineOptions_path;
...
...
...
/*HelperDirectionFinder is a class that I create to call google API and I used this
class to get directions routes*/
/*I have created Service, and I'm calling this lines below after 5 sec. to get the
updated routes from google API.*/
HelperDirectionFinder directionFinder = new HelperDirectionFinder(
JobEndScreen.this, source, destinations);
try {
directionFinder.showDirection();
} catch (UnsupportedEncodingException e) {
HelperProgressDialog.closeDialog();
}
...
...
...
#Override
public void onDirectionFinderStart() {
if(polylineOptions_path == null){
HelperProgressDialog.showDialog(getActivity(), "", getString(R.string.text_loading));
}
}
/*This interface method is called after getting routes from google API.*/
/*Here the routes contains the list of path or routes returned by Google Api*/
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
HelperProgressDialog.closeDialog();
/*When polylineOptions_path is null it means the polyline is not drawn.*/
/*If the polylineOptions_path is not null it means the polyline is drawn on map*/
if(polylineOptions_path == null){
for (Route route : routes) {
polylineOptions_path = new PolylineOptions().
geodesic(true).
color(ContextCompat.getColor(getActivity(), R.color.color_bg_gray_dark)).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions_path.add(route.points.get(i));
polyline_path = map_object.addPolyline(polylineOptions_path);
}
}
else {
for (int i = 0; i < routes.size(); i++) {
Route route = routes.get(i);
if(polyline_path != null){
polyline_path.setPoints(route.points);
}
}
}
}
//Declare on global
PolylineOptions polyOptions, polyOptions2;
Polyline polyline2;
List<LatLng> ltln;
private Double lat_decimal = 0.0,lng_decimal=0.0;
//initialize
ltln = new ArrayList<>();
//if you are using routing library
compile 'com.github.jd-alexander:library:1.0.7'
#Override
public void onRoutingSuccess(ArrayList<Route> arrayList, int i) {
//Add this code snippet on onRoutingSuccess to store latlan list
ltln = new ArrayList<>();
System.out.println("-----arrayList------" + arrayList.get(0).getPoints());
ltln = arrayList.get(0).getPoints();
// NOTE here already we draw polyLine 1
}
//below mentioned how to update polyline
private void UpdatePoliline(){
System.out.println("-------runnablePolyline-------"+ltln.size());
try {
if (ltln.size() > 0) {
for (int i = 0; i < ltln.size(); i++) {
ltln.remove(i);
if (CalculationByDistance(ltln.get(i), new LatLng(lat_decimal, lng_decimal)) >= 10) {
break;
}
}
polyOptions2 = new PolylineOptions();
polyOptions2.color(getResources().getColor(R.color.app_color));
polyOptions2.width(7);
polyOptions2.addAll(ltln);
if (polyline2 == null) {
polyline2 = googleMap.addPolyline(polyOptions2);
if (polyLines.size() > 0) {
for (Polyline poly : polyLines) {
poly.remove();
}
}
polyLines.add(polyline2);
if (polyline != null) {
polyline.remove();
polyline = null;
}
} else {
polyline = googleMap.addPolyline(polyOptions2);
if (polyLines.size() > 0) {
for (Polyline poly : polyLines) {
poly.remove();
}
}
polyLines.add(polyline);
if (polyline2 != null) {
polyline2.remove();
polyline2 = null;
}
}
System.out.println("=====waypoints new===" + ltln);
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
// Calculating distance between 2 points
public float CalculationByDistance(LatLng StartP, LatLng EndP) {
Location locationA = new Location("Source");
locationA.setLatitude(StartP.latitude);
locationA.setLongitude(StartP.longitude);
Location locationB = new Location("Destination");
locationB.setLatitude(EndP.latitude);
locationB.setLongitude(EndP.longitude);
float distance = locationA.distanceTo(locationB);
return distance;
}
//Redraw Polyline vehicle is not in current polyline with particular distance
if (ltln.size() > 0) {
if (PolyUtil.isLocationOnPath(new LatLng(currentlat, currentLon), ltln, false, 60.0f) ){
System.out.println("===tolarance===" + true);
} else {
//Redraw Polyline
}
}
UpdatePoliline();

Every 1 Minute Gps LatLong Getting From Server Showing In Map as Marker. But Marker Geting Duplicating

1.In My app Gps LatLong is Getting from Server Every OneMinute. Saved in Shared Pref ,then getting the LatLong From shared pref Showing the Marker on the Map.
2.Every One Minute I want to Move the Marker based on the LatLong.
3.But While Changing the Marker Location. Getting Duplicates.
Please Help me to Solve this Issue.
Inside Oncreate method i Called below Snippet in Every 60 Secs for Calling a Method.
try
{
Thread t = new Thread()
{
#Override
public void run()
{
try
{
while (!isInterrupted())
{
Thread.sleep(60*1000);
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
display_Location();
Log.i("Every 60 Second","Current Called..");
}
});
}
} catch (Exception e)
{
e.printStackTrace();
}
}
};
t.start();
}
catch (Exception e)
{
e.printStackTrace();
}
Method Iam USing:
private void display_Location()
{
try
{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
/*For Current Location ping Starts Here*/
// get user data from session
HashMap<String, String> user = session.getGPSPING();
// UserLat
String LatLongUser = "";
LatLongUser = user.get(SessionManagerFor_Register.KEY_LATLONG);
if (!LatLongUser.equals("") || LatLongUser != null)
{
Log.i(" PING on MAP LatLong", LatLongUser);
String[] LanlongArr = LatLongUser.split("//");
List<String> Lanlonglist1 = Arrays.asList(LanlongArr);
int length = Lanlonglist1.size();
/*ArrayList For adding All ArrayList items in Single(Concating)*/
arraylist_DetailLineWalker = new ArrayList<String>(length);
for (int i = 0; i < length; i++) {
arraylist_DetailLineWalker.add(Lanlonglist1.get(i)
);
}
if (arraylist_DetailLineWalker != null)
{
// Initializing
LineWalkermMarkers_arr = new ArrayList<Marker>();
// just Remove Older Line Wlaker
if (LineWalkermMarkers_arr != null) {
// LineWalker_marker1.remove();
RemoveLineWalkerMarkers();
Log.i(TAG, "LineWalker REMOVED.............................");
}
for (int i = 0; i < arraylist_DetailLineWalker.size(); i++)
{
try
{
String Val = arraylist_DetailLineWalker.get(i).toString();
//Log.i(" Validation Id",Val);
VALUE_ARRAY_STRING = Val.toString().split("::");
LatLong_DataSaveTable = VALUE_ARRAY_STRING[0].toString();
System.out.println("checking STarted LatLong::" + LatLong_DataSaveTable);
String[] latlong = LatLong_DataSaveTable.split(",");
double latitude1 = Double.parseDouble(latlong[0]);
double longitude2 = Double.parseDouble(latlong[1]);
//To hold location
LatLng latLng1 = new LatLng(latitude1, longitude2);
//To create marker in map
MarkerOptions markerOptionsLineWalker = new MarkerOptions();
markerOptionsLineWalker.position(latLng1); //setting position
markerOptionsLineWalker.draggable(true); //Making the marker draggable
markerOptionsLineWalker.title("USER LOCAITON");
markerOptionsLineWalker.icon(BitmapDescriptorFactory.fromResource(R.drawable.walker_outof_fence_icon_red));
//adding marker to the map
// googleMap.addMarker(markerOptionsLineWalker);
LineWalker_marker1 = googleMap.addMarker(markerOptionsLineWalker);
LineWalkermMarkers_arr.add(LineWalker_marker1);
// LineWalker_marker1.setPosition(latLng1);
Log.i(TAG, " NEW Line Walkers PING Added.............................");
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
} else {
Log.i("MAP NEwLatLong", "TOTAL ARRY LIST NULLL");
}
}
else
{
Log.i("MAP NEwLatLong", "Null Not LatLong");
Toast.makeText(getActivity(), "Lat Long Not Available..!", Toast.LENGTH_SHORT).show();
}
}
else
{
Log.i("Location EXception", "Couldn't get the location. Make sure location is enabled on the device");
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
/*Remove the Linewalker*/
private void RemoveLineWalkerMarkers()
{
for (Marker marker: LineWalkermMarkers_arr)
{
marker.remove();
}
LineWalkermMarkers_arr.clear();
}
if(arraylist_DetailLineWalker != null && arraylist_DetailLineWalker.size()>0){
arraylist_DetailLineWalker.clear()
mMap.clear();
showMarker();
}
You are calling RemoveLineWalkerMarkers() after initializing LineWalkermMarkers_arr doing LineWalkermMarkers_arr = new ArrayList<Marker>();, so you are never removing your markers.
Just initialize your LineWalkermMarkers_arr after removing the markers:
if (LineWalkermMarkers_arr != null) {
RemoveLineWalkerMarkers();
Log.i(TAG, "LineWalker REMOVED.............................");
}
LineWalkermMarkers_arr = new ArrayList<Marker>();
As a side note, you should follow the Java code conventions (variables and method names should start with lowercase). You can find good guides here and here
Solution is just a logic change
Initialize Marker only once , either onCreate or some other method according to your logic
If the markers are multiple, then re-initialization should be done once data is received.
Created markers can be cleared with below logic
if(mGoogleMap != null) {
mGoogleMap.clear();
}
Either reuse this marker to move from last location to new location. Or recreate all the markers, once data is received
//With your logic , this check should be done
if(arraylist_DetailLineWalker.size()>0){
RemoveLineWalkerMarkers();
}
LineWalkermMarkers_arr = new ArrayList<Marker>();
for (int i = 0; i < arraylist_DetailLineWalker.size(); i++)
{
}
Alternative easy method to move single marker , to show live driving direction kind of feature
private Marker mCurrentMarker;
private float ZOOMLEVEL=18.0f;
private LatLng previousLatLon;
private Handler mLocalHandler;
private GoogleMap mGoogleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocalHandler = new Handler();
previousLatLon=new LatLng(45.320372, 2.460161);
//Initialize Marker once Google Map object is created
mMarkerOptions = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker_icon));
mMarkerOptions.position(previousLatLon);
mCurrentMarker = mGoogleMap.addMarker(mMarkerOptions);
}
/**
* Call this method to move marker in map to new location in map with updated location
* #param marker
* #param toPosition
* #param fromPosition
*/
public void animateMarker(final Marker marker, final LatLng toPosition,final LatLng fromPosition) {
final long duration = 500;
final Interpolator interpolator = new LinearInterpolator();
mLocalHandler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - mStartTime;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
marker.setPosition(toPosition);
marker.setAnchor(Constants.MAPANCHOR, Constants.MAPANCHOR);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(toPosition, ZOOMLEVEL));
if (t < 1.0) {
// Post again 16ms later.
mLocalHandler.postDelayed(this, 16);
} else {
marker.setVisible(true);
}
}
}
});
previousLatLon=toPosition;// reassign the previous location to current location
}

How to add letters in google map markers A-Z using cluster marker

I have a map with 10 waypoints, I'm trying to add letters to specify the path, being "A" the starter point and "J" the ending point. How can I achieve that using clustermarkes, like the image below? this is my code so far:
public class MapaViagem extends FragmentActivity implements ClusterManager.OnClusterClickListener<MyItem>, ClusterManager.OnClusterItemClickListener<MyItem> {
private GoogleMap googleMap;
private String rm_IdViagem;
private List<ClienteModel> mClienteModel = new ArrayList<ClienteModel>();
private List<EnderecoModel> mEnderecoModel = new ArrayList<EnderecoModel>();
private ArrayList<LatLng> coordList = new ArrayList<LatLng>();
private ArrayList<String> nomes = new ArrayList<String>();
private ViagemModel mViagemModel = new ViagemModel();
private ClusterManager<MyItem> mClusterManager;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
try {
Bundle parametros = getIntent().getExtras();
rm_IdViagem = parametros.getString("id_viagem");
Repositorio ca = new Repositorio(this);
mViagemModel = ca.getViagemPorId(Integer.valueOf(rm_IdViagem));
Repositorio cl = new Repositorio(this);
mClienteModel = cl.getClientesViagem(Integer.valueOf(rm_IdViagem));
String waypoints = "waypoints=optimize:true";
String coordenadas = "";
//if (mClienteModel != null) {
//for (int i = 0; i < mClienteModel.size(); i++) {
Repositorio mRepositorio = new Repositorio(this);
//mEnderecoModel = mRepositorio.getListaEnderecosDoCliente(Integer.valueOf(mClienteModel.get(i).getClientes_id()));
mEnderecoModel = mRepositorio.getListaEnderecosDaViagem(Integer.valueOf(rm_IdViagem));
for (int j = 0; j < mEnderecoModel.size(); j++) {
float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 5));
coordenadas += "|" + latitude + "," + longitude;
nomes.add(String.valueOf(j));
coordList.add(new LatLng(latitude, longitude));
startDemo();
addItems(coordList, nomes);
mClusterManager.cluster();
}
String sensor = "sensor=false";
String params = waypoints + coordenadas + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyClusterRenderer extends DefaultClusterRenderer<MyItem> {
public MyClusterRenderer(Context context, GoogleMap map,
ClusterManager<MyItem> clusterManager) {
super(context, map, clusterManager);
}
#Override
protected void onBeforeClusterItemRendered(MyItem item, MarkerOptions markerOptions) {
super.onBeforeClusterItemRendered(item, markerOptions);
markerOptions.title(String.valueOf(item.getName()));
}
#Override
protected void onClusterItemRendered(MyItem clusterItem, Marker marker) {
super.onClusterItemRendered(clusterItem, marker);
}
#Override
protected boolean shouldRenderAsCluster(Cluster<MyItem> cluster) {
return cluster.getSize() > 10;
}
}
public void startDemo() {
mClusterManager = new ClusterManager<MyItem>(MapaViagem.this, googleMap);
// mClusterManager.setAlgorithm(new NonHierarchicalDistanceBasedAlgorithm<MyItem>());
mClusterManager.setRenderer(new MyClusterRenderer(MapaViagem.this, googleMap, mClusterManager));
googleMap.setOnCameraChangeListener(mClusterManager);
googleMap.setOnMarkerClickListener(mClusterManager);
mClusterManager.setOnClusterClickListener(this);
mClusterManager.setOnClusterItemClickListener(this);
}
private class ReadTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(MapaViagem.this);
// setup your dialog here
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Traçando Rotas");
dialog.setCancelable(true);
dialog.show();
}
#Override
protected String doInBackground(String... url) {
String data = "";
try {
HttpConnection http = new HttpConnection();
data = http.readUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
PathJSONParser parser = new PathJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
ArrayList<LatLng> points = null;
PolylineOptions polyLineOptions = null;
// traversing through routes
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = routes.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
polyLineOptions.addAll(points);
polyLineOptions.width(4);
polyLineOptions.color(Color.BLUE);
}
googleMap.addPolyline(polyLineOptions);
dialog.dismiss();
}
}
#Override
public boolean onClusterClick(Cluster<MyItem> cluster) {
// Show a toast with some info when the cluster is clicked.
String firstName = cluster.getItems().iterator().next().name;
Toast.makeText(this, cluster.getSize() + " (including " + firstName + ")", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onClusterItemClick(MyItem item) {
return false;
}
private void addItems(List<LatLng> markers, List<String> nomes) {
for (int i = 0; i < markers.size(); i++) {
MyItem offsetItem = new MyItem(markers.get(i), nomes.get(i));
mClusterManager.addItem(offsetItem);
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
EDIT:
I'm looking for a solution where I don't need to import a static group of images to my project. I was trying to use the Dynamic icons from google
#Override
protected void onBeforeClusterItemRendered(final MyItem item, final MarkerOptions markerOptions) {
super.onBeforeClusterItemRendered(item, markerOptions);
Runnable runnable = new Runnable() {
public void run() {
try {
markerOptions.title(String.valueOf(item.getName()));
//markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
URL myurl = new URL("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=B%7CFF0000%7CCCCCCC");
Bitmap bmp = BitmapFactory.decodeStream(myurl.openConnection().getInputStream());
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bmp));
} catch (Exception e) {
e.printStackTrace();
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
}
Simple Way is https://code.google.com/p/google-maps-icons/wiki/NumericIcons Follow this link and use icon that, you just need change drawable image what ever when you need
private void addMarkers() {
if (googleMap != null) {
final LatLng WALL_STREET = new LatLng(lat_map, lng_map);
// marker using custom image
googleMap.addMarker(new MarkerOptions()
.position(WALL_STREET)
.title(address_location)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_carmap)));
googleMap
.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String uri = "geo:" + lat_map + "," + lng_map;
startActivity(new Intent(
android.content.Intent.ACTION_VIEW, Uri
.parse(uri)));
}
});
}
}

Move Map in Android V2

I have implemented Google maps v2 for Android app. My location, marker everything is showing fine, but when I am on move OnMylocationChange is called and marker is updated, but I have to scroll up or down as the view of my location goes off the map.
How do I update my map to scroll with my current location? Like Google Maps App.
#Override
public void onMyLocationChange(Location location)
{
if (markermylocation != null)
{
markermylocation.remove();
}
curlat = location.getLatitude();
curlong = location.getLongitude();
myLocation(curlat, curlong, username, imageURL, ZOOMVALUE);
}
private void myLocation(double lat, double lng, String name, String url, float zoom)
{
if(firsttime == 1)
{
LatLng ll = new LatLng(lat,lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
googleMap.animateCamera(update);
firsttime = 0;
}
final String uname = name;
curlat = lat;
curlong = lng;
Picasso.with(getActivity()).load(url).resize(120, 120).transform(transformation).into(new Target()
{
#Override
public void onBitmapFailed(Drawable arg0)
{
markerOptionsmylocaiton = new MarkerOptions().position(new LatLng(curlat, curlong)).icon(BitmapDescriptorFactory.fromResource(R.drawable.profilepic)).title(uname).anchor(0.5f, 1f);
markermylocation = googleMap.addMarker(markerOptionsmylocaiton);
}
#Override
public void onBitmapLoaded(Bitmap b, LoadedFrom arg1)
{
bitmapMarkermylocation = BitmapDescriptorFactory.fromBitmap(b);
if(b != null)
{
markerOptionsmylocaiton = new MarkerOptions().position(new LatLng(curlat, curlong)).icon(bitmapMarkermylocation).title(uname).anchor(0.5f, 1f);
}
else
{
markerOptionsmylocaiton = new MarkerOptions().position(new LatLng(curlat, curlong)).icon(BitmapDescriptorFactory.fromResource(R.drawable.profilepic)).title(uname).anchor(0.5f, 1f);
}
markermylocation = googleMap.addMarker(markerOptionsmylocaiton);
}
#Override
public void onPrepareLoad(Drawable arg0)
{
}
});
}
Thanks!
I think you just have to remove the if (firsttime == 1) conditional, then the map should recenter whenever your location is updated.
LatLng ll = new LatLng(lat,lng);
CameraUpdate update = null;
if(firsttime == 1) {
update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
firsttime = 0;
} else {
update = CameraUpdateFactory.newLatLng(ll);
}
googleMap.animateCamera(update);
is there a reason you have that in there?
as mentioned in spec:
CameraUpdateFactory is a class containing methods for creating CameraUpdate objects that change a map's camera. To modify the map's camera, call animateCamera(CameraUpdate), animateCamera(CameraUpdate, GoogleMap.CancelableCallback) or moveCamera(CameraUpdate), using a CameraUpdate object created with this class.
read more
so when you are implementing this :
markermylocation = googleMap.addMarker(markerOptionsmylocaiton);
take care of camera move with this methods:
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

update polyline according to the user moving android googleMaps v2

I have googleMap (v2) with polyline that presents a route between the user current location and the destination point. Now, I want to update the polyline according to the user moving.
I tried to redrawing the whole polyline when location is changed but the polyline is flickering.
I didn't find any appropriate function in the PolylineOptions class (the function add() is only to add a vertex but not to update or remove)
do you have any idea how to update the polyline ???
thank you for giving your time.
The only way as of version 3.1.36:
List<LatLng> points = polyline.getPoints();
points.add(newPoint);
polyline.setPoints(points);
Hopefully the API will be enhanced in later versions.
*I have already done working on updating polyline path without removing the polyline. We can do this by changing the points of that polyline. Check below code.
This is the logic of setting new points to polyline.
/*Here the routes contain the points(latitude and longitude)*/
for (int i = 0; i < routes.size(); i++) {
Route route = routes.get(i);
if(polyline_path != null){
polyline_path.setPoints(route.points);
}
}
Detail Explanation:
private GoogleMap map_object;
private Marker marker_driver;
private Marker marker_drop_off;
private Polyline polyline_path;
private PolylineOptions polylineOptions_path;
...
...
...
/*HelperDirectionFinder is a class that I create to call google API and I used this
class to get directions routes*/
/*I have created Service, and I'm calling this lines below after 5 sec. to get the
updated routes from google API.*/
HelperDirectionFinder directionFinder = new HelperDirectionFinder(
JobEndScreen.this, source, destinations);
try {
directionFinder.showDirection();
} catch (UnsupportedEncodingException e) {
HelperProgressDialog.closeDialog();
}
...
...
...
#Override
public void onDirectionFinderStart() {
if(polylineOptions_path == null){
HelperProgressDialog.showDialog(getActivity(), "", getString(R.string.text_loading));
}
}
/*This interface method is called after getting routes from google API.*/
/*Here the routes contains the list of path or routes returned by Google Api*/
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
HelperProgressDialog.closeDialog();
/*When polylineOptions_path is null it means the polyline is not drawn.*/
/*If the polylineOptions_path is not null it means the polyline is drawn on map*/
if(polylineOptions_path == null){
for (Route route : routes) {
polylineOptions_path = new PolylineOptions().
geodesic(true).
color(ContextCompat.getColor(getActivity(), R.color.color_bg_gray_dark)).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions_path.add(route.points.get(i));
polyline_path = map_object.addPolyline(polylineOptions_path);
}
}
else {
for (int i = 0; i < routes.size(); i++) {
Route route = routes.get(i);
if(polyline_path != null){
polyline_path.setPoints(route.points);
}
}
}
}
//Declare on global
PolylineOptions polyOptions, polyOptions2;
Polyline polyline2;
List<LatLng> ltln;
private Double lat_decimal = 0.0,lng_decimal=0.0;
//initialize
ltln = new ArrayList<>();
//if you are using routing library
compile 'com.github.jd-alexander:library:1.0.7'
#Override
public void onRoutingSuccess(ArrayList<Route> arrayList, int i) {
//Add this code snippet on onRoutingSuccess to store latlan list
ltln = new ArrayList<>();
System.out.println("-----arrayList------" + arrayList.get(0).getPoints());
ltln = arrayList.get(0).getPoints();
// NOTE here already we draw polyLine 1
}
//below mentioned how to update polyline
private void UpdatePoliline(){
System.out.println("-------runnablePolyline-------"+ltln.size());
try {
if (ltln.size() > 0) {
for (int i = 0; i < ltln.size(); i++) {
ltln.remove(i);
if (CalculationByDistance(ltln.get(i), new LatLng(lat_decimal, lng_decimal)) >= 10) {
break;
}
}
polyOptions2 = new PolylineOptions();
polyOptions2.color(getResources().getColor(R.color.app_color));
polyOptions2.width(7);
polyOptions2.addAll(ltln);
if (polyline2 == null) {
polyline2 = googleMap.addPolyline(polyOptions2);
if (polyLines.size() > 0) {
for (Polyline poly : polyLines) {
poly.remove();
}
}
polyLines.add(polyline2);
if (polyline != null) {
polyline.remove();
polyline = null;
}
} else {
polyline = googleMap.addPolyline(polyOptions2);
if (polyLines.size() > 0) {
for (Polyline poly : polyLines) {
poly.remove();
}
}
polyLines.add(polyline);
if (polyline2 != null) {
polyline2.remove();
polyline2 = null;
}
}
System.out.println("=====waypoints new===" + ltln);
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
// Calculating distance between 2 points
public float CalculationByDistance(LatLng StartP, LatLng EndP) {
Location locationA = new Location("Source");
locationA.setLatitude(StartP.latitude);
locationA.setLongitude(StartP.longitude);
Location locationB = new Location("Destination");
locationB.setLatitude(EndP.latitude);
locationB.setLongitude(EndP.longitude);
float distance = locationA.distanceTo(locationB);
return distance;
}
//Redraw Polyline vehicle is not in current polyline with particular distance
if (ltln.size() > 0) {
if (PolyUtil.isLocationOnPath(new LatLng(currentlat, currentLon), ltln, false, 60.0f) ){
System.out.println("===tolarance===" + true);
} else {
//Redraw Polyline
}
}
UpdatePoliline();

Categories

Resources