changing getMap to GetMapAsync - java

I am trying to create an interactive infoWindow based on one of the answers from Stack Overflow.
However, I am getting an error with getMap() used in the code. Although I've tried with getMapAsync(), I'm unable to resolve the problem. Please help me. If any new code is available for an interactive infowindow with a button, then please share the code.
public class MainActivity extends AppCompatActivity {
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet;
private Button infoButton1, infoButton2;
private OnInfoWindowElemTouchListener infoButtonListener;
static final LatLng latlng1 = new LatLng(28.5355, 77.3910);
static final LatLng latlng2 = new LatLng(28.6208768, 77.3726377);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout)findViewById(R.id.map_relative_layout);
final GoogleMap googleMap = mapFragment.getMap();
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mapWrapperLayout.init(googleMap, getPixelsFromDp(this, 39 + 20));
// We want to reuse the info window for all the markers,
// so let's create only one class member instance
this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.custom_infowindow, null);
this.infoTitle = (TextView)infoWindow.findViewById(R.id.nameTxt);
this.infoSnippet = (TextView)infoWindow.findViewById(R.id.addressTxt);
this.infoButton1 = (Button)infoWindow.findViewById(R.id.btnOne);
this.infoButton2 = (Button)infoWindow.findViewById(R.id.btnTwo);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton1, getResources().getDrawable(R.drawable.btn_bg), getResources().getDrawable(R.drawable.btn_bg)){
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
Toast.makeText(MainActivity.this, "click on button 1", Toast.LENGTH_SHORT).show();
}
};
this.infoButton1.setOnTouchListener(infoButtonListener);
infoButtonListener = new OnInfoWindowElemTouchListener(infoButton2, getResources().getDrawable(R.drawable.btn_bg),getResources().getDrawable(R.drawable.btn_bg)){
#Override
protected void onClickConfirmed(View v, Marker marker) {
Toast.makeText(getApplicationContext(), "click on button 2", Toast.LENGTH_LONG).show();
}
};
infoButton2.setOnTouchListener(infoButtonListener);
/*infoWindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click on infowindow", Toast.LENGTH_LONG).show();
}
});*/
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoSnippet.setText(marker.getTitle());
infoTitle.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
// Let's add a couple of markers
googleMap.addMarker(new MarkerOptions()
.position(latlng1)
.title("Source")
.snippet("Comapny Name")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.addMarker(new MarkerOptions()
.position(latlng2)
.title("Destination")
.snippet("AmisunXXXXXX")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
//googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng1, 10));
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dp * scale + 0.5f);
}
}
The error is coming because Google has removed getMap(), but I dont know the alternative solution for this.

UPDATE
Define private GoogleMap gMapand implement OnMapReadyCallback in your main Activity and implement onMapReady method
in onMapReady you should write this line
gMap = googleMap, then you can do what you want in onMapReady
getting current location
custom setting for your map
and ...
now it's time to use this lines in your OnCreate method
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
it should solve your problem, hope it helped you

Related

Android app - Google maps location markers disappearing from Map fragment

I am very new to Android development. This is my first attempt at creating an app. I have created a tabbed navigation app, with 4 fragments to navigate between: Home, Search, Map and Account fragments from the MainActivity. I have used a SupportMapFragment within my MapsFragment to display the map. Upon visiting the MapsFragment the map displays and zooms in on my Current location and highlights certain important locations, retrieved from a Firebase instance, with markers.
Everything works as expected when I first launch the app and visit the Map Fragment. I am zoomed into my current location and I see all required markers. The problem arises when I switch to a different fragment from that point. When I navigate to the Home, Search or Account fragment and then return to the Map fragment, none of the location markers are visible anymore. I can still see my current location and get zoomed into it on opening the Map fragment but the other markers disappear.
I originally thought it was to do with the fragment being recreated everytime I navigate to another fragment as I use .replace(container, fragment) to change the fragment based on which button was clicked from the bottom navigation bar. But I observed that the Map fragment would load my current location and zoom into it correctly, so the loadMap() function gets executed but somehow the markers don't appear. If i restart the app, the markers behave correctly the first time I open the Map fragment.
Any help on how to keep the markers showing on the Map when I return to it after navigating to other fragments will be greatly appreciated. Thank you!
Here is a preview of my MapsFragment.java:
public class MapsFragment extends Fragment {
private SupportMapFragment supportMapFragment;
private AutocompleteSupportFragment autocompleteSupportFragment;
private FusedLocationProviderClient client;
private Geocoder geocoder;
private ArrayList<String> mPostCodes;
private ArrayList<Marker> searchMarker;
private DatabaseReference locationRef;
private DatabaseReference businessRef;
private String apiKey;
public MapsFragment() {
// Required empty public constructor
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Initialize Map fragment
supportMapFragment = (SupportMapFragment)
getChildFragmentManager().findFragmentById(R.id.google_map);
// initialize Places client
apiKey = getString(R.string.map_key);
if(!Places.isInitialized()){
Places.initialize(requireActivity(), apiKey);
}
PlacesClient placesClient = Places.createClient(requireActivity());
// Initialize AutoComplete search bar and set autocomplete parameters
autocompleteSupportFragment = (AutocompleteSupportFragment)
getChildFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteSupportFragment.setTypeFilter(TypeFilter.ADDRESS);
autocompleteSupportFragment.setLocationBias(RectangularBounds.newInstance(
new LatLng(55.836229, -4.252612),
new LatLng(55.897463, -4.325364)));
autocompleteSupportFragment.setCountries("UK");
autocompleteSupportFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));
// initialize search marker list
searchMarker = new ArrayList<Marker>();
// Initialize client to get user's last location on device
client = LocationServices.getFusedLocationProviderClient(requireActivity());
// Initialize geocoder to convert business postcodes to latlng coordinates
mPostCodes = new ArrayList<>();
geocoder = new Geocoder(requireActivity());
// Get business locations
locationRef = FirebaseDatabase.getInstance().getReference("Business Locations");
locationRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
for(DataSnapshot locationSnapshot : snapshot.getChildren()){
BusinessLocation location = locationSnapshot.getValue(BusinessLocation.class);
mPostCodes.add(location.getPostCode());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.i("Location error", "Error retrieving location: ", error.toException().getCause());
}
});
// initialize reference to business table
businessRef = FirebaseDatabase.getInstance().getReference("Businesses");
// render the map
loadMap();
}
private void loadMap() {
if (ActivityCompat.checkSelfPermission(requireActivity(),
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Task<Location> task = client.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
// autocomplete place search
autocompleteSupportFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onError(#NonNull Status status) {
Log.i("AutoComplete error", "error status: " + status);
}
#Override
public void onPlaceSelected(#NonNull Place place) {
LatLng placeLatLng = place.getLatLng();
MarkerOptions placeOptions = new MarkerOptions().position(placeLatLng)
.title("search")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
if(!searchMarker.isEmpty()){
Marker searchedMarker = searchMarker.get(0);
searchMarker.remove(searchedMarker);
searchedMarker.remove();
}
final Marker marker = googleMap.addMarker(placeOptions);
searchMarker.add(marker);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(placeLatLng, 10));
}
});
LatLng myLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
// show current location
if (ActivityCompat.checkSelfPermission(requireActivity(),
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
}
// show markers for all businesses on database
for(String code : mPostCodes){
try{
Address address = geocoder.getFromLocationName(code, 1).get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
MarkerOptions options = new MarkerOptions().position(latLng);
googleMap.addMarker(options);
}catch (IOException e){
Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLatLng, 10));
}
});
}
}
});
}else {
ActivityCompat.requestPermissions(requireActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44);
}
}
private ActivityResultLauncher<String> mPermissionResult = registerForActivityResult(
new ActivityResultContracts.RequestPermission(),
result -> {
if(result){
loadMap();
}
}
);
}
Here is my fragment_maps.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".fragments.MapsFragment">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/google_map"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
<fragment
android:id="#+id/autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"/>
</RelativeLayout>
And here is my MainActivity.kt file:
class MainActivity : AppCompatActivity() {
private val homeFragment = HomeFragment()
private val searchFragment = SearchFragment()
private val mapFragment = MapsFragment()
private val accountFragment = AccountFragment()
private val guestAccountFragment = GuestAccountFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
replaceFragment(homeFragment)
bottom_navigation.setOnItemSelectedListener {
when (it.itemId) {
R.id.id_home -> replaceFragment(homeFragment)
R.id.id_search -> replaceFragment(searchFragment)
R.id.id_map -> replaceFragment(mapFragment)
R.id.id_account -> {
if(FirebaseAuth.getInstance().currentUser == null){
replaceFragment(guestAccountFragment)
}else {
replaceFragment(accountFragment)
}
}
}
true
}
}
private fun replaceFragment(fragment : Fragment){
if(fragment != null){
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment_container, fragment)
transaction.commit()
}
}
}
It happening beacuse your map fragment is "dying" after replacing on new fragment. Try this solution:
First of all you need add in your main activity all required fragments which can be called:
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_view, fragment1)
.add(R.id.fragment_container_view, fragment2)
.add(R.id.fragment_container_view, fragment3)
.commit();
After adding you can change them by calling this code:
getSupportFragmentManager().beginTransaction()
.show(fragment2)
.hide(fragment1)
.commit();
Code was writen on Java but I think there is no problem

Why does my for loop not make each marker unique in my google maps activity

I am trying to open a new activity when a user clicks on the window of a marker.
Now I am doing everything correctly it seems and it even works but only for one single shop, it brings all the information from that single shop and places it in every marker every time a user clicks it.
I am wondering why this is happening and why is my shop object not being unique to each marker since its inside of a for loop.
When I open any window from any marker it takes me to the same shop details which in my case is "Starbucks". Why is that?
Here is the code:
public void onMapReady(final GoogleMap googleMap) {
CollectionReference mapRef = fStore.collection("Shops");
Query mapQuery = mapRef;
mapRef.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(final QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots){
final Shop shop = documentSnapshot.toObject(Shop.class);
String Lat = shop.getLatitude();
String Long = shop.getLongitude();
float latitude = Float.parseFloat(Lat);
float longitude = Float.parseFloat(Long);
final LatLng shopLoc = new LatLng(latitude, longitude);
final Marker markers = googleMap.addMarker(new MarkerOptions()
.position(shopLoc)
.title(""+shop.getName())
.snippet(shop.getShopPID()));
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent i = new Intent(MapActivity.this,DetailsActivity.class);
i.putExtra("shopModel",shop);
startActivity(i);
}
});
}
}
});
}
i solved it!!!
i did some research and there were other stackoverflow answers to this question. i just took out the oninfoclick outside the for loop and did as follows:
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(shopLoc)
.title(""+shop.getName()).snippet("Click to view shops information"));
marker.setTag(shop);
and then outside the for loop i did this:
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent i = new Intent(MapActivity.this,DetailsActivity.class);
Shop shop2 = (Shop) marker.getTag();
i.putExtra("shopModel",shop2);
startActivity(i);
}
});

getting error with getMap()?

I am trying for interactive infoWindow with one of the answer of stack overflow.
link is given below:
interactive infowindow
but i am getting error with getMap() used in the code. although I tried with getMapAsync but unable to resolve the problem. please help me asap.If any new code available for interactive infowindow with button then please share the code.
public class MainActivity extends Activity {
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet;
private Button infoButton;
private OnInfoWindowElemTouchListener infoButtonListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout)findViewById(R.id.map_relative_layout);
final GoogleMap map = mapFragment.getMap();
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mapWrapperLayout.init(map, getPixelsFromDp(this, 39 + 20));
// We want to reuse the info window for all the markers,
// so let's create only one class member instance
this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.info_window, null);
this.infoTitle = (TextView)infoWindow.findViewById(R.id.title);
this.infoSnippet = (TextView)infoWindow.findViewById(R.id.snippet);
this.infoButton = (Button)infoWindow.findViewById(R.id.button);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
getResources().getDrawable(R.drawable.btn_default_normal_holo_light),
getResources().getDrawable(R.drawable.btn_default_pressed_holo_light))
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton.setOnTouchListener(infoButtonListener);
map.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
// Let's add a couple of markers
map.addMarker(new MarkerOptions()
.title("Prague")
.snippet("Czech Republic")
.position(new LatLng(50.08, 14.43)));
map.addMarker(new MarkerOptions()
.title("Paris")
.snippet("France")
.position(new LatLng(48.86,2.33)));
map.addMarker(new MarkerOptions()
.title("London")
.snippet("United Kingdom")
.position(new LatLng(51.51,-0.1)));
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dp * scale + 0.5f);
}
}
error is coming because of google has removed getMap but dont know the alternative solution for this.
Error:(149, 42) error: cannot find symbol method getMap()
Your Existing Code is:
final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
final GoogleMap map = mapFragment.getMap();
Try this instead of that:
MapFragment mapFragment; // declare in global scope
GoogleMap googleMap; // declare in global scope
Put this code in OnCreate method:
mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(false); // false to disable
googleMap.setOnMarkerClickListener(onMarkerClick);
googleMap.setOnInfoWindowClickListener(onInfoWindowClick);
googleMap.getUiSettings().setZoomControlsEnabled(true);// Display Zoom Controls
googleMap.setMyLocationEnabled(true);// Display My Location Control
}
});
}
for converting pixels into DP use this:
public int getPixelsFromDp(int px){
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
return Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
Use getMapAsync in your onCreatView() method
((SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map))
.getMapAsync(this)
Also imeplement the OnMapReadyCallback interface, and override it's method
In method onMapReady() which belongs to onMapReadyCallback interface do all the operations with your map you need. It will look like after your manipulations next
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// some action with our map
mMap.addMarker(new MarkerOptions().position(randomPosition).title("Random Title"));
mMap.addMarker(new MarkerOptions().position(antoherRandomPosition).title("Another RND Title"));
// some processes with db
DataBaseMapFragment database = new DataBaseMapFragment(dbHelper, mMap);
database.createBD();
// permission to check, if gps access is granted
if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
//another actions with map
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(camera, 13));
mMap.setBuildingsEnabled(true);
mMap.setOnMapLongClickListener(this);
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
mMap.setOnMarkerClickListener(this);
reffering Google documentation and guide.
Check it to learn more about maps in android and to be clear about
The getMap() function replaced from getMapAsync() more here
https://developers.google.com/android/reference/com/google/android/gms/maps/package-summary

Maps marker point image with picasso not loaded at first time

I'm implementing android Mapview with Custom marker. I'm using picasso to load image into marker view. And when i launch the app at the first time, it shows me all the markers, but only one marker that has loaded from database with picasso, the other markers are not loaded from database, they only show me the default maps marker pin. But when i go to the previous activity and go back into MapsActivity, it shows me all the markers that loaded from database with picasso.
Here's my PicassoMarker class
public class PicassoMarker implements Target {
Marker mMarker;
PicassoMarker(Marker marker) {
mMarker = marker;
}
#Override
public int hashCode() {
return mMarker.hashCode();
}
#Override
public boolean equals(Object o) {
if(o instanceof PicassoMarker) {
Marker marker = ((PicassoMarker) o).mMarker;
return mMarker.equals(marker);
} else {
return false;
}
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
mMarker.setIcon(BitmapDescriptorFactory.fromBitmap(bitmap));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
//mMarker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.here));
}
}
Here's the method in MapsActivity
public void plotMarkers(ArrayList<MyMarker> markers) {
if(markers.size() > 0) {
for (MyMarker myMarker : markers)
{
markerOption = new MarkerOptions().position(new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude()));
location_marker = mMap.addMarker(markerOption);
target = new PicassoMarker(location_marker);
Picasso.with(MapsActivity.this).load(myMarker.getmIcon()).resize(84, 125).into(target);
mMarkersHashMap.put(location_marker, myMarker);
i = getIntent();
if(i.getBooleanExtra("maps", true)) {
buttonNavigasi.setVisibility(View.VISIBLE);
location_marker.setTitle(i.getStringExtra("nama"));
dest = new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(dest, 16));
}
else {
mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
}
}
}
}
What's going wrong here?
Thanks.
Okay, so I managed to reproduce what you are experiencing and found what was causing your problem. In the code you provided, notice this line in MapsActivity:
target = new PicassoMarker(location_marker);
I presumed that you are using a global single variable for target. I added some logs and managed to see that the only Marker that gets the image loaded using Picasso is the last Marker in the for loop.
The reason is because, every time you enter the loop, the value of target changes to the newer PicassoMarker that you have, making the onBitmapLoaded of the previous PicassoMarker you have useless, since it no longer has a target. :(
So what I did is, I just added a List<Target> variable (make sure you don't forget to initialize it) to store the instances of the targets. In the line where that I specified earlier, I just added the code to store the value of the target to the list, like so:
Target target = new PicassoMarker(location_marker);
targets.add(target);
Tested it on my emulator and it loads the images to all the Markers.
EDIT
Here is the Activity code I used to reproduce your error and then modified it to make it work:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
Intent i;
MarkerOptions markerOption;
List<Target> targets;
HashMap<Marker, MyMarker> mMarkersHashMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mMarkersHashMap = new HashMap<>();
targets = new ArrayList<>();
// 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));
ArrayList<MyMarker> markers = new ArrayList<MyMarker>();
MyMarker m1 = new MyMarker(new LatLng(-34, 151.1), "https://developer.chrome.com/extensions/examples/api/idle/idle_simple/sample-128.png");
MyMarker m2 = new MyMarker(new LatLng(-34, 151.2), "https://developer.chrome.com/extensions/examples/api/idle/idle_simple/sample-128.png");
MyMarker m3 = new MyMarker(new LatLng(-34, 151.3), "https://developer.chrome.com/extensions/examples/api/idle/idle_simple/sample-128.png");
markers.add(m1);
markers.add(m2);
markers.add(m3);
plotMarkers(markers);
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Log.d(MapsActivity.class.getSimpleName(), "MARKER Longitude: " + marker.getPosition().longitude);
return false;
}
});
}
public void plotMarkers(ArrayList<MyMarker> markers) {
if (markers.size() > 0) {
for (MyMarker myMarker : markers) {
markerOption = new MarkerOptions().position(new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude()));
Marker location_marker = mMap.addMarker(markerOption);
Target target = new PicassoMarker(location_marker);
targets.add(target);
Picasso.with(MapsActivity.this).load(myMarker.getmIcon()).resize(84, 125).into(target);
mMarkersHashMap.put(location_marker, myMarker);
i = getIntent();
if (i.getBooleanExtra("maps", true)) {
// buttonNavigasi.setVisibility(View.VISIBLE);
location_marker.setTitle(i.getStringExtra("nama"));
LatLng dest = new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(dest, 8f));
} else {
Log.d(MapsActivity.class.getSimpleName(), "In else{}");
// mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
}
}
}
}
}

Google maps api v2 show all markers title always without any click

I need that in my Map-application Google map markers title always will be shown without any user click. I want that this title even will not be possible hide.
Of course I searched online, and I found this: marker.showInfoWindow(); but it is not working because I have near to 30 markers and I need that all of them will be shown all the time (I guess marker.showInfoWindow(); working just when there is one marker).
............................................................................
(And I would like to know how to do that when map activity will start it will not show whole world from far, but from specific country. I mean already zoomed to this country.)
public class Map extends Activity {
static LatLng Sapphire = new LatLng(41.085078, 29.006100);
static LatLng Metrocity = new LatLng(41.076138, 29.010518);
static LatLng Istinye = new LatLng(41.114247, 29.058924);
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMyLocationEnabled(true);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
Marker marker = googleMap.addMarker(new MarkerOptions().position(Sapphire).title("Istanbul Sapphire").snippet("Levent")); marker.showInfoWindow();
Marker marker1 = googleMap.addMarker(new MarkerOptions().position(Metrocity).title("Metrocity").snippet("Levent")); marker1.showInfoWindow();
Marker marker2 = googleMap.addMarker(new MarkerOptions().position(Istinye).title("Istinye Park").snippet("Istinye/ Pınar Mh.")); marker2.showInfoWindow();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories

Resources