Is it possible to have onMapClick() called instead of onMarkerClick()? - android

I have a google map in my app and I handle clicks on it. Everything is fine but if I click on a marker or really close to it onMarkerClick() is called, not onMapClick() and then I don't have the exact location of the place I tapped because marker.getPosition() returns the center point of the marker what's not the same.
Is it possible to disable onMarkerClick() and have onMapClick() called even if I click on a marker?

Return true for disabling marker click event
googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
return true;
}
});
For getting click on maps use this listener on onMapReady
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener()
{
#Override
public void onMapClick(LatLng arg0)
{
Log.v("onMapClick", "Yea worked!");
}
});
}
Complete code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#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);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
Toast.makeText(MapsActivity.this, "Map clicked", Toast.LENGTH_SHORT).show();
}
});
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(MapsActivity.this, "Marker disabled", Toast.LENGTH_SHORT).show();
return true;
}
});
}
}

It is possible.Here is a simple solution.
First of all you should declare GoogleMap.OnMarkerClickListener and GoogleMap.OnMapClickListener in your activity or fragment like this.
public class MapActivity extends FragmentActivity implements
GoogleMap.OnMarkerClickListener,
GoogleMap.OnMapClickListener
{
//..
}
And then register that interfaces in your onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState)
{
//..
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mMap.setOnMarkerClickListener(this);
mMap.setOnMapClickListener(this);
}
Finally you can implement two interfaces.You should call onMapClick() method in onMarkerClick() method to achieve that even if you click on a marker like that.Don't forget to return true in onMarkerClick() method.
#Override
public void onMapClick(LatLng latLng) {
Log.v("onMapClick", "Map Clicked..")
}
#Override
public boolean onMarkerClick(Marker marker) {
onMapClick(marker.getPosition());
return true;
}

Related

Zoom map Get location chosen by User and pass it to activity

I have this code, that allows a user to select a location (mechanic_location) and passes it to another activity(mechanic_login). The problem is, it does not zoom. Help me enable it to zoom to the current location the user is in but give the user the ability to pick another location different from the one that he/she is in. Once the location is picked, click a button to send the latitude and longitude to the view (mechanic_login). Here is my code
public class mechanic_location extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
Button mSendLocationBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mechanic_location);
// 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.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
Intent returnIntent = new Intent();
returnIntent.putExtra("picked_point",latLng);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
}
}
You can use the moveCamera() Method and defined the zoom level
float zoomLevel = 16.0f; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
for mor information about using google map, you can check it here
source

onMarkerClick() is never called in Emulator

I want to register a OnMarkerClickListener to a GoogleMap:
implement the GoogleMap.OnMarkerClickListener interface
register listener via GoogleMap.setOnMarkerClickListener(this)
but when I click on a marker the callback onMarkerClick() is never called. For test purposes I also implemented OnMapLongClickListener and it works perfectly well.
public class ShowCoords extends FragmentActivity implements
OnMapReadyCallback,
LocationListener,
GoogleMap.OnCameraMoveListener,
GoogleMap.OnCameraMoveStartedListener,
GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener,
GoogleMap.OnMarkerClickListener,
GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_coords);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setMapToolbarEnabled(false);
if (gpsPermission()) {
mMap.setMyLocationEnabled(true);
}
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
mMap.setOnCameraMoveStartedListener(this);
mMap.setOnCameraMoveListener(this);
mMap.setOnMarkerClickListener(this);
mMap.setOnMapLongClickListener(this);
if (displayFormat.equals(getString(R.string.heatmapValue))) {
// display markers as heatmap
} else if (displayFormat.equals(getString(R.string.clusterValue))) {
// diplay markers as cluster
mClusterManager = new ClusterManager<>(this, mMap);
mMap.setOnCameraIdleListener(mClusterManager);
// this causes the problem
mMap.setOnMarkerClickListener(mClusterManager);
for (LatLng p : coords) {
mClusterManager.addItem(new MyClusterItem(p));
}
} else {
Log.w(TAG, "onMapReady: coords still null, nothing to display");
}
//just for testing
mMap.addMarker(new MarkerOptions().position(new LatLng(51.866404, 12.643411)));
}
#Override
public boolean onMarkerClick(Marker marker) {
Log.i(TAG, "onMarkerClick");
return true;
}
#Override
public void onMapLongClick(LatLng latLng) {
Log.i(TAG, "onMapLongClick");
}
// removed other callbacks
}
Any ideas, whats going wrong?
I got it. When I display the markers as a cluster (via Google Maps Android Marker Clustering Utility) the clustermanager registers as OnMarkerClickListener and the registration of my listener get lost. As a workaround, I omit the clustermanager registration and pass the click event on the clustermanager by myself.

Add marker on long press in Google Maps API v3

How to implement adding a marker on long press in Google Maps API v3 for android? There are answers about this in Stack Overflow itself but they are for Google Maps API v2.
public class advertiserMap extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advertiser_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);
}
//for searching for a location
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
As #tyczj pointed out, there's no v3 for Android Google Maps API, so you are probably using v2.
That said, to accomplish what you want, call setOnMapLongClickListener in your mMap object, and add the marker as you want inside onMapLongClick. You should do this in the onMapReady method:
#Override
public void onMapReady(GoogleMap googleMap) {
...
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Your marker title")
.snippet("Your marker snippet"));
}
});
}
// EDIT:
If you want to keep only one marker present at a time, you should declare your marker in the global activity's scope, and then, in onMapLongClick, if marker already exists, instead of creating a new marker, just update it's position:
public class advertiserMap extends FragmentActivity implements OnMapReadyCallback {
// Declare marker globally
Marker myMarker;
...
#Override
public void onMapReady(GoogleMap googleMap) {
...
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
// First check if myMarker is null
if (myMarker == null) {
// Marker was not set yet. Add marker:
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Your marker title")
.snippet("Your marker snippet"));
} else {
// Marker already exists, just update it's position
myMarker.setPosition(latLng);
}
}
});
}
}
If done like this, remember to always check if your marker is not NULL before manipulating it in your code.
Hey guys if you all are using mMap.clear() then remove it . Mostly it work just fine.

Adding markers to google api

I have followed some online tutorials for adding markers to the google maps api in android. There code is structured differently from mine but in general I saw them do it in the onCreate method. Below I have a really basic code to try and get a marker in the middle of the map, however, I get a null pointer exception. Does anyone know of a simple fix to this?
Here is the error in detail and below is my method. I have map declared as a global variable.
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
serviceManager = ServiceManager.getInstance(getActivity());
userID = getString(R.string.mobile_health_client_user_id);
client = MobileIOClient.getInstance(getContext(), userID);
//client = MobileIOClient.getInstance(userID);
map.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Hello world"));
}
I have also ran through the google tutorial which overrides onMapReady() but that method did not work for me either. I am not sure how to get it working in my code and can't find adequate resource online to assist me. Any help would be appreciated.
Thanks
You should not be interacting with the map object in your activity or fragment's onCreate() method. The simple reasoning being that the map probably isn't ready yet. The proper way to handle this is to implement the OnMapReadyCallback interface and add you marker in your implementation of the onMapReady(GoogleMap googleMap) function.
Your solution will need to be slightly different if you are using a MapFragment vs a MapView, but the general idea remains the same.
Example:
public class MyActivity extends Activity implements OnMapReadyCallback {
.
.
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap; // Set your local instance of GoogleMap for future use
map.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Hello world"));
}
.
.
}
If you are using a MapView, you will need to get a handle to your view in your layout and explicitly call map.getMapAsync(this) in order to attach the onMapReady() listener.
I hope this helps!
Here is the code I use:
public class Map extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
public GoogleApiClient mGoogleApiClient;
public static final String TAG = Map.class.getSimpleName();
public LocationRequest mLocationRequest;
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_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);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng here = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(here).title("Here!"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(here));
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = null;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
};
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
protected void onResume(){
super.onResume();
//setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude,longitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
Write simply in onMapReadygoogleMap.addMarker(new MarkerOptions().position(new LatLng(0, 0));

Touch listener on Google Map Markers Android

How can I add a Tab/Touch/Click listener on the Markers I have on my Google Map in android program. For example in the below image I have one marker on google maps and when clicked, I want to bring up a toast saying this has been clicked
http://i.stack.imgur.com/Bc7Lp.png
I have tried onMapClickListener but that does not work.
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
}
}
All markers in Google Android Maps Api v2 are clickable. You don't need to set any additional properties to your marker. What you need to do - is to register marker click callback to your googleMap and handle click within callback:
public class MarkerDemoActivity extends android.support.v4.app.FragmentActivity
implements OnMarkerClickListener{
private Marker myMarker;
private void setUpMap()
{
.......
googleMap.setOnMarkerClickListener(this);
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my spot!")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
......
}
#Override
public boolean onMarkerClick(final Marker marker) {
if (marker.equals(myMarker))
{
//handle click here
}
}
}
Use this
map.setOnMarkerClickListener(new OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(Marker arg0)
Toast.makeText(MainActivity.this, arg0.getTitle(),1000).show();// display toast
return true;
}
});
This will help to you :)

Categories

Resources