Route directions for driving mode - android

I'm trying to implement a route direction for the points I have on my map, for doing that I'm using Polyline, the problem is, I managed to connect 2 points of the map, but I have an array of LatLng with 8 points, how would I connect all the points?:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
ArrayList<LatLng> coordList = new ArrayList<LatLng>();
ArrayList<String> nomes = new ArrayList<String>();
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));
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()));
for (int j = 0; j < mEnderecoModel.size(); j++) {
// 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);
final float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
final float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());
nomes.add(mClienteModel.get(i).getNome());
coordList.add(new LatLng(latitude, longitude));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 5));
mClusterManager = new ClusterManager<MyItem>(MapaViagem.this, googleMap);
mClusterManager.setRenderer(new MyClusterRenderer(MapaViagem.this, googleMap, mClusterManager));
googleMap.setOnCameraChangeListener(mClusterManager);
googleMap.setOnMarkerClickListener(mClusterManager);
//mClusterManager.setAlgorithm(new GridBasedAlgorithm<MyItem>());
addItems(coordList, nomes);
mClusterManager.cluster();
}
}
}
} 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);
//here you have access to the marker itself
}
#Override
protected boolean shouldRenderAsCluster(Cluster<MyItem> cluster) {
return cluster.getSize() > 1;
}
}

Use this example. This will help you to find solution.
http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/

Related

Drag polyline along with marker in openstreetmap?

I'm currently developing an android application that would allow users to draw Polylines with Markers or point in the polyline when user long press on points how to dragline with points move also line would be move on the map. how do I achieve this I drag marker but cant move marker
public class MainMapActivity extends AppCompatActivity {
GeoPoint startPoint;
MapView map;
Road road;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_map);
map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
GpsTracking gps=new GpsTracking(MainMapActivity.this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
startPoint = new GeoPoint(latitude, longitude);
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
// GeoPoint startPoint = new GeoPoint(48.13, -1.63);
IMapController mapController = map.getController();
mapController.setZoom(17);
mapController.setCenter(startPoint);
Marker startMarker = new Marker(map);
startMarker.setPosition(startPoint);
startMarker.setDraggable(true);
startMarker.setOnMarkerDragListener(new OnMarkerDragListenerDrawer());
startMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
map.getOverlays().add(startMarker);
//Set-up your start and end points:
RoadManager roadManager = new OSRMRoadManager(this);
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
waypoints.add(startPoint);
GeoPoint endPoint = new GeoPoint(31.382108, 74.260107);
waypoints.add(endPoint);
// retreive the road between those points:
Road road = roadManager.getRoad(waypoints);
// build a Polyline with the route shape:
Polyline polyline=new Polyline();
polyline.setOnClickListener(new Polyline.OnClickListener() {
#Override
public boolean onClick(Polyline polyline, MapView mapView, GeoPoint eventPos) {
return false;
}
});
Polyline roadOverlay = RoadManager.buildRoadOverlay(road);
//Polyline to the overlays of your map:
map.getOverlays().add(roadOverlay);
//Refresh the map!
map.invalidate();
//3. Showing the Route steps on the map
FolderOverlay roadMarkers = new FolderOverlay();
map.getOverlays().add(roadMarkers);
Drawable nodeIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.marker_node, null);
for (int i = 0; i < road.mNodes.size(); i++) {
RoadNode node = road.mNodes.get(i);
Marker nodeMarker = new Marker(map);
nodeMarker.setDraggable(true);
nodeMarker.setOnMarkerDragListener(new OnMarkerDragListenerDrawer());
nodeMarker.setPosition(node.mLocation);
nodeMarker.setIcon(nodeIcon);
//4. Filling the bubbles
nodeMarker.setTitle("Step " + i);
nodeMarker.setSnippet(node.mInstructions);
nodeMarker.setSubDescription(Road.getLengthDurationText(this, node.mLength, node.mDuration));
Drawable iconContinue = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_continue, null);
nodeMarker.setImage(iconContinue);
//4. end
roadMarkers.add(nodeMarker);
}
}
class OnMarkerDragListenerDrawer implements Marker.OnMarkerDragListener {
ArrayList<GeoPoint> mTrace;
Polyline mPolyline;
OnMarkerDragListenerDrawer() {
mTrace = new ArrayList<GeoPoint>(100);
mPolyline = new Polyline();
mPolyline.setColor(0xAA0000FF);
mPolyline.setWidth(2.0f);
mPolyline.setGeodesic(true);
map.getOverlays().add(mPolyline);
}
#Override public void onMarkerDrag(Marker marker) {
//mTrace.add(marker.getPosition());
}
#Override public void onMarkerDragEnd(Marker marker) {
mTrace.add(marker.getPosition());
mPolyline.setPoints(mTrace);
map.invalidate();
}
#Override public void onMarkerDragStart(Marker marker) {
//mTrace.add(marker.getPosition());
}
}
}
Does anyone know how I can achieve this? above is a snippet of my codes. Thanks!

How to join multiple markers on the map with arrow headed poly-line to show directions of travelling?

I am a newbie to the android and currently working on the Google-map API.
I am able to plot multiple markers on the map but want to join multiple markers with poly line.I have referred this for the directions concern but it is for two points only.
Below is the code for the Activity:
public class MainActivity extends AppCompatActivity {
// Google Map
private GoogleMap googleMap;
// latitude and longitude
double latitude;
double longitude;
String newtime;
ArrayList<LatLng> points;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
points = new ArrayList<LatLng>();
points.add(new LatLng(21.114369, 79.049423));
points.add(new LatLng(21.113913, 79.049203));
points.add(new LatLng(21.113478, 79.048736));
points.add(new LatLng(21.113002, 79.048592));
points.add(new LatLng(21.112857, 79.047315));
points.add(new LatLng(21.112997, 79.046741));
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.setMyLocationEnabled(true);
SimpleDateFormat sdfDateTime = new SimpleDateFormat("dd-MM-yy HH:mm:ss", Locale.US);
newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
// googleMap.addMarker(marker);
drawMarker(points);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
}
private void drawMarker(ArrayList<LatLng> l) {
// Creating an instance of MarkerOptions
for (int i = 0; i < l.size(); i++) {
latitude = l.get(i).latitude;
longitude = l.get(i).longitude;
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Bus")
.snippet(newtime);
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// Adding marker on the Google Map
googleMap.addMarker(marker);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(l.get(0).latitude, l.get(0).longitude)).zoom(18).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Please help/guide me to achieve the task.
~Thanks.
Modify your drawMarker() to the following:-
private void drawMarker(ArrayList<LatLng> l) {
// Creating an instance of MarkerOptions
PolylineOptions options = new PolylineOptions();
options.color(Color.RED);
for (int i = 0; i < l.size(); i++) {
options.add(l.get(i));
MarkerOptions marker = new MarkerOptions().position(l.get(i)).title("Bus")
.snippet(newtime);
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// Adding marker on the Google Map
googleMap.addMarker(marker);
}
googleMap.addPolyline(options);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(l.get(0).latitude, l.get(0).longitude)).zoom(18).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
Here it will add lines with red color, to change colors as your wish just modify the options.color().

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)));
}
});
}
}

Android setOnMarkerClickListener set title for each marker

I've implemented a clustermarker in my app, I have a list of LatLng that comes from my database, now I want to show the name of the clients as title when the user clicks on the marker,but when I click on the marker it shows me nothing, how can I achieve that, this is my code so far:
public class MapaViagem extends FragmentActivity {
private GoogleMap googleMap;
private String rm_IdViagem;
private List<ClienteModel> mClienteModel = new ArrayList<ClienteModel>();
private List<EnderecoModel> mEnderecoModel = new ArrayList<EnderecoModel>();
private ViagemModel mViagemModel = new ViagemModel();
private ClusterManager<MyItem> mClusterManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
ArrayList<LatLng> coordList = new ArrayList<LatLng>();
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));
int i;
for ( i = 0; i < mClienteModel.size(); i++) {
Repositorio mRepositorio = new Repositorio(this);
mEnderecoModel = mRepositorio.getListaEnderecosDoCliente(Integer.valueOf(mClienteModel.get(i).getClientes_id()));
System.out.println("NOMES " + mClienteModel.get(i).getNome());
for (int j = 0; j < mEnderecoModel.size(); j++) {
// 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);
final float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
final float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());
coordList.add(new LatLng(latitude, longitude));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 10));
// Initialize the manager with the context and the map.
// (Activity extends context, so we can pass 'this' in the constructor.)
mClusterManager = new ClusterManager<MyItem>(this, googleMap);
// Point the map's listeners at the listeners implemented by the cluster
// manager.
googleMap.setOnCameraChangeListener(mClusterManager);
googleMap.setOnMarkerClickListener(mClusterManager);
addItems(coordList);
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(final Marker marker) {
LatLng pos = marker.getPosition();
int arryListPosition = getArrayListPosition(pos);
return true;
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private int getArrayListPosition(LatLng pos) {
for (int i = 0; i < mEnderecoModel.size(); i++) {
if (pos.latitude == Double.parseDouble(mEnderecoModel.get(i).getLatitude().split(",")[0])) {
if (pos.longitude == Double.parseDouble(mEnderecoModel.get(i).getLongitude().split(",")[1]))
return i;
}
}
return 0;
}
private void addItems(List<LatLng> markers) {
for (int i = 0; i < markers.size(); i++) {
MyItem offsetItem = new MyItem(markers.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();
}
}
Not sure how you are initializing your Markers because you don't show that part of the code but put a title on it is done this way:
//You need a reference to a GoogleMap object
GoogleMap map = ... // get a map.
Marker marker = map.addMarker(new MarkerOptions()
.position(new LatLng(37.7750, 122.4183)) //Or whatever coordinate
.title("Your title")
.snippet("Extra info"));
And that's it, when you click it you'll see the info of that marker.
You can find more information here
EDIT
For the ClusterManagerI think you can find this answer helpful

Google map not display Marker

hi i have to implement Google map v2 in my application an it's perfect working. but my problem i have to send one Marker position from one activity to another activity and then add marker into Google map but i don't know it's not.
Post my code below.
public class BasicMapActivity extends FragmentActivity{
private GoogleMap mMap;
AlertMessages messages;
String latitude;
double lat = 0, lng = 0;
String longitude ;
String title = "", city = "";
static boolean is_back_pressed = false;
ImageView img;
GPSTracker gps;
RelativeLayout rel;
Marker Contactloc;
LatLng contactLoc;
Button ib_back;
static boolean is_window_pressed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo_new);
img = (ImageView) findViewById(R.id.popup_h);
img.setVisibility(View.INVISIBLE);
gps = new GPSTracker(getParent());
messages = new AlertMessages(getParent());
Bundle b = getIntent().getExtras();
title = b.getString("title");
city = b.getString("City");
latitude = b.getString("latitude");
longitude = b.getString("longitude");
back_layout=(LinearLayout)findViewById(R.id.back_lay);
ib_back=(Button)findViewById(R.id.ib_back_music);
System.out.println("Lat:::" + latitude);
System.out.println("Long:::" + longitude);
setUpMapIfNeeded();
ib_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
is_back_pressed = true;
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.onBackPressed();
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
try{
System.out.println("Map Pause state");
if(mMap!=null){
mMap.clear();
mMap=null;
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.onBackPressed();
}
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getParent());
if (status == ConnectionResult.SUCCESS) {
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true);
} else {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getParent(),
requestCode);
dialog.show();
}
}
protected LocationManager locationManager;
LatLng pos=null;
private void setUpMapIfNeeded() {
System.out.println("Setup If Needed");
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map1)).getMap();
mMap.setMyLocationEnabled(true);
boolean isInternetPresent = isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
Toast.makeText(getParent(), "Internet Connection Error!",Toast.LENGTH_SHORT).show();
//messages.showAlertDialog(getParent(),
// "Internet Connection Error",
//"Please connect to working Internet connection");
// stop executing code by return
// return;
} else {
locationManager = (LocationManager) getParent()
.getSystemService(LOCATION_SERVICE);
// getting GPS status
if (!locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showSettingsAlert();
}
if (gps.canGetLocation()) {
lat = gps.getLatitude();
lng = gps.getLongitude();
pos = new LatLng(lat, lng);
if (lat == 0.0 && lng == 0.0) {
Toast.makeText(getParent(), "Can't find location",
Toast.LENGTH_SHORT).show();
} else {
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.mark_blue))
.position(pos)
.title("Current Location"));
double trans = 0.3;
for (int k = 100; k <= 500;) {
// draw circle
int radiusM = k;
int d = k; // diameter
Bitmap bm = Bitmap.createBitmap(d, d,
Config.ARGB_8888);
Canvas c = new Canvas(bm);
Paint p = new Paint();
p.setColor(getResources().getColor(
android.R.color.darker_gray));
c.drawCircle(d / 2, d / 2, d / 2, p);
// generate BitmapDescriptor from circle
// Bitmap
BitmapDescriptor bmD = BitmapDescriptorFactory
.fromBitmap(bm);
// mapView is the GoogleMap
mMap.addGroundOverlay(new GroundOverlayOptions()
.image(bmD)
.position(pos, radiusM * 2,
radiusM * 2)
.transparency((float) trans));
k = k + 100;
trans = trans + 0.1;
}
}
} else {
Toast.makeText(getParent(), "Can't find location",
Toast.LENGTH_SHORT).show();
}
}
mMap.getUiSettings().setCompassEnabled(true);
mMap.setTrafficEnabled(true);
mMap.getUiSettings().setTiltGesturesEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
setUpMap();
} // Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
setUpMap();
}
}
private void setUpMap() {
System.out.println("Setup Map");
try{
contactLoc=new LatLng(latitude, longitude);
Contactloc=mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mark_red))
.position(new LatLng(latitude, longitude)).title(title)
.snippet(city));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longitude), 18.0f));
}catch(Exception ew){
ew.printStackTrace();
}
}
}
please some one help me!
Add Marker like below
Contactloc=mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mark_red))
.position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)).title(title)
.snippet(city));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longitude), 18.0f));
You need to Convert your latitude and longitude String values into Double. and AFAIK you said no not any error. your app defiantly crash over here with some logcat.

Categories

Resources