Add Makrer not working android - android

public class MapActivity extends SherlockFragmentActivity{
// Google Map
private GoogleMap googleMap;
String longitude="0";
String latitude="0";
String title="";
#Override
protected void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}}
catch(Exception eos)
{
}
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
try
{
if (googleMap == null) {
String longitude="27.175015";
String latitude="78.042155";
double savedLat = Double.parseDouble(longitude);
double savedLng =Double.parseDouble(latitude);
LatLng cameraLatLng = new LatLng(savedLat, savedLng);
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.addMarker(new MarkerOptions()
.position(new LatLng( Float.parseFloat(latitude), Float.parseFloat(longitude))).title("Marker")
.title("mazen"));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(cameraLatLng, 17));
// check if map is created successfully or not
if (googleMap == null) {
}
}
}
catch(Exception e)
{
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
overridePendingTransition(R.anim.dux_sld_lft_in,
R.anim.dux_sld_lft_out);
return true;
}else {
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
overridePendingTransition(R.anim.dux_sld_lft_in, R.anim.dux_sld_lft_out);
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return true;
}
}
am adding markers here, but no markers are showing why? also how can i add multiple markers to multiple places? it very funny error...because i really did exacty as tutorial i read..
hope someone can feed me with nessary help needed to finish this task

use addMarker()
like :
myMap.addMarker(new MarkerOptions().position(yourLatLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.yourmarkericon)));
where myMap is the Object of GoogleMap and yourLatlng is Latlng Where you want to add marker and yourmarkericon is icon which you want to display on map
References
https://developers.google.com/maps/documentation/android/marker
https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/model/Marker
Simple Tutorial
http://bon-app-etit.blogspot.be/2012/12/add-informationobject-to-marker-in.html

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! ;)

How to use getMapAsync() instead of getMap()

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.

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)

How to add title, snippet and icon to ClusterItem?

I had this activity:
public class MapViewer extends Activity {
private GoogleMap map;
private Database db = new Database(this);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapviewer);
try {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (map != null) {
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.getUiSettings().setRotateGesturesEnabled(false);
this.addMerchantMarkers(new MarkerOptions());
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public void addMerchantMarkers(MarkerOptions mo) {
SQLiteDatabase dbRead = db.getReadableDatabase();
Cursor result = dbRead.rawQuery("SELECT title, addr, lat, lon FROM users", null);
while(result.moveToNext()) {
map.addMarker(mo.position(new LatLng(result.getFloat(2), result.getFloat(3)))
.title(result.getString(0))
.snippet(result.getString(1))
);;
}
}
}
that i changed in the following way to use markers clustering:
public class MapViewer extends Activity {
private GoogleMap map;
private Database db = new Database(this);
private ClusterManager<MyItem> mClusterManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapviewer);
try {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (map != null) {
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.getUiSettings().setRotateGesturesEnabled(false);
setUpClusterer();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void setUpClusterer() {
mClusterManager = new ClusterManager<MyItem>(this, map);
map.setOnCameraChangeListener(mClusterManager);
map.setOnMarkerClickListener(mClusterManager);
addItems();
}
private void addItems() {
SQLiteDatabase dbRead = db.getReadableDatabase();
Cursor result = dbRead.rawQuery("SELECT lat, lon, title, addr FROM users", null);
while(result.moveToNext()) {
MyItem offsetItem = new MyItem(result.getFloat(0), result.getFloat(1));
mClusterManager.addItem(offsetItem);
}
}
}
Now i don't know how to add title, snippet and icon to every marker like previous code.
Now if i click on single marker nothing happens...
How to get that?
Here you should work with ClusterManager itself.
For example, setting on cluster item click:
mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<MyItem>() {
#Override
public boolean onClusterItemClick(MyItem item) {
//put your code here
return false;
}
});
And there are other different methods in ClusterManager class.
You'll need a less obvious code to assign info window to marker or cluster - you should use this code:
mClusterManager.getMarkerCollection().setOnInfoWindowAdapter(new MarkerInfoWindowAdapter());
mClusterManager.getClusterMarkerCollection().setOnInfoWindowAdapter(new ClusterInfoWindow());
There MarkerInfoWindowAdapter and ClusterWindowAdapter is your classes, which implements GoogleMap.InfoWindowAdapter.
With icons it's a little harder, because clustering changes icons to default. You should use method:
public void setRenderer(com.google.maps.android.clustering.view.ClusterRenderer<T> view)
You could your own renderer class and override some methods. For example, to set custom icons use such a class:
class OwnIconRendered extends DefaultClusterRenderer<MyItem> {
public OwnIconRendered(Context context, GoogleMap map,
ClusterManager<MyItem> clusterManager) {
super(context, map, clusterManager);
}
#Override
protected void onBeforeClusterItemRendered(MyItem item, MarkerOptions markerOptions) {
markerOptions.icon(item.getIcon());
markerOptions.snippet(item.getSnippet());
markerOptions.title(item.getTitle());
super.onBeforeClusterItemRendered(item, markerOptions);
}
}
And use it in such way:
mClusterManager.setRenderer(new OwnIconRendered(activity.getApplicationContext(), getMap(), mClusterManager));

Android: MapView not responding after Resume

I have a strange problem with a com.google.android.gms.maps.MapView.
To check if my App crashes after the garbage collector is doing his job i force my HTC One (4.2.2) to allow only 1 running app in background. If I leave my app(home button) while showing a MapView, start any other app and resume to my app, my MapView is still showing up...but I can not move or zoom the map, it's not responding at all. Other activities are working fine. I really have no clue where the problem might be.
Hope that someone can help me out?
Here is the sourcecode of my fragment that shows the MapView
public class FragmentAdvertlistMap extends Fragment {
com.google.android.gms.maps.MapView m;
GoogleMap mMap;
ArrayList<Advert> ads;
HashMap<Marker, String> myMarker;
public final LatLngBounds.Builder builder= new LatLngBounds.Builder();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
View inflatedView = inflater.inflate(R.layout.activity_advert_tab2, container, false);
m = (com.google.android.gms.maps.MapView)inflatedView.findViewById(R.id.map_tab);
m.onCreate(savedInstanceState);
myMarker = new HashMap<Marker, String>();
ads= AdvertListActivity.getAdverts();
setUpMapIfNeeded(inflatedView);
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent myIntent = new Intent(getActivity(), AdvertLocationActivity.class);
Advert putadvert = DefaultApplication.dbc.getAdvertForAdvertID(Integer.parseInt(myMarker.get(arg0)));
myIntent.putExtra("advert", putadvert);
startActivity(myIntent);
}
});
return inflatedView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((com.google.android.gms.maps.MapView) inflatedView.findViewById(R.id.map_tab)).getMap();
if (mMap != null) {
this.initMarker();
}
}
}
public void initMarker(){
for(int i=0;i<ads.size();i++){
Advert tempAd = ads.get(i);
LatLng tlalo = new LatLng(tempAd.mainLocation.latitude,tempAd.mainLocation.longitude);
builder.include(tlalo);
String address = "";
if(tempAd.mainLocation.contact_street != null){
address = address + tempAd.mainLocation.contact_street;
}
if(tempAd.mainLocation.contact_street_number != null){
address = address + " " + tempAd.mainLocation.contact_street_number;
}
Marker marker = mMap.addMarker(new MarkerOptions()
.position(tlalo)
.anchor(0.5f, 0.5f)
.title(tempAd.name)
.snippet(address)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.androidpin)));
myMarker.put(marker,String.valueOf(tempAd.myid));
}
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
mMap.setOnCameraChangeListener(null);
}
});
}
#Override
public void onResume() {
super.onResume();
m.onResume();
}
#Override
public void onPause() {
super.onPause();
m.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
m.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
m.onLowMemory();
}
}
try add this in onCreateView()
container.removeAllViews();
I found it in another similar question to yours but I lost the original link of the answer...

Categories

Resources