How to use getMapAsync() instead of getMap() - android

I am aware that in Play Services, getMap() is depreciated, and is replaced by getMapAsync().
But I am not sure how to use getMapAsync(). I found other questions similar to this -- however, in my code, I am not sure what to implement in my getMapAsync(). I think it is supposed to be a callback method, but I am not sure.
Could someone please put the correct code in, and tell me what I am doing wrong?
public class FindParty extends AppCompatActivity {
static final LatLng Durban = new LatLng(-29.858680, 31.021840);
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_party);
try{
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMapAsync();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
final Marker marker_Durban = googleMap.addMarker(new MarkerOptions()
.position(Durban)
.snippet("Durban, KwaZulu-Natal, South Africa")
.title("Durban"));
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
if (marker.getTitle().equals("Durban")) {
Intent intent = new Intent(FindParty.this, Party.class);
intent.putExtra("message", "Durban");
startActivity(intent);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}

your class need to implements OnMapReadyCallback
public class FindParty extends AppCompatActivity implements OnMapReadyCallback {
static final LatLng Durban = new LatLng(-29.858680, 31.021840);
private GoogleMap googleMap;
MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_party);
try {
if (googleMap == null) {
mapFragment = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
mapFragment.getMapAsync(this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
final Marker marker_Durban = googleMap.addMarker(new MarkerOptions()
.position(Durban)
.snippet("Durban, KwaZulu-Natal, South Africa")
.title("Durban"));
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
if (marker.getTitle().equals("Durban")) {
Intent intent = new Intent(FindParty.this, Party.class);
intent.putExtra("message", "Durban");
startActivity(intent);
}
}
});
}
}

You are right, getMapAsync() is based on callback, please see belowe example and move your map options settings to callback method:
Example

getMapAsync() { it.isTrafficEnabled = false }

The better way I found to understand the use of getMapAsync was to create a new project in Android Studio and use the template of google maps activity instead of an empty activity.
Hope help others with the same difficulty.

Related

I have a problem using onMarkerClickListeners. I am a beginner and there is an error appearing that says Missing return statement

I am getting that error in the last Override.
I really do not know what I need to return so please help me.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;
private Marker myMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng MORNAR = new LatLng(43.5201139, 16.4282208);
googleMap.setOnMarkerClickListener(this);
mMap.addMarker(new MarkerOptions().position(MORNAR).title("Stari mornar"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(MORNAR));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(MORNAR, 13));
}
#Override
public boolean onMarkerClick(final Marker marker) {
String name= marker.getTitle();
if (name.equalsIgnoreCase("Stari mornar"))
{
openActivity3();
}
}
public void openActivity3(){
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
}
Change the maker click listener to this
#Override
public boolean onMarkerClick(final Marker marker) {
String name= marker.getTitle();
if (name.equalsIgnoreCase("Stari mornar"))
{
openActivity3();
return true;
}
return false;
}
Here the method shows that it returns boolean.
So if you click the marker and the function returns true, that means the click event is successful, and if it returns false info windows will show as usual.
In the last override method (onMapReady(Marker)) you need to return a boolean, since it is mandatory.
#Override
public boolean onMarkerClick(final Marker marker) {
String name= marker.getTitle();
if (name.equalsIgnoreCase("Stari mornar"))
{
openActivity3();
}
// return true or false
}
If you return true, that means you have clicked on the marker.
After the privacy accessor of your function ("public") you have your returning type, which is boolean in this case.
Let me know if this helped! ;)

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.

How to set method onItemClick to open a Google Maps?

I'm building an app, and I run on a problem with Google Maps. I wrote most of the code, but I don't how how to set that when user clicks on item(method onItemClick), in my case I have ListView on Firebase that is showing Tours of concerts, which you can see here:my tours listview to open a specific place and show it on map. For example, user clicks on Anaheim, CA concert and it shows where that place is. Thanks in advance.
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int REQUEST_LOCATION_PERMISSION = 10;
private GoogleMap.OnMapClickListener mCustomOnMapClickListener;
private GoogleMap mGoogleMap;
private MapFragment mMapFragment;
#BindView(R.id.lvTours) ListView lvTours;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
this.initialize();
}
public void initialize(){
this.mMapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.fGoogleMap);
this.mMapFragment.getMapAsync(this);
this.mCustomOnMapClickListener = new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
MarkerOptions newMarkerOptions = new MarkerOptions();
newMarkerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.tour));
newMarkerOptions.title("Tour");
newMarkerOptions.snippet("It' was here!");
newMarkerOptions.position(latLng);
mGoogleMap.addMarker(newMarkerOptions);
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.mGoogleMap = googleMap;
UiSettings uiSettings = this.mGoogleMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true);
uiSettings.setMyLocationButtonEnabled(true);
uiSettings.setZoomGesturesEnabled(true);
this.mGoogleMap.setOnMapClickListener(this.mCustomOnMapClickListener);
}
private boolean hasLocationPermission() {
String LocationPermission = android.Manifest.permission.ACCESS_FINE_LOCATION;
int status = ContextCompat.checkSelfPermission(this, LocationPermission);
if (status == PackageManager.PERMISSION_GRANTED) {
this.mGoogleMap.setMyLocationEnabled(true);
return true;
}
return false;
}
private void requestPermission() {
String[] permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(MapActivity.this, permission, REQUEST_LOCATION_PERMISSION);
}
#OnItemClick(R.id.lvTours)
public void onClick()
{
}
}
Since you have your coordinates, you can build a LatLng(latitude, longitude) object
then you can move the camera of your map like this:
build a new camera position using CameraPosition.Builder() and then ask to your mGoogleMap to animate to that position:
CameraPosition position = CameraPosition.builder()
.target(location)
.zoom(16f)
.bearing(0.0f)
.tilt(0.0f)
.build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position), null)
using that position you can even put a marker on the map:
mGoogleMap.addMarker(new MarkerOptions().position(position)
.title("some title"));

How can I post a marker onto Google Maps from a separate fragment?

I'm trying to post a marker onto a map from a separate fragment. So when you tap a button, the fragment manager will take you to the map fragment and then show you your newly placed marker. But I'm having some (nullPointer) issues.
I'm getting a null pointer because I'm trying to add a marker before the map loads. I've tried some methods to find a way to add the marker when the map is ready but I couldn't get anything to work.
Is there a clean solution to adding a marker when the map is ready?
Also, here's the error that comes up:
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
EDIT: The way I'm getting the marker information (LatLng) is with a method I found on stackoverflow. What it does is, it takes the address from an EditText and retrieves the Latitude and Longitude points from it. I use that to store it into 'marker' and 'point'. The method is found below...
UPDATE: It no longer gives me a null exception. The MapFragment loads but there's no marker to be seen.
In my PostFragment class:
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setUpSpinners();
Button button = (Button) getActivity().findViewById(R.id.postButton);
button.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
EditText editEvent = (EditText) getActivity().findViewById(R.id.map_location);
point = getLocationFromAddress(getActivity()
.getApplicationContext(), editEvent.getText().toString());
marker = new MarkerOptions().position(
new LatLng(point.latitude, point.longitude)).title("New Marker");
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frag, new GoogleMapFragment()).commit();
}
}
);
}
public void addThisMarker(GoogleMap googleMap) {
googleMap.addMarker(marker
.position(point)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
}
And in my MapFragment class:
#Override
public void onMapReady(GoogleMap googleMap) {
globalMap = googleMap;
setUpMap(); //just enabling some map properties here
PostFragment x = new PostFragment();
x.addThisMarker(globalMap);
}
**And this is the method I'm using, in PostFragment, to retrieve LatLng from an address
public LatLng getLocationFromAddress(Context context, String strAddress) {
Geocoder coder = new Geocoder(context);
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng(location.getLatitude(), location.getLongitude());
} catch (Exception ex) {
ex.printStackTrace();
}
return p1;
}
You can do it like this:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
MapFragment fMap = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
fmap.getMapAsync(this);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
map = googleMap;
// Draw your marker here
}
}

Call another fragment page when clicking google map infowindow

I am using retrofit to fetch data online.However I cannot find any solution to my problem. I want to call another fragment and display more of the details about the marker I clicked and pass those values to another fragment. Can someone please help me on this. Any help and solutions are well appreciated.
MapFragment.jav
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(getString(R.string.fine_dinings))
.build();
RestaurantPlacesApiInterface restaurantPlacesApiInterface =
adapter.create(RestaurantPlacesApiInterface.class);
restaurantPlacesApiInterface.getStreams(new Callback<List<RestaurantPlaces>>() {
#Override
public void success(List<RestaurantPlaces> restaurantPlaces, Response response) {
for (RestaurantPlaces restaurantPlace : restaurantPlaces){
MarkerOptions options = new MarkerOptions().position(new LatLng(restaurantPlace.getLatitude(),
restaurantPlace.getLongitude()));
options.title(restaurantPlace.getName());
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
getMap().addMarker(options);
}
}
#Override
public void failure(RetrofitError error) {
}
});
}
You need to use this:
#Override
public boolean onMarkerClick(Marker marker) {
// call fragment and pass data.
return false;
}
If you return false the click is not consumed.
If you need help implementing this let me know, it's fairly simple.
Here is a quick sample, please change the names to match your own code:
public class MapActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
private GoogleMap mGoogleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
initMap();
}
public void initMap() {
MapFragment map = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
map.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
if (googleMap != null) {
mGoogleMap = googleMap;
mGoogleMap.setOnMarkerClickListener(this);
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Now make your retrofit call
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ERROR", "GOOGLE MAPS NOT LOADED");
}
}
#Override
public boolean onMarkerClick(Marker marker) {
Bundle bundle = new Bundle();
bundle.putString("myString", "value");
// set Fragment class Arguments
MyFragment myFragment= new MyFragment();
myFragment.setArguments(bundle);
// launch fragment
return false;
}
}
better to use interface in fragment and implement that interface in (activity where RestAdapter used)

Categories

Resources