how to use polyline in google maps in android? - android

public class map2 extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener {
private static final String TAG =null ;
private GoogleMap mGoogleMap;
private Geocoder mGeocoder;
String Startlongitude,Endlongitude;
String Startlattitude,Endlattitude;
double lon,Eat,Elot;
double lat;
LatLng latlon,latlon2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mSupportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mSupportMapFragment.getMapAsync(this);
mGeocoder = new Geocoder(this, Locale.getDefault());
Bundle b = getIntent().getExtras();
String Array=b.getString("ITEM_EXTRA");
String Tripname = getIntent().getExtras().getString("Trip");
List<LatLng> routeArray = new ArrayList<>();
try {
JSONArray jO=new JSONArray(Array);
for(int i=0;i<jO.length();i++)
{
JSONObject tripObject=jO.getJSONObject(i);
String Trips=tripObject.getString("TripNO");
JSONObject msg=tripObject.getJSONObject("Trips");
if(Trips.equals(Tripname))
{
JSONArray msgObject=msg.getJSONArray("Trip1");
for(int j=0;j<msgObject.length();j++)
{
JSONObject d=msgObject.getJSONObject(j);
Startlongitude=d.getString("SfltLogitude");
Startlattitude=d.getString("Sfltlattitude");
Endlongitude = d.getString("EfltLogitude");
Endlattitude = d.getString("Efltlattitude");
Eat=Double.parseDouble(Endlattitude.trim());
Elot=Double.parseDouble(Endlongitude.trim());
lat=Double.parseDouble(Startlattitude.trim());
lon=Double.parseDouble(Startlongitude.trim());
latlon= new LatLng(lat, lon);
latlon2=new LatLng(Eat,Elot);
PolylineOptions polyLineOptions = new PolylineOptions();
polyLineOptions.addAll(latlon,latlon2);
polyLineOptions.width(2);
polyLineOptions.color(Color.BLUE);
mGoogleMap.addPolyline(polyLineOptions);
break;
}
}
else{
String task=tripObject.getString("Trips");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.normal:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.satellite:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.terrain:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.hybrid:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
case R.id.none:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
}
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.setOnMyLocationChangeListener(this);
}
#Override
public void onMyLocationChange(Location location) {
}
}
here i have fetch LAttitude and Longitude from JsonServer and also converted it into doubles......but iam unable to plot the path in google map??..IT is showing me this ERROR" Polyline com.google.android.gms.maps.GoogleMap.addPolyline(com.google.android.gms.maps.model.PolylineOptions)' on a null object reference"

You are setting polyline on the map when map is not yet ready. So move you code of setting polyline in onMapReady() method.
Like :
public class map2 extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener {
private static final String TAG =null ;
private GoogleMap mGoogleMap;
private Geocoder mGeocoder;
String Startlongitude,Endlongitude;
String Startlattitude,Endlattitude;
double lon,Eat,Elot;
double lat;
LatLng latlon,latlon2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mSupportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mSupportMapFragment.getMapAsync(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.normal:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.satellite:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.terrain:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.hybrid:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
case R.id.none:
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
}
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.setOnMyLocationChangeListener(this);
mGeocoder = new Geocoder(this, Locale.getDefault());
Bundle b = getIntent().getExtras();
String Array=b.getString("ITEM_EXTRA");
String Tripname = getIntent().getExtras().getString("Trip");
List<LatLng> routeArray = new ArrayList<>();
try {
JSONArray jO=new JSONArray(Array);
for (int i = 0; i < jO.length(); i++)
{
JSONObject tripObject=jO.getJSONObject(i);
String Trips = tripObject.getString("TripNO");
JSONObject msg = tripObject.getJSONObject("Trips");
if (Trips.equals(Tripname))
{
JSONArray msgObject=msg.getJSONArray("Trip1");
for (int j = 0; j < msgObject.length(); j++)
{
JSONObject d = msgObject.getJSONObject(j);
Startlongitude = d.getString("SfltLogitude");
Startlattitude = d.getString("Sfltlattitude");
Endlongitude = d.getString("EfltLogitude");
Endlattitude = d.getString("Efltlattitude");
Eat=Double.parseDouble(Endlattitude.trim());
Elot=Double.parseDouble(Endlongitude.trim());
lat = Double.parseDouble(Startlattitude.trim());
lon = Double.parseDouble(Startlongitude.trim());
latlon = new LatLng(lat, lon);
latlon2 = new LatLng(Eat,Elot);
PolylineOptions polyLineOptions = new PolylineOptions();
polyLineOptions.addAll(latlon,latlon2);
polyLineOptions.width(2);
polyLineOptions.color(Color.BLUE);
mGoogleMap.addPolyline(polyLineOptions);
break;
}
}
else {
String task = tripObject.getString("Trips");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onMyLocationChange(Location location) {
}
}

Related

android studio:java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

I'm having a problem with my code. Displays the message: java.lang.NullPointerException: Attempt to invoke the interface method 'int java.util.List.size ()' on a null object reference. My code is:`
public class MainActivity extends FragmentActivity implements GoogleMap.OnMyLocationButtonClickListener, OnMyLocationClickListener, OnMapReadyCallback {
private GoogleMap maps;
ArrayList<LatLng> markerPoints=new ArrayList<>();
MarkerOptions markerOptions;
MarkerOptions markerOpt;
LatLng latLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//parapobh sto SupportMapFragment ths Activity_main
SupportMapFragment fm = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
/* lhpsh xarth gia to SupportMapFragment */
fm.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
maps = googleMap;
LatLng Greece = new LatLng(37.97, 23.73);
//googleMap.addMarker(new MarkerOptions().position(Greece).title("Marker in Greece"));
//googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Greece,16));
Button btn_find = (Button) findViewById(R.id.btn_find);
OnClickListener findClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
EditText etLocation = (EditText) findViewById(R.id.et_location);
String location = etLocation.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
};
btn_find.setOnClickListener(findClickListener);
Button btn_go=(Button) findViewById(R.id.btn_go);
OnClickListener goClickListener=new OnClickListener() {
#Override
public void onClick(View v) {
EditText etDieuthinsh=(EditText) findViewById(R.id.et_dieuthinsh);
String dieuthinsh=etDieuthinsh.getText().toString();
if(dieuthinsh!=null && !dieuthinsh.equals("")){
new GeocoderTask1().execute(dieuthinsh);
}
}
};
btn_go.setOnClickListener(goClickListener);
}
private class GeocoderTask extends AsyncTask<String,Void,List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address>addresses=null;
try {
addresses = geocoder.getFromLocationName(locationName[0], 8);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address>addresses) {
if (addresses==null||addresses.size()==0) {
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
maps.clear();
//try {
for (int t = 0; t < addresses.size(); t++) {
Address address = (Address) addresses.get(t);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s,%s", address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
/**
* for the start location,the color of marker is Green and*
* for the end location, the color of marker is Red
*/
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
//prosthesh neou deikth sto GoogleMaps Android API V2
markerOptions.title(addressText);
maps.addMarker(markerOptions);
if (t == 0)
maps.animateCamera(CameraUpdateFactory.newLatLng(latLng));
if (markerPoints.size() == 1) {
//lhpsh URL sto Google Directions API
String url = getDirectionsUrls(markerPoints.get(0));
DownloadTask downloadTask = new DownloadTask();
//xekinhste thn lhpsh dedomenwn json apo to Google Directions API
downloadTask.execute(url);
}
}
//} catch(NullPointerException e){
// e.printStackTrace();
// }
}
}
private class GeocoderTask1 extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... dieuthinshName) {
Geocoder geocoders = new Geocoder(getBaseContext());
List<Address> dieuts = null;
try {
dieuts = geocoders.getFromLocationName(dieuthinshName[0], 8);
} catch (IOException e) {
e.printStackTrace();
}
return dieuts;
}
#Override
protected void onPostExecute(List<Address> dieuts) {
if (dieuts == null || dieuts.size() == 0) {
Toast.makeText(getBaseContext(), "No Dieuthinsh found", Toast.LENGTH_SHORT).show();
}
maps.clear();
//try{
for (int k = 0; k < dieuts.size(); k++) {
Address address1 = (Address) dieuts.get(k);
latLng = new LatLng(address1.getLatitude(), address1.getLongitude());
String address1Text = String.format("%s,%s", address1.getMaxAddressLineIndex() > 0 ? address1.getAddressLine(0) : "", address1.getCountryName());
markerOpt = new MarkerOptions();
markerOpt.position(latLng);
markerOpt.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
markerOpt.title(address1Text);
maps.addMarker(markerOpt);
if (k == 0)
maps.animateCamera(CameraUpdateFactory.newLatLng(latLng));
if(markerPoints.size()==2) {
//lhpsh URL sto Google Directions API
String url1 = getDirectionsUrl(markerPoints.get(1));
DownloadTask1 downloadTask1 = new DownloadTask1();
//xekinhste thn lhpsh dedomenwn json apo to Google Directions API
downloadTask1.execute(url1);
}
}
// } catch (NullPointerException e) {
// e.printStackTrace();
//}
}
}
the answers that exist on the site do not solve the problem.
Instead of declaring List<Address>addresses=null; do this
List<Address>addresses = new ArrayList<>();
the same with List<Address> dieuts = null;
List<Address> dieuts = new ArrayList<>();
this should solve the problem

How to show infowindow without cluster click

I have little problem of Cluster and Custom InfoWindow.
I don't want to show Infowindow when i click cluster.
But my application is show Infowindow when i click clusterItem and click Cluter. It show last click ClusterItem's Infowindow.
Code :
public class MapsLActivity extends FragmentActivity implements OnMapReadyCallback, ClusterManager.OnClusterItemClickListener<House>, GoogleMap.OnMapClickListener, ClusterManager.OnClusterClickListener<House>{
private GoogleMap mMap;
private View infoWindow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_k);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
ClusterManager<House> mClusterManager = new ClusterManager<>(this, mMap);
mMap.setOnMapClickListener(this);
mMap.setOnMarkerClickListener(mClusterManager);
mMap.setOnCameraChangeListener(mClusterManager);
AssetManager assetManager = getResources().getAssets();
try {
AssetManager.AssetInputStream ais = (AssetManager.AssetInputStream) assetManager.open("yb_edu.json");
BufferedReader br = new BufferedReader(new InputStreamReader(ais));
StringBuilder sb = new StringBuilder();
int bufferSize = 1024 * 1024;
char readBuf[] = new char[bufferSize];
int resultSize = 0;
while ((resultSize = br.read(readBuf)) != -1) {
if (resultSize == bufferSize) {
sb.append(readBuf);
} else {
for (int i = 0; i < resultSize; i++) {
sb.append(readBuf[i]);
}
}
}
String jString = sb.toString();
JSONObject object = new JSONObject(jString);
JSONArray list = new JSONArray(object.getString("yb_edu"));
for (int i = 0; i < list.length(); i++) {
JSONObject inside = list.getJSONObject(i);
String title = inside.getString("title");
String lats = inside.getString("lat");
String lngs = inside.getString("lng");
double lat = Double.parseDouble(lats);
double lng = Double.parseDouble(lngs);
LatLng position = new LatLng(lat, lng);
Log.v("###", "postion : " + position);
Log.v("##i=##", String.valueOf(i));
i++;
mClusterManager.addItem(new House(position, title));
}
mClusterManager.cluster(); //클러스터 새로고침
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
mClusterManager.setOnClusterItemClickListener(this);
mClusterManager.setOnClusterClickListener(this);
}
#Override
public boolean onClusterItemClick(final House house) {
Toast.makeText(this, "onClusterItemClick", Toast.LENGTH_SHORT).show();
LatLng latLng = house.getLatLng();
Log.v("##", "LatLng : " + latLng);
infoWindow = getLayoutInflater().inflate(R.layout.markerinfo, null);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
((TextView)infoWindow.findViewById(R.id.tx_infoWindowTitle)).setText(house.getTitle());
((TextView)infoWindow.findViewById(R.id.tx_infoWindowContent)).setText(house.getLatLng().toString());
return infoWindow;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
});
return false;
}
#Override
public boolean onClusterClick(Cluster<House> cluster) {
mMap.moveCamera(CameraUpdateFactory.zoomIn());
Toast.makeText(this, "onClusterClick", Toast.LENGTH_SHORT).show();
return false;
}
#Override
public void onMapClick(LatLng latLng) {
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
Finally i resolve it....
public class MapsPActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnCameraMoveListener {
private GoogleMap mMap;
private float pastZoom = 0;
private ArrayList<House> edulList;
private int clusters = 0;
private int marks = 0;
private View infoWindow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_m);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
edulList = new ArrayList<>();
addEdu();
mMap.setOnMarkerClickListener(null);
mMap.setInfoWindowAdapter(null);
mMap.setOnCameraMoveListener(this);
}
private void addEdu() {
try {
AssetManager assetManager = getResources().getAssets();
AssetManager.AssetInputStream ais = (AssetManager.AssetInputStream) assetManager.open("list.json");
BufferedReader br = new BufferedReader(new InputStreamReader(ais));
StringBuilder sb = new StringBuilder();
int bufferSize = 1024 * 1024;
char readBuf[] = new char[bufferSize];
int resultSize = 0;
while ((resultSize = br.read(readBuf)) != -1) {
if (resultSize == bufferSize) {
sb.append(readBuf);
} else {
for (int i = 0; i < resultSize; i++) {
sb.append(readBuf[i]);
}
}
}
String jString = sb.toString();
JSONObject object = new JSONObject(jString);
JSONArray list = new JSONArray(object.getString("list"));
for (int i = 0; i < list.length(); i++) {
JSONObject inside = list.getJSONObject(i);
String title = inside.getString("title");
String lats = inside.getString("lat");
String lngs = inside.getString("lng");
double lat = Double.parseDouble(lats);
double lng = Double.parseDouble(lngs);
LatLng position = new LatLng(lat, lng);
Log.v("###", lats + ", " + lngs + ", " + title);
Log.v("##i=##", String.valueOf(i));
edulList.add(new House(position, title));
i++;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void createMarker() {
mMap.clear();
mMap.setOnMarkerClickListener(null);
mMap.setInfoWindowAdapter(null);
MarkerOptions markerOptions = new MarkerOptions();
for (int i = 0; i < edulList.size(); i++) {
LatLng position = edulList.get(i).getLatLng();
String title = edulList.get(i).getTitle();
markerOptions.position(position);
markerOptions.title(title);
mMap.addMarker(markerOptions).hideInfoWindow();
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
infoWindow = getLayoutInflater().inflate(R.layout.markerinfo, null);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
((TextView)infoWindow.findViewById(R.id.tx_infoWindowTitle)).setText(marker.getTitle());
((TextView)infoWindow.findViewById(R.id.tx_infoWindowContent)).setText(marker.getPosition().toString());
return infoWindow;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
});
return false;
}
});
}
private void createCluster() {
mMap.clear();
mMap.setOnMarkerClickListener(null);
mMap.setInfoWindowAdapter(null);
ClusterManager mClusterManager = new ClusterManager<>(this, mMap);
for (int i = 0; i < edulList.size(); i++) {
LatLng position = edulList.get(i).getLatLng();
String title = edulList.get(i).getTitle();
mClusterManager.addItem(edulList.get(i));
}
mClusterManager.cluster();
mMap.setOnMarkerClickListener(mClusterManager);
mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener() {
#Override
public boolean onClusterItemClick(final ClusterItem clusterItem) {
infoWindow = getLayoutInflater().inflate(R.layout.markerinfo, null);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
((TextView)infoWindow.findViewById(R.id.tx_infoWindowTitle)).setText(marker.getTitle());
((TextView)infoWindow.findViewById(R.id.tx_infoWindowContent)).setText(marker.getPosition().toString());
return infoWindow;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
});
return false;
}
});
mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener() {
#Override
public boolean onClusterClick(Cluster cluster) {
mMap.setInfoWindowAdapter(null);
mMap.moveCamera(CameraUpdateFactory.zoomIn());
return false;
}
});
}
#Override
public void onCameraMove() {
CameraPosition cameraPosition = mMap.getCameraPosition();
float zoom = cameraPosition.zoom;
Log.v("##", "" + pastZoom + " / " + zoom);
if (pastZoom == zoom) {
} else {
if (zoom < 13) {
if(clusters == 0){
createCluster();
marks = 0;
clusters = 1;
}
} else {
if(marks == 0){
createMarker();
marks = 1;
clusters = 0;
}
}
pastZoom = zoom;
}
}
}

I want to show Multiple Markers at runtime on the screen which have different id's that received from the server

I want to show Multiple Markers at runtime on the screen which have different id's that received from the server and longitude and latitude also change or save on server.
** Code work fine in 1 to 1 tracking but not work on multiple Id's PLEASE HELP ME..**
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
static final LatLng HAMBURG1 = new LatLng(74.3226214, 31.5003567);
static final LatLng HAMBURG = new LatLng(74.3229122, 31.5003193);
private static MainActivity instance;
private static final int ERROR_DIALOG_REQUEST = 9001;
GoogleMap mMap;
int i = 0;
protected static String longitudeServer;
protected static String latitudeServer;
protected static String uniqueidSserver;
protected static String latitudeLast;
protected static String logitudeLast;
protected static String uniqueidlast;
protected static double latilasdoublet;
protected static double longilastdouble;
double latitude = 0;
double longitude = 0;
private GoogleApiClient mLocationClient;
private com.google.android.gms.location.LocationListener mListener;
private Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (servicesOK()) {
setContentView(R.layout.activity_map);
if (initMap()) {
// gotoLocation(SEATTLE_LAT, SEATTLE_LNG, 15);
mLocationClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mLocationClient.connect();
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(this, "Map not connected!", Toast.LENGTH_SHORT).show();
}
} else {
setContentView(R.layout.activity_main);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//Add menu handling code
switch (id) {
case R.id.mapTypeNone:
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
case R.id.mapTypeNormal:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.mapTypeSatellite:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.mapTypeTerrain:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.mapTypeHybrid:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
}
return super.onOptionsItemSelected(item);
}
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog =
GooglePlayServicesUtil.getErrorDialog(isAvailable, this, ERROR_DIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, "Can't connect to mapping service", Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap() {
if (mMap == null && i == 0) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
return (mMap != null);
}
private void gotoLocation(double lat, double lng, float zoom) {
LatLng latLng = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
mMap.moveCamera(update);
}
public void showCurrentLocation(MenuItem item) {
Location currentLocation = LocationServices.FusedLocationApi
.getLastLocation(mLocationClient);
if (currentLocation == null) {
Toast.makeText(this, "Couldn't connect!", Toast.LENGTH_SHORT).show();
} else {
LatLng latLng = new LatLng(
currentLocation.getLatitude(),
currentLocation.getLongitude()
);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
latLng, 10
);
mMap.animateCamera(update);
}
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show();
mListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(MainActivity.this, "Location : " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_LONG).show();
if (i == 0) {
gotoLocation(location.getLatitude(), location.getLongitude(), 15);
i = 1;
}
AppUtill.UniqueId();
if (AppStatus.getInstance(getContext()).isOnline()) {
new JSONAsyncTask().execute("http://ip/hajjapi/api/GPSLocator/GetLocations");
} else {
Toast.makeText(MainActivity.this, "Turn On your WIFI ", Toast.LENGTH_LONG).show();
}
///HOW I CAN DISPLAY MULTIPLE MARKERS WHICH HAVE DIFFERENT ID'S RECEIVED FROM THE SERVER PLEASE HELP ME PLEASE...
if (marker != null) {
marker.remove();
}
MarkerOptions options = new MarkerOptions().title("User Name").position(new LatLng(latilasdoublet, longilastdouble)).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
marker = mMap.addMarker(options);
}
};
LocationRequest request = LocationRequest.create();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setInterval(5000);
request.setFastestInterval(5000);
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, request, mListener);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void showcurrentLocation() {
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
i = 1;
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(data);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
longitudeServer = obj.getString("longi");
latitudeServer = obj.getString("lati");
uniqueidSserver = obj.getString("uniqueid");
}
////LAST LONGITUDE AND LATITUDE THAT RECEIVED FROM SERVER
List<String> longitude = Arrays.asList(longitudeServer);
logitudeLast = longitude.get(longitude.size() - 1);
System.out.println(logitudeLast + " logitude ");
List<String> latitude = Arrays.asList(latitudeServer);
latitudeLast = latitude.get(latitude.size() - 1);
System.out.println(latitudeLast + " latitude ");
List<String> uniqueid = Arrays.asList(uniqueidSserver);
uniqueidlast = uniqueid.get(uniqueid.size() - 1);
System.out.println(uniqueidlast + " unique id ");
latilasdoublet = Double.parseDouble(latitudeLast);
longilastdouble = Double.parseDouble(logitudeLast);
return true;
}
//------------------>>
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if (result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStop() {
super.onStop();
startService(new Intent(getContext(), Services.class));
}
public MainActivity() {
instance = this;
}
public static Context getContext() {
return instance;
}
}
you are using only two double variables for lat and lng. create an arrayList of LatLng objects. for all the urls you get in response, add the LatLng to the arrayList.
add a field
private ArrayList<LatLng> latLngList;
initialize in oncreate function
latLngList = new ArrayList<>();
instead of
latilasdoublet = Double.parseDouble(latitudeLast);
longilastdouble = Double.parseDouble(logitudeLast);
add
for(int i=0; i< latitude.size(); i++){
LatLng latLng = new LatLng(Double.parseDouble(latitude.get(i)), Double.parseDouble(longitude.get(i)));
latLngList.add(latLng);
}
in place of
MarkerOptions options = new MarkerOptions().title("User Name").position(new LatLng(latilasdoublet, longilastdouble)).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
marker = mMap.addMarker(options);
use
ArrayList<MarkerOptions> list = new ArrayList<>();
for (LatLng object : latLngList){
MarkerOptions options = new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
mMap.addMarker(options);
list.add(options); //if you want to keep track of all your markers
}
use mMap.clear() to clear all markers and clustering refer
More info on markers.

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

Google map V2 giving the address of previous touched location

I am using Google map v2 in my app. i am placing the marker where i click. when i click again on map the privios marke gone and new marker added. when i check the address then it shows me the address of removed marker. i.e it contains the the last touched location.
Please help me. How can i remove address as well as marker removed. Here is my code
public class Map extends FragmentActivity {
GoogleMap gMap;
static int loginCheck = 0;
GeoPoint p, currentLocationPixels;
ConnectionDetector conDec;
ArrayList<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
SharedPreferences prefs;
LatLng latLng;
MarkerOptions markerOptions;
EditText desc;
String addressText = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
prefs = getApplicationContext().getSharedPreferences("jam",
MODE_PRIVATE);
conDec = new ConnectionDetector(this);
SupportMapFragment smf = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
gMap = smf.getMap();
gMap.setMyLocationEnabled(true);
gMap.getUiSettings().setCompassEnabled(true);
// gMap.setTrafficEnabled(true);
gMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
// Getting the Latitude and Longitude of the touched location
latLng = arg0;
// Clears the previously touched position
gMap.clear();
addressText=null;
// Animating to the touched position
// gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
int caller = getIntent().getIntExtra("button", 0);
System.out.println(caller);
switch (caller) {
case R.id.btMap:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_darkblue)).title(addressText));
break;
case R.id.imageButton1:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_bue)).title(addressText));
break;
case R.id.imageButton2:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_green)).title(addressText));
break;
case R.id.imageButton3:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_light)).title(addressText));
break;
case R.id.imageButton4:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_purple)).title(addressText));
break;
case R.id.imageButton5:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_red)).title(addressText));
break;
case R.id.imageButton6:
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_yellow)).title(addressText));
break;
}
// Creating a marker
// markerOptions = new MarkerOptions();
// Setting the position for the marker
// markerOptions.position(latLng);
// Placing a marker on the touched position
// gMap.addMarker(markerOptions);
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng);
}
});
// ** Hide By Gaurav
// gMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
// #Override
// public void onInfoWindowClick(Marker marker) {
// System.out.println(marker.getPosition().latitude);
//
// Intent i = new Intent(Map.this, Detail.class);
// i.putExtra("lat", "" + marker.getPosition().latitude);
// i.putExtra("lng", "" + marker.getPosition().longitude);
// i.putExtra("title", marker.getTitle());
// i.putExtra("desc", marker.getSnippet());
// startActivity(i);
// }
// });
getInfo();
CameraPosition cp = new CameraPosition.Builder()
.target(new LatLng(Double.parseDouble("30.7353"), Double
.parseDouble("76.7911"))).zoom(16).build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
}
// ** Gaurav Work Start Here
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
// Finding address using reverse geocoding
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
//String addressText = "";
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
addressText = String.format(
"%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address.getLocality(),
address.getCountryName());
}
return addressText;
}
// #Override
// protected void onPostExecute(String addressText) {
//
// // This will be displayed on taping the marker
// markerOptions.title(addressText);
//
// // Placing a marker on the touched position
// gMap.addMarker(markerOptions);
//
// }
}}
I have solved this with. its my own mistake. it will help you.
public class Map extends FragmentActivity {
GoogleMap gMap;
static int loginCheck = 0;
GeoPoint p, currentLocationPixels;
ConnectionDetector conDec;
ArrayList<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
SharedPreferences prefs;
LatLng latLng;
MarkerOptions markerOptions;
EditText desc;
String selectedLocAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
prefs = getApplicationContext().getSharedPreferences("jam",
MODE_PRIVATE);
conDec = new ConnectionDetector(this);
SupportMapFragment smf = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
gMap = smf.getMap();
gMap.setMyLocationEnabled(true);
gMap.getUiSettings().setCompassEnabled(true);
// gMap.setTrafficEnabled(true);
// ** Gaurav Works Start Here
gMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
// Getting the Latitude and Longitude of the touched location
latLng = arg0;
// Clears the previously touched position
gMap.clear();
// Animating to the touched position
gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng);
}
});
// ** Hide By Gaurav
gMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
public void onInfoWindowClick(Marker marker) {
System.out.println(marker.getPosition().latitude);
Intent i = new Intent(Map.this, Detail.class);
startActivity(i);
}
});
getInfo();
CameraPosition cp = new CameraPosition.Builder()
.target(new LatLng(Double.parseDouble("30.7353"), Double
.parseDouble("76.7911"))).zoom(16).build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
}
// ** Gaurav Work Start Here
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
// Finding address using reverse geocoding
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
String addressText = "";
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
addressText = String.format("%s, %s, %s",address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),address.getCountryName());
}
} catch (IOException e) {
e.printStackTrace();
}
return addressText;
}
// #Override
protected void onPostExecute(String addressText) {
selectedLocAddress = addressText;
int caller = getIntent().getIntExtra("button", 0);
System.out.println(caller);
switch (caller) {
case R.id.btMap:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_darkblue)).title(selectedLocAddress));
System.out.println("selectedLocAddress");
break;
case R.id.imageButton1:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_bue)).title(selectedLocAddress));
break;
case R.id.imageButton2:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_green)).title(selectedLocAddress));
break;
case R.id.imageButton3:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_light)).title(selectedLocAddress));
break;
case R.id.imageButton4:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_purple)).title(selectedLocAddress));
break;
case R.id.imageButton5:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_red)).title(selectedLocAddress));
break;
case R.id.imageButton6:
gMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_annotation_yellow)).title(selectedLocAddress));
break;
}
//
// // This will be displayed on taping the marker
// markerOptions.title(addressText);
//
// // Placing a marker on the touched position
// gMap.addMarker(markerOptions);
//
}
}

Categories

Resources