I'm having some issue with the following:
I have multiple markers on Google Maps. I've done this using a For loop that goes through an array of my objects and adds a marker for each of them. Markers show title and address. But now I need to make clickable InfoWindow (or just clickable Markers) which will display an AlertDialog containing additional information (description). But I can't get this to work. Alternatively, the data doesn't need to be displayed in an AlertDialog, I could also display it in a TextView.
Here's part of the code for displaying markers (this is a FragmentActivity):
...
Double longitude, latitude;
static LatLng coordinates;
GoogleMap supportMap;
String title, address;
BitmapDescriptor bdf;
ArrayList<GasStations> listGas = new ArrayList<GasStations>();
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
supportMap = fm.getMap();
...
if (listGas != null) {
for (int i = 0; i < listGas.size(); i++) {
longitude = listGas.get(i).getLongitude();
latitude = listGas.get(i).getLatitude();
naslov = listGas.get(i).getTitle();
adresa = listGas.get(i).getAddress() + " "
+ listGas.get(i).getLocation();
koordinate = new LatLng(latitude, longitude);
supportMap.addMarker(new MarkerOptions().position(koordinate)
.title(title).snippet(address).icon(bdf));
supportMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
coordinates, 10));
}
}
Markers show just fine and their InfoWindows display correct data. But now I want to display additional information based on which InfoWindow is clicked. If this can't be done via InfoWindow, can it be done by clicking on a particular marker?
You can create Custom Infowindow
GoogleMap googleMap;
Map.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker arg0) {
// Getting view from the layout file custom_window
View v = getLayoutInflater().inflate(R.layout.custom_window, null);
// Getting the position from the marker
LatLng latLng = arg0.getPosition();
TextView tvLat = (TextView) v.findViewById(R.id.lat);
TextView tvLng = (TextView) v.findViewById(R.id.lng);
tvLat.setText("Lat:" + latLng.latitude);
return v;
}
});
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
String add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = mapFragment.getMap();
googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
LatLng latLng = arg0.getPosition();
TextView tvLat = (TextView) v.findViewById(R.id.tv_lat);
TextView tvLng = (TextView) v.findViewById(R.id.tv_lng);
TextView loc = (TextView) v.findViewById(R.id.loc);
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if(addresses.size() > 0)
add = addresses.get(0).getAddressLine(0);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loc.setText(""+add);
tvLat.setText("" + latLng.latitude);
tvLng.setText(""+ latLng.longitude);
return v;
}
});
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
googleMap.clear();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(arg0);
googleMap.animateCamera(CameraUpdateFactory.newLatLng(arg0));
Marker marker = googleMap.addMarker(markerOptions);
marker.showInfoWindow();
}
});
googleMap.setOnInfoWindowClickListener(
new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getBaseContext(), "Info Window Clicked#" + marker.getId(),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
Toast.makeText(getApplicationContext(), "isGooglePlayServicesAvailable SUCCESS", Toast.LENGTH_SHORT).show();
}
else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, 1);
Toast.makeText(getApplicationContext(), "isGooglePlayServicesAvailable ERROR", Toast.LENGTH_SHORT).show();
}
}
}
Related
I would like to implement multiple polygons with an editable using a drag listener. I am able to draw the multiple polygons but I don't know how to make editable.
I am able to move marker for current polygon but when I try to move previous polygon’s marker app is crash. I tried with saving polygon list but I can not able to drag the marker.
please see my code HERE.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (readyToGo()) {
setContentView(R.layout.activity_maps);
// 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);
if (savedInstanceState == null) {
mapFragment.getMapAsync(this);
}
mapFragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
CameraUpdate center =
CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
-73.98180484771729));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
mMap.setIndoorEnabled(false);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
Marker marker = mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
marker.setTag(latLng);
markerList.add(marker);
points.add(latLng);
drawPolygon(points);
}
});
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
updateMarkerLocation(marker, false);
}
#Override
public void onMarkerDragEnd(Marker marker) {
updateMarkerLocation(marker, true);
}
});
}
public void closePolygon(View view) {
}
public void newPolygon(View view) {
//
points.clear();
markerList.clear();
polygon = null;
// mMap.clear();
}
private void updateMarkerLocation(Marker marker, boolean calculate) {
LatLng latLng = (LatLng) marker.getTag();
int position = points.indexOf(latLng);
points.set(position, marker.getPosition());
marker.setTag(marker.getPosition());
drawPolygon(points);
}
private void drawPolygon(List<LatLng> latLngList) {
if (polygon != null) {
polygon.remove();
}
polygonOptions = new PolygonOptions();
polygonOptions.addAll(latLngList);
polygon = mMap.addPolygon(polygonOptions);
}
}
Basically this approach keeps the markers and points as collections associated with each polygon. It simplifies things by assuming after 5 markers a new polygon is created (equivalent to an add polygon).
UPDATED: To use the "new polygon" button as defined in the layout in github. Button listener just sets a flag and instead of using a size=5 check replace the check with the flag.
A map from any marker to its corresponding list is maintained for use in the updateMarkerLocation method.
All of this is predicated on the fact that any marker has a unique id provided by the map API getId() which in practice is a string like "m7".
I've listed the parts updated:
// Map a marker id to its corresponding list (represented by the root marker id)
HashMap<String,String> markerToList = new HashMap<>();
// A list of markers for each polygon (designated by the marker root).
HashMap<String,List<Marker>> polygonMarkers = new HashMap<>();
// A list of polygon points for each polygon (designed by the marker root).
HashMap<String,List<LatLng>> polygonPoints = new HashMap<>();
// List of polygons (designated by marker root).
HashMap<String,Polygon> polygons = new HashMap<>();
// The active polygon (designated by marker root) - polygon added to.
String markerListKey;
// Flag used to record when the 'New Polygon' button is pressed. Next map
// click starts a new polygon.
boolean newPolygon = false;
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
CameraUpdate center =
CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
-73.98180484771729));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
mMap.setIndoorEnabled(false);
Button b = findViewById(R.id.bt_new_polygon);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
newPolygon = true;
}
});
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
Marker marker = mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
marker.setTag(latLng);
// Special case for very first marker.
if (polygonMarkers.size() == 0) {
polygonMarkers.put(marker.getId(),new ArrayList<Marker>());
// only 0 or 1 polygons so just add it to new one or existing one.
markerList = new ArrayList<>();
points = new ArrayList<>();
polygonMarkers.put(marker.getId(),markerList);
polygonPoints.put(marker.getId(),points);
markerListKey = marker.getId();
}
if (newPolygon) {
newPolygon = false;
markerList = new ArrayList<>();
points = new ArrayList<>();
polygonMarkers.put(marker.getId(),markerList);
polygonPoints.put(marker.getId(),points);
markerListKey = marker.getId();
}
markerList.add(marker);
points.add(latLng);
markerToList.put(marker.getId(),markerListKey);
drawPolygon(markerListKey, points);
}
});
private void updateMarkerLocation(Marker marker, boolean calculate) {
// Use the marker to figure out which polygon list to use...
List<LatLng> pts = polygonPoints.get(markerToList.get(marker.getId()));
// This is much the same except use the retrieved point list.
LatLng latLng = (LatLng) marker.getTag();
int position = pts.indexOf(latLng);
pts.set(position, marker.getPosition());
marker.setTag(marker.getPosition());
drawPolygon(markerToList.get(marker.getId()),pts);
}
private void drawPolygon(String mKey, List<LatLng> latLngList) {
// Use the existing polygon (if any) for the root marker.
Polygon polygon = polygons.get(mKey);
if (polygon != null) {
polygon.remove();
}
polygonOptions = new PolygonOptions();
polygonOptions.addAll(latLngList);
polygon = mMap.addPolygon(polygonOptions);
// And update the list for the root marker.
polygons.put(mKey,polygon);
}
Initial
Initial collection of 3 polygons added by clicking on map...
Modified
Then an image showing a point in each polygon stretched...
I am trying to impliment InfoWindow Adapter.
I am facing the problem of having info for the first marker being displayed for all markers.
I have read that i have to impliment OnInfoWindowClickListener() but i failed to .
The code the load the map is as below.
public void getBridgeData()
{
db= new DbHelperClass(this);
bridges= db.getAllBridges();
DecimalFormat dc=new DecimalFormat("#.00");
Builder builder= new LatLngBounds.Builder();
for (int i= 0;i<bridges.size();i++)
{
final Bridge b= (Bridge)bridges.get(i);
// get bridge info
double lati= b.getLatitude();
double longo= b.getLongitude();
// references for calculating Chainage
double reflat= b.getReflat();
double reflong= b.getReflong();
LatLng start = new LatLng(reflat,reflong);
LatLng end = new LatLng(lati,longo);
GeneralUtils uts= new GeneralUtils();
final double ch= uts.calculateDistance(start, end);
final String schainage ="Chainage:" + dc.format(ch) + "Km";
map.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
// TODO Auto-generated method stub
View v = getLayoutInflater().inflate(R.layout.infor_window, null);
// set custom window info details
TextView bname= (TextView) v.findViewById(R.id.bridge);
String txtname="Bridge Name:" + b.getBridgename();
bname.setText(txtname);
TextView rname= (TextView) v.findViewById(R.id.road_name);
String txtroad="Road:" + b.getRoadname();
rname.setText(txtroad);
TextView chainage= (TextView) v.findViewById(R.id.chainage);
chainage.setText( schainage);
TextView btype= (TextView) v.findViewById(R.id.bridge_type);
String txttype= "Bridge Type:" + b.getBridgetype();
btype.setText(txttype);
TextView blength= (TextView) v.findViewById(R.id.bridge_length);
String l= "Length:" + b.getBridgelength() + "M";
blength.setText(l);
TextView bwidth= (TextView) v.findViewById(R.id.bridge_width);
String w= "Width:" + b.getBridgewidth() + "M";
bwidth.setText(w);
return v;
}
#Override
public View getInfoContents(Marker arg0) {
return null;
}
});
Marker mm=map.addMarker(new MarkerOptions().position(
new LatLng(lati, longo))
);
//mm.showInfoWindow();
builder.include(mm.getPosition());
}
final LatLngBounds bounds= builder.build();
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
// TODO Auto-generated method stub
map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 20));
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}
});
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
arg0.showInfoWindow();
}
});
}
Any ideas on how to make it work?
Ronald
The problem is that you put the map.setInfoWindowAdapter in the for loop which will change and change each time you iterate the data.. so the last data of the bridges will be the infowindow layout so that why all of your info window are identical..
Solution:
instead if putting the map.setInfoWindowAdapter in the forloop. just set the bridges as a tag to the marker and use the marker parameter getInfoWindow(Marker arg0) to get the tag..
I've a problem with Google Maps v2. I've to show a custom dialog when the user clicks on the only marker on the map. But the only things that happens is, it centers the map on the marker.
Here's the code:
public class where extends FragmentActivity implements OnMarkerClickListener{
private final LatLng STARTING_POINT=new LatLng(37.5****, 14.2****);
Marker marker;
TextView testo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mappa);
GoogleMap map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(STARTING_POINT, 5));
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//zoom che dura 2 secondi
map.animateCamera(CameraUpdateFactory.zoomTo(19), 3000, null);
map.setOnMarkerClickListener(this);
marker = map.addMarker(new MarkerOptions().position(STARTING_POINT).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
}
#Override
public boolean onMarkerClick(Marker marker) {
if(this.marker == marker){
AlertDialog.Builder alertadd = new AlertDialog.Builder(dovesiamo.this);
LayoutInflater factory = LayoutInflater.from(dovesiamo.this);
final View view = factory.inflate(R.layout.alert, null);
alertadd.setView(view);
alertadd.show();
}
return false;
}
Change
if(this.marker == marker)
to
if(this.marker.equals(marker))
I am displaying google map api v2 in my app. I have set some markers in the map.
I have also set title and snippet on the markers which are shown when you click the marker.
Now I want to call a new activity when clicked on the marker's title and not on marker itself.
map.setOnMarkerClickListner
is called only on the click of the marker.
But I dont want to do that. I want the marker to show the title and snippet on the click of the marker but I want to call new activity on the click of the title.
Any idea how we do that?
Thanks
To achieve this you need to implement setOnInfoWindowClickListener in your getInfoContents method so that a click on your infoContents window will wake the listener to do what you want, you do it like so:
map.setInfoWindowAdapter(new InfoWindowAdapter() {
// Use default InfoWindow frame
#Override
public View getInfoWindow(Marker args) {
return null;
}
// Defines the contents of the InfoWindow
#Override
public View getInfoContents(Marker args) {
// Getting view from the layout file info_window_layout
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
// Getting the position from the marker
clickMarkerLatLng = args.getPosition();
TextView title = (TextView) v.findViewById(R.id.tvTitle);
title.setText(args.getTitle());
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
public void onInfoWindowClick(Marker marker)
{
if (SGTasksListAppObj.getInstance().currentUserLocation!=null)
{
if (String.valueOf(SGTasksListAppObj.getInstance().currentUserLocation.getLatitude()).substring(0, 8).contains(String.valueOf(clickMarkerLatLng.latitude).substring(0, 8)) &&
String.valueOf(SGTasksListAppObj.getInstance().currentUserLocation.getLongitude()).substring(0, 8).contains(String.valueOf(clickMarkerLatLng.longitude).substring(0, 8)))
{
Toast.makeText(getApplicationContext(), "This your current location, navigation is not needed.", Toast.LENGTH_SHORT).show();
}
else
{
FlurryAgent.onEvent("Start navigation window was clicked from daily map");
tasksRepository = SGTasksListAppObj.getInstance().tasksRepository.getTasksRepository();
for (Task tmptask : tasksRepository)
{
String tempTaskLat = String.valueOf(tmptask.getLatitude());
String tempTaskLng = String.valueOf(tmptask.getLongtitude());
Log.d(TAG, String.valueOf(tmptask.getLatitude())+","+String.valueOf(clickMarkerLatLng.latitude).substring(0, 8));
if (tempTaskLat.contains(String.valueOf(clickMarkerLatLng.latitude).substring(0, 8)) && tempTaskLng.contains(String.valueOf(clickMarkerLatLng.longitude).substring(0, 8)))
{
task = tmptask;
break;
}
}
Intent intent = new Intent(getApplicationContext() ,RoadDirectionsActivity.class);
intent.putExtra(TasksListActivity.KEY_ID, task.getId());
startActivity(intent);
}
}
else
{
Toast.makeText(getApplicationContext(), "Your current location could not be found,\nNavigation is not possible.", Toast.LENGTH_SHORT).show();
}
}
});
// Returning the view containing InfoWindow contents
return v;
}
});
To set a title on a marker:
marker.showInfoWindow();
To set a click listener on title:
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
}
});
GoogleMap mGoogleMap;
mGoogleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent intent = new Intent(getBaseContext(), Activity.class);
String reference = mMarkerPlaceLink.get(arg0.getId());
intent.putExtra("reference", reference);
// Starting the Activity
startActivity(intent);
Log.d("mGoogleMap1", "Activity_Calling");
}
});
/**
* adding individual markers, displaying text on on marker click on a
* bubble, action of on marker bubble click
*/
private final void addLocationsToMap() {
int i = 0;
for (Stores store : storeList) {
LatLng l = new LatLng(store.getLatitude(), store.getLongtitude());
MarkerOptions marker = new MarkerOptions()
.position(l)
.title(store.getStoreName())
.snippet("" + i)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(marker);
++i;
}
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
try {
popUpWindow.setVisibility(View.VISIBLE);
Stores store = storeList.get(Integer.parseInt(marker
.getSnippet()));
// set details
email.setText(store.getEmail());
phoneNo.setText(store.getPhone());
address.setText(store.getAddress());
// setting test value to phone number
tempString = store.getPhone();
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0,
spanString.length(), 0);
phoneNo.setText(spanString);
// setting test value to email
tempStringemail = store.getEmail();
SpannableString spanString1 = new SpannableString(tempStringemail);
spanString1.setSpan(new UnderlineSpan(), 0, spanString1.length(), 0);
email.setText(spanString1);
storeLat = store.getLatitude();
storelng = store.getLongtitude();
} catch (ArrayIndexOutOfBoundsException e) {
Log.e("ArrayIndexOutOfBoundsException", " Occured");
}
}
});
}
I want to add a marker on map with long press.
Toast in onMapClick() was display with normal tap. But long press is not working. Toast in onMapLongClick() is not displayed with long press. Also marker is not displayed on map.
I'm using SupportMapFragment because I want to use my application on Android 2.x devices. I have tested my app on Nexus One which has Android version 2.3.7.
This is my code.
public class MainActivity extends FragmentActivity implements
OnMapClickListener, OnMapLongClickListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Location myLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment = (SupportMapFragment) myFragmentManager
.findFragmentById(R.id.map);
myMap = mySupportMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// myMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// myMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
myMap.setOnMapClickListener(this);
myMap.setOnMapLongClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS", Toast.LENGTH_LONG)
.show();
} else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onMapClick(LatLng point) {
myMap.animateCamera(CameraUpdateFactory.newLatLng(point));
Toast.makeText(getApplicationContext(), point.toString(),
Toast.LENGTH_LONG).show();
}
#Override
public void onMapLongClick(LatLng point) {
myMap.addMarker(new MarkerOptions().position(point).title(
point.toString()));
Toast.makeText(getApplicationContext(),
"New marker added#" + point.toString(), Toast.LENGTH_LONG)
.show();
}
}
How can I solve this ?
I used this. It worked.
GoogleMap gm;
gm.setOnMapLongClickListener(this);
#Override
public void onMapLongClick(LatLng point) {
gm.addMarker(new MarkerOptions()
.position(point)
.title("You are here")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
You have no icon setted.
Try:
#Override
public void onMapLongClick(LatLng point) {
myMap.addMarker(new MarkerOptions()
.position(point)
.title(point.toString())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
Toast.makeText(getApplicationContext(),
"New marker added#" + point.toString(), Toast.LENGTH_LONG)
.show();
}
googleMap = supportMapFragment.getMap();
// Setting a click event handler for the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
});
OR
mMap.setOnMapLongClickListener(new
GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick (LatLng latLng){
Geocoder geocoder =
new Geocoder(MapMarkerActivity.this);
List<Address> list;
try {
list = geocoder.getFromLocation(latLng.latitude,
latLng.longitude, 1);
} catch (IOException e) {
return;
}
Address address = list.get(0);
if (marker != null) {
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(address.getLocality())
.position(new LatLng(latLng.latitude,
latLng.longitude));
marker = mMap.addMarker(options);
}
});