i want to create a dialog box when the map get start .. i create this code on my maps activity but i don t know how to make it work what i m missing !thank you
this is my full code for the activity where i show the map
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback {
private GoogleMap mMap;
LatLng origin, dest;
String name, name1;
ArrayList<LatLng> MarkerPoints;
TextView ShowDistanceDuration;
Polyline line;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
#.......
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Creating CameraUpdate object for position
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(origin);
// Creating CameraUpdate object for zoom
CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);
// Updating the camera position to the user input latitude and longitude
googleMap.moveCamera(updatePosition);
// Applying zoom to the marker position
googleMap.animateCamera(updateZoom);
Button btnDriving = (Button) findViewById(R.id.btnDriving);
btnDriving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("driving");
}
});
Button btnWalk = (Button) findViewById(R.id.btnWalk);
btnWalk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("walking");
}
});
}
private void addMarker(GoogleMap googleMap, LatLng position, String name) {
// Instantiating MarkerOptions class
MarkerOptions options = new MarkerOptions();
// Setting position for the MarkerOptions
options.position(position);
// Setting title for the MarkerOptions
options.title(name);
// Setting snippet for the MarkerOptions
options.snippet("Latitude:"+position.latitude+",Longitude:"+position.longitude)
googleMap.addMarker(options);
}
// *****************for the dialog to change map*********//
private static final CharSequence[] MAP_TYPE_ITEMS =
{"Road Map", "Hybrid", "Satellite", "Terrain"};
private void showMapTypeSelectorDialog() {
// Prepare the dialog by setting up a Builder.
final String fDialogTitle = "Select Map Type";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(fDialogTitle);
// Find the current map type to pre-check the item representing the
current state.
int checkItem = mMap.getMapType() - 1;
// Add an OnClickListener to the dialog, so that the selection will be
handled.
builder.setSingleChoiceItems(
MAP_TYPE_ITEMS,
checkItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// Locally create a finalised object.
// Perform an action depending on which item was
selected.
switch (item) {
case 1:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 2:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case 3:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
default:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
dialog.dismiss();
}
}
);
// Build the dialog and show it.
AlertDialog fMapTypeDialog = builder.create();
fMapTypeDialog.setCanceledOnTouchOutside(true);
fMapTypeDialog.show();
}
}
Just add another Button in your activity_maps.xml file and use this Button to change map type by call method showMapTypeSelectorDialog().
Update onMapReady() as below:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Creating CameraUpdate object for position
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(origin);
// Creating CameraUpdate object for zoom
CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);
// Updating the camera position to the user input latitude and longitude
googleMap.moveCamera(updatePosition);
// Applying zoom to the marker position
googleMap.animateCamera(updateZoom);
Button btnDriving = (Button) findViewById(R.id.btnDriving);
btnDriving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("driving");
}
});
Button btnWalk = (Button) findViewById(R.id.btnWalk);
btnWalk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build_retrofit_and_get_response("walking");
}
});
Button btnChangeMap = (Button) findViewById(R.id.btnChangeMap);
btnChangeMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Show map selection dialog
showMapTypeSelectorDialog();
}
});
}
Add below Button to activity_maps.xml
<Button
android:id="#+id/btnChangeMap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Map"/>
Hope this will help~
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 already added multiple marker in google map. But when I click on the particular marker, it should show dialog containing some message and selection button.How to get this?
You should do like #Vurtne says.
Here you can see many another interesting things what you can do with markers.
https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/MarkerDemoActivity.java
It can be useful for you.
By creating a class with all the information you want to show in dialog box, you can solve the problem. Just use the marker id as a key to that information so you can get specific data from the class.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//here I'm using Firebase but you can add marker statically or from any other source
mList.addListenerForSingleValueEvent(new ValueEventListener() {
double location_left, location_right;
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int count = 0;
for (DataSnapshot child : dataSnapshot.getChildren()) {
String rightLocation = child.child("lat").getValue().toString();
String leftLocation = child.child("lon").getValue().toString();
String city = child.child("city").getValue().toString();
String deg = child.child("deg").getValue().toString();
String speed = child.child("speed").getValue().toString();
location_left = Double.parseDouble(leftLocation);
location_right = Double.parseDouble(rightLocation);
Marker marker = mMap.addMarker(new MarkerOptions().position(new LatLng(location_right, location_left)).title(city).snippet("Wind Speed: "+speed).icon(BitmapDescriptorFactory.fromResource(R.drawable.wlll)));
//adding all the information in LocationDetails class with marker id so I can get the specific information, but you can store the data in sqlite db or anything
locationDetailses.add(new LocationDetails(marker.getId(), location_right, location_left, city, Double.parseDouble(deg), Double.parseDouble(speed)));
}
LatLng position = new LatLng(88.0433, 92.66942);
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
//Here setting onClickListener on mMap object of GoogleMap
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
AlertDialog.Builder builder = new AlertDialog.Builder(Map_Activity.this);
//searching marker id in locationDetailses and getting all the information of a particular marker
for (int i = 0; i<locationDetailses.size(); i++) {
//matching id so, alert dialog can show specific data
if (marker.getId().equals(locationDetailses.get(i).getMarkerID())){
builder.setTitle("City: "+locationDetailses.get(i).getCity());
builder.setMessage("Wind Speed: "+locationDetailses.get(i).getSpeed()+"\n"+"Degree: "+locationDetailses.get(i).getDeg()+"\n"+"We can plant WindMill here");
}
}
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog
AlertDialog dialog = builder.create();
dialog.show();
// Add the button
return false;
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
You can use onMarkerClick and get the marker info like this:
yourMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
});
Using google map on clicklistener you can open alert dialog
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
alertDialog();
}
}
});
Hi i working on demo application for google map with custom pop-up.
please suggest me how to handle textview & image view click handle.
i can't get event. below are my code.
class PopupAdapter implements InfoWindowAdapter {
LayoutInflater inflater=null;
Context context;
PopupAdapter(LayoutInflater inflater, Context context) {
this.inflater=inflater;
this.context = context;
}
public View getInfoWindow(Marker marker) {
return(null);
}
public View getInfoContents(Marker marker) {
MyModel mapItem = (MyModel) MainActivity.markers.get(marker.getId());
View popup=inflater.inflate(R.layout.popup, null);
TextView tv=(TextView)popup.findViewById(R.id.title);
ImageView im = (ImageView)popup.findViewById(R.id.icon);
tv.setText(marker.getTitle());
tv=(TextView)popup.findViewById(R.id.snippet);
tv.setText(marker.getSnippet());
im.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("POPUP", "Image Click");
}
});
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("POPUP", "HI");
Toast.makeText(context, "HI", Toast.LENGTH_SHORT).show();
}
});
return(popup);
}
}
Main Activity
public class MainActivity extends AbstractMapActivity implements
OnNavigationListener, OnInfoWindowClickListener {
private static final String STATE_NAV="nav";
private static final int[] MAP_TYPE_NAMES= { R.string.normal,
R.string.hybrid, R.string.satellite, R.string.terrain };
private static final int[] MAP_TYPES= { GoogleMap.MAP_TYPE_NORMAL,
GoogleMap.MAP_TYPE_HYBRID, GoogleMap.MAP_TYPE_SATELLITE,
GoogleMap.MAP_TYPE_TERRAIN };
private GoogleMap map=null;
public static HashMap<String, MyModel> markers= new HashMap<String, MyModel>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (readyToGo()) {
setContentView(R.layout.activity_main);
SupportMapFragment mapFrag=
(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
initListNav();
map=mapFrag.getMap();
if (savedInstanceState == null) {
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
-73.98180484771729));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
map.moveCamera(center);
map.animateCamera(zoom);
}
MyModel item = new MyModel();
item.setId("1");
item.setName("Bhavesh");
item.setAdd("Krishnanagar");
addMarker(map, 40.748963847316034, -73.96807193756104,R.string.un, R.string.united_nations,item);
item = new MyModel();
item.setId("2");
item.setName("Kunal");
item.setAdd("Bhavnagar");
addMarker(map, 40.76866299974387, -73.98268461227417,R.string.lincoln_center,R.string.lincoln_center_snippet,item);
item = new MyModel();
item.setId("3");
item.setName("Ravi");
item.setAdd("Ahmedabad");
addMarker(map, 40.765136435316755, -73.97989511489868,R.string.carnegie_hall, R.string.practice_x3,item);
item = new MyModel();
item.setId("3");
item.setName("Binitbhai");
item.setAdd("Shivranjani");
addMarker(map, 40.70686417491799, -74.01572942733765,R.string.downtown_club, R.string.heisman_trophy,item);
map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater(),MainActivity.this));
map.setOnInfoWindowClickListener(this);
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
map.setMapType(MAP_TYPES[itemPosition]);
return(true);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(STATE_NAV, getSupportActionBar().getSelectedNavigationIndex());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_NAV));
}
#Override
public void onInfoWindowClick(Marker marker) {
// MyModel mapItem = (MyModel) markers.get(marker.getId());
// Toast.makeText(this,marker.getSnippet()+ marker.getTitle() + " "+mapItem.getName() +" "+mapItem.getAdd() , Toast.LENGTH_LONG).show();
}
private void initListNav() {
ArrayList<String> items=new ArrayList<String>();
ArrayAdapter<String> nav=null;
ActionBar bar=getSupportActionBar();
for (int type : MAP_TYPE_NAMES) {
items.add(getString(type));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
nav=
new ArrayAdapter<String>(
bar.getThemedContext(),
android.R.layout.simple_spinner_item,
items);
}
else {
nav=
new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_item,
items);
}
nav.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
bar.setListNavigationCallbacks(nav, this);
}
private void addMarker(GoogleMap map, double lat, double lon, int title, int snippet,MyModel item) {
markers.put(map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title(getString(title)).snippet(getString(snippet)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))).getId(), item);
// map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title(getString(title)).snippet(getString(snippet)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
}
Please suggest me how to do this event.
thank you..
You cannot put OnClickListeners on the contents of an info window. The info window itself is not displaying your layout, but rather a Bitmap generated from the layout. This is covered in the documentation:
As mentioned in the previous section on info windows, an info window is not a live View, rather the view is rendered as an image onto the map. As a result, any listeners you set on the view are disregarded and you cannot distinguish between click events on various parts of the view. You are advised not to place interactive components — such as buttons, checkboxes, or text inputs — within your custom info window.
You can use setOnInfoWindowClickListener() to find out when the info window itself is tapped.
As explained in other answers what you want to achieve is not supported directly by Google Maps Android API v2, but...
you can do what you need by putting yourself in front of MapFragment or MapView, handle MotionEvents to make your OnClickListeners be called.
See this answer for a nice (but hackish) how-to: https://stackoverflow.com/a/15040761/2183804
yes you cannot add listener on the view of info window. One thing you can do , onInfoWindowClick show alert menu and give the user some options.
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
final CharSequence[] items = { "message", "call"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Call");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
sendMessage();
} else {
makeCall();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
Or you can try something like this..
I am not sure whether its work or not.
https://stackoverflow.com/a/15040761/1792228
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'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();
}
}
}