Connect pinned map marker to user ID in android - android

In an app I am making I wanted to enable a single user to post only 5 markers. I did this, but I think this will disable user to pin a marker when someone else pinned 5.
My question is how to connect marker to users unique ID so that he can still pin markers after others pinned more than 5.
Code I used for disabling more than 5 markers is:
private GoogleMap mMap;
Marker marker; // Marker
int markerCount = 0; // Marker counter
//Add marker on long click
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
int iMax = 5; // Max number of markers
#Override
public void onMapLongClick(LatLng arg0) {
if (markerCount < iMax) {
// start SendMessageActivity need to add marker to message activity
startActivity(new Intent(MapsActivity.this, SendMessageActivity.class));
markerCount = markerCount + 1;
marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker))
.position(
new LatLng(arg0.latitude,
arg0.longitude))
.visible(true));
} else {
Toast.makeText(getApplicationContext(), "Only " + iMax + " markers allowed at the same time",
Toast.LENGTH_LONG).show();
}
}
});

Related

Marker sometimes change colour on click and sometimes it does not

I have this application where I show markers on google maps for pharmacies nearby. When I click on marker I want the marker to change the colour. When I click on some other marker, it should change the previous marker's colour to default and will change new marker's colour.
This is working randomly, I mean sometimes marker colour is getting changed and sometimes it stays the default color.
Marker lastClicked;
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in user's location
// User's location is taken from the postal code entered
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
if(lastClicked != null){
lastClicked.setIcon(BitmapDescriptorFactory.defaultMarker());
}
marker.setIcon(getMarkerIcon(getResources().getColor(R.color.app_color)));
lastClicked=marker;
return false;
}
});
}
Code for getMarkerIcon() method is:
public BitmapDescriptor getMarkerIcon(int color){
float[] hsvFloat = new float[3];
Color.colorToHSV(color, hsvFloat);
return BitmapDescriptorFactory.defaultMarker(hsvFloat[0]);
}
NOTE: I added debugger in every line to see what part of code does not run, and it is strange that when debugger come to this line
marker.setIcon(getMarkerIcon(getResources().getColor(R.color.app_color)));
it is getting compiled and yet sometimes it does not change the color of the marker.
I solved this problem by checking my list of markers. From that I found that there were markers with exactly same lat and lng, that's why markers were overlapped, that means there were more than 1 markers on one
public boolean isDuplicate(Pharmacy pharmacy){
for(int i=0; i<pharmacyList.size(); i++){
if(pharmacyList.get(i).getLatitude() == pharmacy.getLatitude()
&&pharmacyList.get(i).getLongitude() == pharmacy.getLongitude())
return true;
}
return false;
}
NOTE: Pharmacy is class that lat and lng properties.
you should try this out
googlemap.addMarker(new MarkerOptions()
.position(new LatLng( 65.07213,-2.109375))
.title("This is my title")
.snippet("and snippet")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
Hope this will work for you!
Probably at marker creation step several markers with same coordinates added and overlap each other. To check marker existence by coordinates you can use O(1) complexity (instead of O(N) for iterating over all markers case) approach by using LatLng of Marker object as HashMap/HashSet key. For do that you need to implement approach described, for example, in this answer of Tomasz Nurkiewicz. For example, Key class can be like this:
public class LatLngKey {
private LatLng mLatLng;
public LatLngKey(LatLng latLng) {
mLatLng = latLng;
}
public double getLattitude() {
return mLatLng.latitude;
}
public double getLongitude() {
return mLatLng.longitude;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof LatLngKey)) return false;
LatLngKey key = (LatLngKey) o;
return mLatLng.latitude == key.getLattitude() && mLatLng.longitude == key.getLongitude();
}
#Override
public int hashCode() {
// for better accuracy it is needed to convert double values into integer
int result = (int) mLatLng.latitude * 10_000;
result = 31 * result + (int) mLatLng.longitude * 10_000;
return result;
}
}
and using of it like that:
...
mGoogleMap = googleMap;
Map<LatLngKey, Marker> markersMap = new HashMap<>();
LatLng positionNoida = new LatLng(28.57, 77.32);
Marker markerNoida = mGoogleMap.addMarker(new MarkerOptions().position(positionNoida)
.title("Marker in Noida"));
LatLngKey markerKey = new LatLngKey(markerNoida.getPosition());
markersMap.put(markerKey, markerNoida);
LatLng positionNoida2 = new LatLng(28.57, 77.32);
Marker markerNoida2 = mGoogleMap.addMarker(new MarkerOptions().position(positionNoida2)
.title("Marker in Noida 2"));
LatLngKey markerKey2 = new LatLngKey(markerNoida2.getPosition());
if (markersMap.containsKey(markerKey2)) {
// marker with same coordinates exists
...
} else {
// marker with same coordinates do not exists
...
}
...
You need to implement PharmacyKey class for your Pharmacy.

InfoWindows doesn't take each info window marker

I load the markers from sqlite and I do looping to get data from sqlite the put the marker to each latitude and longitude. It works.
But when I try to get the info window from each marker, it doesnt works. It just take one infowindow.
this is my code:
while (cursor.moveToNext()){
// mengambil koordinat lokasi ATM
title = cursor.getString(1).toString();
__global_endposition = cursor.getString(2).toString();
alamat = cursor.getString(3).toString();
String[] exp_endCoordinate = __global_endposition.split(",");
double lat_endposition = Double.parseDouble(exp_endCoordinate[0]);
double lng_endposition = Double.parseDouble(exp_endCoordinate[1]);
LatLng endx = new LatLng(lat_endposition, lng_endposition);
MarkerOptions options = new MarkerOptions()
.position(endx)
.title(title)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
// mMap.addMarker(options);
Marker marker = googleMap.addMarker(options);
mapBuilder.include(marker.getPosition());
addedMarker = true;
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getActivity(), alamat, Toast.LENGTH_SHORT).show();
}
});
}
This is my sqlite record:
enter image description here
When I clik to each marker, it only showed "Giant Ekspres, Jl. Urip Sumoharjo, Klitren, Gondokusuman, Kota Yogyakarta" to each marker info windows.
There is only one onInfoWindowClick listener per map object. In your case, you Toast the contents of alamat which will always be the last cursor result (column index 3) string.
If you want to display for each marker the alamat contents as it appears you intended then the simplest approach is to set the marker's tag field to the contents of alamat and then in the listener use the marker's tag field in the toast:
alamat = cursor.getString(3).toString();
// ...
MarkerOptions options = new MarkerOptions()
.position(endx)
.title(title)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
Marker marker = googleMap.addMarker(options);
marker.setTag(new String(alamat));
// ...
googleMap.setOnInfoWindowClickListener(new
GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getActivity(), marker.getTag().toString(), Toast.LENGTH_SHORT).show();
}
});
You will soon find you may want to do more than just display the tag string. So you can either use a more complex object in the tag or use the marker id in the onInfoWindowClick to access a managed collection of marker data, like a Hashmap.

Google Place - set On Info Window Click Listener

How I can setOnInfoWindowClickListener if have this loop?
I'm trying to create an Android application. To retrieve data from json file I use retrofit.
I need help when clicking on the info window I want to show more information about the clicked place.
I want to display Toast with the name of clicked the Nearby Places.
for (int i = 0; i < response.body().getResults().size(); i++) {
Double lat = response.body().getResults().get(i).getGeometry().getLocation().getLat();
Double lng = response.body().getResults().get(i).getGeometry().getLocation().getLng();
final String placeName = response.body().getResults().get(i).getName();
// String vicinity = response.body().getResults().get(i).getVicinity();
// Double ratting = response.body().getResults().get(i).getRating();
final List <String> nameLocation = new ArrayList<>();
nameLocation.add(placeName);
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, lng);
// Position of Marker on Map
markerOptions.position(latLng);
// Adding Title to the Marker
markerOptions.title(placeName);
// Adding colour to the marker
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(markerColor));
// Adding Marker to the Camera.
Marker mMarker = mMap.addMarker(markerOptions);
// move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
As you mentioned in the comments, you can show a toast in when a marker on your map is clicked by doing the following.
First attach a marker click listener to your map:
mMap.setOnMarkerClickListener(new OnMarkerClickListener {
public boolean onMarkerClick(final Marker marker) {
//TODO: Show your toast
}
});
Next within the click handler, create a new toast. Make sure you have the application context within this handler, so that you can attach the toast to that context.
final Context context = this;
mMap.setOnMarkerClickListener(new OnMarkerClickListener {
public boolean onMarkerClick(final Marker marker) {
Toast toast = Toast.makeText(context, marker.getTitle(), "Additional info", Toast.LENGTH_SHORT);
toast.show();
}
});

Google Map does not moving to the new LatLng location

I'm developing an Android app which traces the path from current location to a specific destination. It works well. But there is an exception scenario.
When user clicks on a destination marker, it needs to move the map to another location with zoom. But only get zoomed without moving to the second location.
This is my relating code segment with that. If you can please help me with this. Thanks in advance.
double Kumana1_Latitude = 6.573022;
double Kumana1_Longitude = 81.666875;
double Kumana2_Latitude = 6.649353;
double Kumana2_Longitude = 81.770114;
final LatLng Kumana = new LatLng(Kumana1_Latitude, Kumana1_Longitude);
final LatLng Kumana2 = new LatLng(Kumana2_Latitude,Kumana2_Longitude);
Marker Kumana_marker = mGoogleMap.addMarker(new MarkerOptions()
.title("Kumana National Park")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(Kumana));
Kumana_marker.showInfoWindow();
mGoogleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker m) {
//here it get Zoomed, but does not move to the new location
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Kumana2, 13));
m.remove();
Toast.makeText(getApplicationContext(),
"Tap on the Kumana National Park entreance", Toast.LENGTH_LONG)
.show();
});
}
Put the marker in onLocationChanged() and plot the marker. First remove the marker and then add the new marker with the new location.
All this code must come under onLocationChanged()
Check first
(if marker == null){
//plot marker
}
else{
//remove first marker..
//add new marker
}
Try to call super.onMarkerClick(m) in your overriden function ònMarkekClick(Marker m)`.

How to get the latitude and longitude of location where user taps on the map in android

In my Android application, I'm using google maps v2 to show map by getting the latitute and longitude of the device's current location And I'm showing pin on that location.
Now when user clicks or taps on any other location on the map, then I have to get that points latitude and longitude and i have to set the pin at that location.
Could you please tell me how get the latitude and longitude of the user taps/clicks location.
An example of what i use. Change it accordingly for your needs. I use it with long press.
map.setOnMapLongClickListener(new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
map.addMarker(new MarkerOptions().position(point).title("Custom location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));enter code here
}
});
the LatLng point contains the coordinated of the longpress
Try to use google-maps v2 built-in method.
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng position) {
Toast.makeText(context,position.latitude+" : "+position.longitude,Toast.LENGTH_SHORT).show();
}
});
Try the following.
Write a class which derives from the Overlay class and override the onTap() method. Then you can add your overlay to the your MapView. A GeoPoint object, which represents the position of you tap, is passed to the onTap() method when you tab somewhere on the map.
OR
The modern answer here, using Android Maps v2, is to use OnMapClickListener, which gives you the LatLng of a tap on the map.
// Setting onclick event listener for the map
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
//Get LatLng from touched point
double touchLat=point.latitude;
double touchLong=point.longitude;
///here is reverse GeoCoding which helps in getting address from latlng
try {
Geocoder geo = new Geocoder(MainActivity.this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(touchLat,touchLong, 1);
if (addresses.isEmpty()) {
Toast.makeText(getApplicationContext(),"Waiting for Location",Toast.LENGTH_SHORT).show();
}
else {
if (addresses.size() > 0) {
address =addresses.get(0).getFeatureName()
+ ", " + addresses.get(0).getLocality()
+ ", " + addresses.get(0).getAdminArea()
+ ", " + addresses.get(0).getCountryName();
Toast.makeText(getApplicationContext(), "Address:- " +address, Toast.LENGTH_LONG).show();
}
// draws the marker at the currently touched location
drawMarker(point,"Your Touched Position",address+"");
}
}
catch (Exception e) {
e.printStackTrace(); // getFromLocation() may sometimes fail
}

Categories

Resources