OnInfoClick Doesn't Work - android

I have a program that wants to direct me to a location review page where the person can read all about the location about that particular location on which he clicks.
I tried implementing it with the code below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_places_near_me);
// 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);
progressDialog = new ProgressDialog(PlacesNearMeActivity.this);
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(PlacesNearMeActivity.this, ReviewActivity.class);
startActivity(intent);
}
});
} // #EndOfOnCreate!
Markers are displayed on google maps using
public void markPlaces(String result, GoogleMap mMap) {
try {
final JSONObject json = new JSONObject(result);
JSONArray resultArray = json.getJSONArray("results");
for ( int z=0; z<resultArray.length(); ++z ) {
JSONObject locObj = resultArray.getJSONObject(z);
JSONObject geometry = locObj.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
Double lat = Double.parseDouble(location.getString("lat"));
Double lng = Double.parseDouble(location.getString("lng"));
String name = locObj.getString("name");
String placeId = locObj.getString("place_id");
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title(name)
.snippet(placeId));
}
}
catch (JSONException e) { }
} // #EndOfmarkMarkers!
problem is that nothing happens, i tried implementing it using the implements method and onMarkerClickListener as well.. Any solution?

If you use getMapAsync() (and you should!), all map configuration of the map needs to be put into onMapReady(). Until then, you do not have a map to configure. This includes setting listeners for events like info window or marker clicks.

Related

IllegalArgumentException: Unmanaged descriptor

i am trying to run a geoquery everytime someone select a place from PlaceAutoComplete fragment and show the markers on the map. It is working fine for the first.When i start the app the icons are are all fine the geoquery is running fine, but when i enter a location second time the app crashes showing an error llegalArgumentException: Unmanaged descriptor below is what i am trying to do.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SupportPlaceAutocompleteFragment autocompleteFragment =
(SupportPlaceAutocompleteFragment)
getChildFragmentManager().findFragmentById
(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new
PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Toast.makeText(getContext(),place.getAddress(),Toast.LENGTH_LONG).show();
Log.i(TAG, "Place: " + place.getName());
Double latitude1 = place.getLatLng().latitude;
Double longitude1 =place.getLatLng().longitude;
LatLng latLng = new LatLng(latitude1,longitude1);
getPeople(latLng); // method to call geofire query
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
return mMainView;
}
public void getPeople(LatLng latLng1){
mMap.clear();
mMap.addCircle(new CircleOptions()
.center(latLng1)
.radius(2000)
.strokeColor(Color.BLACK)
.fillColor(0x220000FF)
.strokeWidth(1)
);
DatabaseReference ref =
FirebaseDatabase.getInstance().getReference().child("Location");
GeoFire geoFire = new GeoFire(ref);
GeoQuery geoQuery = geoFire.queryAtLocation(new
GeoLocation(latLng1.latitude, latLng1.longitude), 2);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(final String key, GeoLocation location) {
UIDLocation.put(key,location);
marker.setIcon(BitmapDescriptorFactory.fromResource
(R.drawable.ic_mapmarker2));
markers.put(key, marker);
for (Map.Entry<String,GeoLocation> entry : UIDLocation.entrySet())
{
final Marker marker = markers.get(entry.getKey());
if (marker != null) {
DatabaseReference mUser =
FirebaseDatabase.getInstance().getReference().child("People")
.child(string);
mUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
String display_name =
dataSnapshot.child("name").getValue().toString();
String status =
dataSnapshot.child("status").getValue().toString();
String image =
dataSnapshot.child("image").getValue().toString();
PeopleInfo info = new PeopleInfo();
info.setName(display_name);
info.setStatus(status);
info.setImage(image);
marker.setTag(info);
String iconName = dataSnapshot.child("iconName")
.getValue().toString();
Context context = getContext();
int id = context.getResources().getIdentifier(iconName, "drawable",
context.getPackageName());
String s = String.valueOf(id);
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),id);
marker.setIcon(BitmapDescriptorFactory.fromResource(id));
}
#Override
public void onCancelled(DatabaseError
databaseError) {
}
});
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
mUiSettings = mMap.getUiSettings();
mUiSettings.setZoomControlsEnabled(true);
mFusedLocationClient =
LocationServices.getFusedLocationProviderClient(getContext());
Task task= mFusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new
OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
markeroptn = new MarkerOptions();
markeroptn.position(myPosition);
markeroptn.title("You are Here");
mMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition,10));
getWorkMen(myPosition);
}
}
});
So far what i have learned from the posts on SO that its because the program is trying to set the icon on marker which is already there. I tried clear() map in the begining of getPeople() but still it is showing the same error.It works fine first time. i also tried remove() also but its also not working.
The problem may come from the way you manage the Marker variables. In the code, you store a marker variable as global outside of the method scope. When calling map.clear(), it makes the marker variable invalid and if somehow you still use this variable to set something, it may cause the exception. The same thing happens with the markers Map you use to map key and Marker, it's not being cleared when map.clear().
Try to manage your map elements more carefully, clear each map element dependently and avoid using map.clear().
Suggestion approach:
Create new marker
private void addMarker(String key, LatLng latLng) {
// Clear the current marker before add the new one
if (marker != null) {
marker.remove();
marker = null;
}
// Store new marker to the variable
marker = mMap.addCircle(new CircleOptions()
.center(latLng)
.radius(2000)
.strokeColor(Color.BLACK)
.fillColor(0x220000FF)
.strokeWidth(1)
);
// Add to markers map if needed
markers.put(key, marker);
}
Clear all markers (clear manually every marker variable available, don't use map.clear:
public synchronized void clear() {
// markers is the marker map
for (Marker marker : markers.values()) {
try {
marker.remove();
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
}
// Clear all the marker map
markers.clear();
// Marker is the your global marker variable
marker.remove();
}

Passing a address via intent to Google map activity:

I am working on an app that gets the address of an event the user selects. The address is a String and is passed from one activity to a Google Map activity. I know the string arrives in the map activity as I have used a Toast to display it.
However, when I try to get the longitude and latitude of the address it doesn't work. The try catch block doesn't seem to execute unless I hard code and address into the addresses = geocoder.getFromLocationName('Dublin,Ireland', 1);
Any help would be greatly appreciated.
public class EventMapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private Intent MyTournamentsActivityIntent;
private String eventAddress = "";
double latitude = 0;
double longitude = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_map);
// 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);
MyTournamentsActivityIntent = getIntent();
eventAddress = MyTournamentsActivityIntent.getStringExtra("event_location");
Toast.makeText(getApplicationContext(),"Address from intent" + eventAddress,Toast.LENGTH_SHORT).show();
}//end onCreate
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Geocoder geocoder = new Geocoder(this);
List<Address> addresses;
try{
/*
This doesnt execute unless I hard code the eventAddress
*/
addresses = geocoder.getFromLocationName(eventAddress, 1);
latitude= addresses.get(0).getLatitude();
longitude= addresses.get(0).getLongitude();
Toast.makeText(getApplicationContext(),String.valueOf(latitude) + " " + String.valueOf(longitude) ,Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
e.printStackTrace();
}
LatLng eventLocation = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(eventLocation).title("Your Event"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(eventLocation));
}//end onMapReady
public void setEventAddress(String eventAddress) {
this.eventAddress = eventAddress;
}
}//end Class
Change this :
eventAddress = MyTournamentsActivityIntent.getStringExtra("event_location");
To this:
eventAddress = getIntent().getStringExtra("event_location");
And call mapFragment.getMapAsync(this);:
eventAddress = getIntent().getStringExtra("event_location");
mapFragment.getMapAsync(this);
After you get the eventAddress

Can't see multiple markers on google map

In PostExecute i have this array name : locations
I print Log for more details like that:
[lat/lng: (18.5159983333333,-72.2916166666667), lat/lng: (18.5363383333333,-72.3231866666667), lat/lng: (18.5076266666667,-72.3164933333333), lat/lng: (18.54138,-72.2920766666667)]
And i try to show all coordinates like that
protected void onPostExecute(Boolean result) {
dialog.dismiss();
for (int i = 0; i < locations.size(); i++)
{
Double latitude = Double.valueOf(locations.get(i).latitude);
Double longitude = Double.valueOf(locations.get(i).longitude);
LatLng lng = new LatLng(latitude,longitude);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.addMarker(new MarkerOptions()
.position(lng)
.title("Test")
.icon(BitmapDescriptorFactory.fromResource(getResources().getIdentifier("Title", "drawable", getPackageName()))));
}
}
Google map shows blank. How may i resolve it please??
You can only add markers when your map is ready to receive them and that is true when
public void onMapReady(GoogleMap googleMap)
is called.
I will try to get you started with this:
You need to setup some variables:
private GoogleMap mMap;
private boolean isMapReady = false;
private ArrayList<LatLng> myLocations = null;
the ArrayList will contain your locations you get from your AsyncTask
Then you need to get the mapOnReady setup in your onCreate() Methode:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// What ever else you need
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapViewRidesFoundMap);
mapFragment.getMapAsync(this);
}
Now you need to override the onMapReady method:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Set a boolean flag to let other parts of you code
// know that the map is ready
isMapReady = true;
// If you need to get info from your marker Implement this
//mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
// #Override
// public boolean onMarkerClick(Marker marker) {
// showMarkerInfo(marker);
// return false;
// }
//});
//If you need a click listener add this
// Add implement the method 'onMapClickLocation'
//mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
// #Override
// public void onMapClick(LatLng latLng) {
// onMapClickLocation(latLng);
// }
//});
// call a function to update your locations
updateMapLocations();
}
Within your(!) protected void onPostExecute(Boolean result) add code to fill the myLocations ArrayList
protected void onPostExecute(Boolean result) {
dialog.dismiss();
myLocations = new ArrayList<LatLng>();
for (int i = 0; i < locations.size(); i++)
{
Double latitude = Double.valueOf(locations.get(i).latitude);
Double longitude = Double.valueOf(locations.get(i).longitude);
LatLng lng = new LatLng(latitude,longitude);
myLocations.put(lng);
}
// calls the update method when data is available
this.updateMapLocations();
}
and add a call to updateMapLocations() which could look like this:
private void updateMapLocations(){
// update locations won't continue unless the map is ready
if(!isMapReady) return;
// Zoom into your location !! if you need too
// with a destinationLocation of your choice
// perhaps your first location in you ArrayList
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(destinationLocation, zoomFactor));
// PseudoCode!!
// Add your for Loop
// !!! Check to see if your myLocations ArrayList is null before you continue !!!
// !!! or just add another boolean to you onPostExcecute method
// And add the Markers
//Loop Start
//float hue = BitmapDescriptorFactory.HUE_MAGENTA;
//MarkerOptions markerOptions = setMarker(latLng, hue)
// !!! You need to add your destination loop !!!
//mMap.addMarker(markerOptions);
//Loop end!
}
private MarkerOptions setMarker(LatLng latLng, float hue){
MarkerOptions markerOptions = null;
try {
float markerAlpha = 0.7f;
markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(hue));
markerOptions.position(latLng);
markerOptions.alpha(markerAlpha);
markerOptions.flat(false);
markerOptions.title("What Ever");
markerOptions.snippet("MySnippet");
markerOptions.draggable(false);
markerOptions.zIndex(0.0f);
}
catch (Exception ex){
Log.e(TAG, " setMarker --- " + ex.getMessage());
}
return markerOptions;
}
Notice that updateMapLocations() is called in both your onPostExecute() and the onMapReady() methods. The onPostExecute() might be finished before the onMapReady() is called. So that first when the map is ready the updateMapLocations() will run to completion when data and map are ready.
I wrote this in a text editor - so there will probably be a couple of syntax errors.

Add second marker on google maps activity in android on user input

I have a google maps activity with a map an edittext and a button.
The screenshot of the activity that I have ready at the moment.
Whenever this activity is opened a marker is added to the map.
What I want further in this is that whenever the user inputs an address in that edittext and clicks the button, then another marker is added on the same map without erasing the previous marker and a polyline is created in the map joining the two markers.
I have tried adding the second marker but the app just crashes and I am not able to do that. It would be a great help if you guys can help me in adding the second marker.
Here is the activity code :
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private EditText findRouteEdittext;
private Button findRouteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
Intent intent = getIntent();
Geocoder coder = new Geocoder(this);
List<Address> addressList;
LatLng coord = null;
String completeAddress = intent.getStringExtra("completeAddress");
try {
addressList = coder.getFromLocationName(completeAddress, 5);
if (addressList != null) {
Address location = addressList.get(0);
coord = new LatLng(location.getLatitude(), location.getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
mMap = googleMap;
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(coord);
mMarkerOptions.title(completeAddress);
mMap.addMarker(mMarkerOptions).showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(coord));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coord, 14.0f));
}
}
EDIT 1
I finally got the answer myself, on where to add, it was basically a minor error but just so other people know where to add I will update the answer here :
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private EditText findRouteEdittext;
private Button findRouteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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);
findRouteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchString = findRouteEdittext.getText().toString().toLowerCase().trim();
if (searchString.equals("")){
// findRouteEditTextInputLayout.setErrorEnabled(true);
// findRouteEditTextInputLayout.setError("Enter a location or City!");
//use snackbar to show something.
}
else{
coder2 = new Geocoder(MapsActivity.this);
coord2 = null;
try {
addressList2 = coder2.getFromLocationName(searchString, 5);
if (addressList2 != null) {
Address location = addressList2.get(0);
coord2 = new LatLng(location.getLatitude(), location.getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (coord2!=null && coord!=null) {
mMap.clear();
mMarkerOptions2 = new MarkerOptions();
mMarkerOptions2.position(coord2);
mMarkerOptions2.title(searchString); //this is the address of the new string entered by the user
mMap.addMarker(mMarkerOptions2).showInfoWindow();
mMarkerOptions3 = new MarkerOptions();
mMarkerOptions3.position(coord);
mMarkerOptions3.title(completeAddress); //this is the address of the original string received from intent
mMap.addMarker(mMarkerOptions3).showInfoWindow();
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
Intent intent = getIntent();
Geocoder coder = new Geocoder(this);
List<Address> addressList;
LatLng coord = null;
String completeAddress = intent.getStringExtra("completeAddress");
try {
addressList = coder.getFromLocationName(completeAddress, 5);
if (addressList != null) {
Address location = addressList.get(0);
coord = new LatLng(location.getLatitude(), location.getLongitude());
}
} catch (Exception ex) {
ex.printStackTrace();
}
mMap = googleMap;
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(coord);
mMarkerOptions.title(completeAddress);
mMap.addMarker(mMarkerOptions).showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(coord));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coord, 14.0f));
}
}
If you already got Location object then use below code to add new marker in to map.
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
place this code in side add button on click listener.

How to use onInfoWindowClick with array of markers?

I have a map with a lot of markers. When you click marker, small windows with information will appear. When you click it I want to call fragment. I found that I should use onInfoWindowClick but something is wrong. I can't get any values.
public class Map extends Activity implements OnInfoWindowClickListener{
static final LatLng xxx = new LatLng(70.000, 70,22);
static String[] streets;
static String[] artist;
Coordinate cor = new Coordinate();
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
try {
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
Resources res = this.getResources();
artist = res.getStringArray(R.array.authors_nicks);
streets = res.getStringArray(R.array.streets);
for (int i = 0; i < cor.coordinatesVale.size(); i++) {
Marker m = googleMap.addMarker(new MarkerOptions()
.position(cor.coordinatesVale.get(i))
.title(artist[i])
.snippet(streets[i])
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker)));
m.getId();
}
googleMap.setMyLocationEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(xxx, 12));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
}
#Override
public void onInfoWindowClick(Marker marker) {
String id = marker.getId();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("dsdsd", 3);
startActivity(i);
Log.i("dddd", id); /// CAN't see
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
I found some tutorials, but I'm don't know what I'm doing wrong
In your initializeMap() function, right after you use getMap(), put the following code there. Using this method, you don't need to call implements OnInfoWindowClickListener, but would work the same either way.
if (googleMap != null) {
// More info: https://developers.google.com/maps/documentation/android/infowindows
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
// Determine what marker is clicked by using the argument passed in
// for example, marker.getTitle() or marker.getSnippet().
// Code here for navigating to fragment activity.
}
});
}
The above code allows you to do something when the user clicks on the info window.
In order to show the info window in the first place, use one either one of the following code snippets, which you have already:
static final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400"));
Or,
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne"));
melbourne.showInfoWindow();
Source: Google Maps Android API v2

Categories

Resources