I have a map with a lot of markers. When you click marker, small windows with information will appear. When you click it I want to call fragment. I found that I should use onInfoWindowClick but something is wrong. I can't get any values.
public class Map extends Activity implements OnInfoWindowClickListener{
static final LatLng xxx = new LatLng(70.000, 70,22);
static String[] streets;
static String[] artist;
Coordinate cor = new Coordinate();
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
try {
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
Resources res = this.getResources();
artist = res.getStringArray(R.array.authors_nicks);
streets = res.getStringArray(R.array.streets);
for (int i = 0; i < cor.coordinatesVale.size(); i++) {
Marker m = googleMap.addMarker(new MarkerOptions()
.position(cor.coordinatesVale.get(i))
.title(artist[i])
.snippet(streets[i])
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker)));
m.getId();
}
googleMap.setMyLocationEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(xxx, 12));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
}
#Override
public void onInfoWindowClick(Marker marker) {
String id = marker.getId();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("dsdsd", 3);
startActivity(i);
Log.i("dddd", id); /// CAN't see
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
I found some tutorials, but I'm don't know what I'm doing wrong
In your initializeMap() function, right after you use getMap(), put the following code there. Using this method, you don't need to call implements OnInfoWindowClickListener, but would work the same either way.
if (googleMap != null) {
// More info: https://developers.google.com/maps/documentation/android/infowindows
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
// Determine what marker is clicked by using the argument passed in
// for example, marker.getTitle() or marker.getSnippet().
// Code here for navigating to fragment activity.
}
});
}
The above code allows you to do something when the user clicks on the info window.
In order to show the info window in the first place, use one either one of the following code snippets, which you have already:
static final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400"));
Or,
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne"));
melbourne.showInfoWindow();
Source: Google Maps Android API v2
Related
I am using the following method to move the camera:
private void moveCamera(LatLng latLng, float zoom, GoogleMap map) {
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
When I am using it inside OnMapReady like this:
private void initMapHome() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.harta_adauga_adresa_acasa);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady: map is readyyyyyyyyyyyyyyyyyyy");
gmap = googleMap;
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
gmap.setMyLocationEnabled(true);
gmap.getUiSettings().setMyLocationButtonEnabled(true);
gmap.getUiSettings().setCompassEnabled(true);
gmap.getUiSettings().setMapToolbarEnabled(false);
gmap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
});
gmap.setOnMapClickListener(latLng -> {
gmap.clear();
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title(adresa);
gmap.addMarker(options).showInfoWindow();
});
moveCamera(pozitie_curenta, DEFAULT_ZOOM, gmap);
}
});
}
The camera animates in a nice manner to the selected position, the pozitie_curenta LatLng created somewhere else in my code. Now, I have a AutoCompleteTextView that returns the places (I am using the one created by Mukesh Solanki from github), and I am looking to move the camera on the selected place from the AutoCompleteTextView. I have the following code:
adresa_home.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Place place = (Place) parent.getItemAtPosition(position);
adresa_home.setText(place.getDescription());
placesApi.fetchPlaceDetails(place.getId(), new OnPlacesDetailsListener() {
#Override
public void onPlaceDetailsFetched(PlaceDetails placeDetails) {
latitudine_acasa = placeDetails.getLat();
longitudine_acasa = placeDetails.getLng();
updateHartaHome(latitudine_acasa, longitudine_acasa, place.getDescription());
}
#Override
public void onError(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
}
);
}
});
The place is fetched correctly, and I get the latitude and longitude correctly. The method updateHartaHome is looking like this:
private void updateHartaHome(double lat, double lng, String title) {
acasa = new LatLng(lat, lng);
MarkerOptions options = new MarkerOptions()
.position(pozitie_curenta)
.title(title);
gmap.addMarker(options).showInfoWindow();
moveCamera(acasa, DEFAULT_ZOOM, null, gmap);
}
Debugging the code I've come to the conclusion that the problem it's with the moveCamera from the updateHartaHome which is never called. Setting a breakpoint on the line gmap.addMarker(options).showInfoWindow(); gets me the following:
So, eveything looks fine, but the map doesn't update and, it also doesn't add the marker. Setting the breakpoint on the moveCamera line, it never gets accesed. Any help would be appreciated, I've been going mad over this issue. Thanks!
Please try this once inside your onMapReady method
CameraPosition cameraPosition = CameraPosition.builder()
.target(new LatLng(placeLatitude, placeLongitude))
.zoom(16)
.bearing(0)
.tilt(45)
.build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
where mGoogleMap is defined as
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
if you want to add Marker do this before moving the camera
mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(placeLatitude, placeLongitude)));
EDIT:
If you want to click on the map and move the camera
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
mGoogleMap.clear();
mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(latLng.latitude, latLng.longitude)));
CameraPosition cameraPosition = CameraPosition.builder()
.target(new LatLng(latLng.latitude, latLng.longitude))
.zoom(16)
.bearing(0)
.tilt(45)
.build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
i am trying to run a geoquery everytime someone select a place from PlaceAutoComplete fragment and show the markers on the map. It is working fine for the first.When i start the app the icons are are all fine the geoquery is running fine, but when i enter a location second time the app crashes showing an error llegalArgumentException: Unmanaged descriptor below is what i am trying to do.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SupportPlaceAutocompleteFragment autocompleteFragment =
(SupportPlaceAutocompleteFragment)
getChildFragmentManager().findFragmentById
(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new
PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Toast.makeText(getContext(),place.getAddress(),Toast.LENGTH_LONG).show();
Log.i(TAG, "Place: " + place.getName());
Double latitude1 = place.getLatLng().latitude;
Double longitude1 =place.getLatLng().longitude;
LatLng latLng = new LatLng(latitude1,longitude1);
getPeople(latLng); // method to call geofire query
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
return mMainView;
}
public void getPeople(LatLng latLng1){
mMap.clear();
mMap.addCircle(new CircleOptions()
.center(latLng1)
.radius(2000)
.strokeColor(Color.BLACK)
.fillColor(0x220000FF)
.strokeWidth(1)
);
DatabaseReference ref =
FirebaseDatabase.getInstance().getReference().child("Location");
GeoFire geoFire = new GeoFire(ref);
GeoQuery geoQuery = geoFire.queryAtLocation(new
GeoLocation(latLng1.latitude, latLng1.longitude), 2);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(final String key, GeoLocation location) {
UIDLocation.put(key,location);
marker.setIcon(BitmapDescriptorFactory.fromResource
(R.drawable.ic_mapmarker2));
markers.put(key, marker);
for (Map.Entry<String,GeoLocation> entry : UIDLocation.entrySet())
{
final Marker marker = markers.get(entry.getKey());
if (marker != null) {
DatabaseReference mUser =
FirebaseDatabase.getInstance().getReference().child("People")
.child(string);
mUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
String display_name =
dataSnapshot.child("name").getValue().toString();
String status =
dataSnapshot.child("status").getValue().toString();
String image =
dataSnapshot.child("image").getValue().toString();
PeopleInfo info = new PeopleInfo();
info.setName(display_name);
info.setStatus(status);
info.setImage(image);
marker.setTag(info);
String iconName = dataSnapshot.child("iconName")
.getValue().toString();
Context context = getContext();
int id = context.getResources().getIdentifier(iconName, "drawable",
context.getPackageName());
String s = String.valueOf(id);
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),id);
marker.setIcon(BitmapDescriptorFactory.fromResource(id));
}
#Override
public void onCancelled(DatabaseError
databaseError) {
}
});
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
mUiSettings = mMap.getUiSettings();
mUiSettings.setZoomControlsEnabled(true);
mFusedLocationClient =
LocationServices.getFusedLocationProviderClient(getContext());
Task task= mFusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new
OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
markeroptn = new MarkerOptions();
markeroptn.position(myPosition);
markeroptn.title("You are Here");
mMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition,10));
getWorkMen(myPosition);
}
}
});
So far what i have learned from the posts on SO that its because the program is trying to set the icon on marker which is already there. I tried clear() map in the begining of getPeople() but still it is showing the same error.It works fine first time. i also tried remove() also but its also not working.
The problem may come from the way you manage the Marker variables. In the code, you store a marker variable as global outside of the method scope. When calling map.clear(), it makes the marker variable invalid and if somehow you still use this variable to set something, it may cause the exception. The same thing happens with the markers Map you use to map key and Marker, it's not being cleared when map.clear().
Try to manage your map elements more carefully, clear each map element dependently and avoid using map.clear().
Suggestion approach:
Create new marker
private void addMarker(String key, LatLng latLng) {
// Clear the current marker before add the new one
if (marker != null) {
marker.remove();
marker = null;
}
// Store new marker to the variable
marker = mMap.addCircle(new CircleOptions()
.center(latLng)
.radius(2000)
.strokeColor(Color.BLACK)
.fillColor(0x220000FF)
.strokeWidth(1)
);
// Add to markers map if needed
markers.put(key, marker);
}
Clear all markers (clear manually every marker variable available, don't use map.clear:
public synchronized void clear() {
// markers is the marker map
for (Marker marker : markers.values()) {
try {
marker.remove();
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
}
// Clear all the marker map
markers.clear();
// Marker is the your global marker variable
marker.remove();
}
In PostExecute i have this array name : locations
I print Log for more details like that:
[lat/lng: (18.5159983333333,-72.2916166666667), lat/lng: (18.5363383333333,-72.3231866666667), lat/lng: (18.5076266666667,-72.3164933333333), lat/lng: (18.54138,-72.2920766666667)]
And i try to show all coordinates like that
protected void onPostExecute(Boolean result) {
dialog.dismiss();
for (int i = 0; i < locations.size(); i++)
{
Double latitude = Double.valueOf(locations.get(i).latitude);
Double longitude = Double.valueOf(locations.get(i).longitude);
LatLng lng = new LatLng(latitude,longitude);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.addMarker(new MarkerOptions()
.position(lng)
.title("Test")
.icon(BitmapDescriptorFactory.fromResource(getResources().getIdentifier("Title", "drawable", getPackageName()))));
}
}
Google map shows blank. How may i resolve it please??
You can only add markers when your map is ready to receive them and that is true when
public void onMapReady(GoogleMap googleMap)
is called.
I will try to get you started with this:
You need to setup some variables:
private GoogleMap mMap;
private boolean isMapReady = false;
private ArrayList<LatLng> myLocations = null;
the ArrayList will contain your locations you get from your AsyncTask
Then you need to get the mapOnReady setup in your onCreate() Methode:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// What ever else you need
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapViewRidesFoundMap);
mapFragment.getMapAsync(this);
}
Now you need to override the onMapReady method:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Set a boolean flag to let other parts of you code
// know that the map is ready
isMapReady = true;
// If you need to get info from your marker Implement this
//mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
// #Override
// public boolean onMarkerClick(Marker marker) {
// showMarkerInfo(marker);
// return false;
// }
//});
//If you need a click listener add this
// Add implement the method 'onMapClickLocation'
//mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
// #Override
// public void onMapClick(LatLng latLng) {
// onMapClickLocation(latLng);
// }
//});
// call a function to update your locations
updateMapLocations();
}
Within your(!) protected void onPostExecute(Boolean result) add code to fill the myLocations ArrayList
protected void onPostExecute(Boolean result) {
dialog.dismiss();
myLocations = new ArrayList<LatLng>();
for (int i = 0; i < locations.size(); i++)
{
Double latitude = Double.valueOf(locations.get(i).latitude);
Double longitude = Double.valueOf(locations.get(i).longitude);
LatLng lng = new LatLng(latitude,longitude);
myLocations.put(lng);
}
// calls the update method when data is available
this.updateMapLocations();
}
and add a call to updateMapLocations() which could look like this:
private void updateMapLocations(){
// update locations won't continue unless the map is ready
if(!isMapReady) return;
// Zoom into your location !! if you need too
// with a destinationLocation of your choice
// perhaps your first location in you ArrayList
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(destinationLocation, zoomFactor));
// PseudoCode!!
// Add your for Loop
// !!! Check to see if your myLocations ArrayList is null before you continue !!!
// !!! or just add another boolean to you onPostExcecute method
// And add the Markers
//Loop Start
//float hue = BitmapDescriptorFactory.HUE_MAGENTA;
//MarkerOptions markerOptions = setMarker(latLng, hue)
// !!! You need to add your destination loop !!!
//mMap.addMarker(markerOptions);
//Loop end!
}
private MarkerOptions setMarker(LatLng latLng, float hue){
MarkerOptions markerOptions = null;
try {
float markerAlpha = 0.7f;
markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(hue));
markerOptions.position(latLng);
markerOptions.alpha(markerAlpha);
markerOptions.flat(false);
markerOptions.title("What Ever");
markerOptions.snippet("MySnippet");
markerOptions.draggable(false);
markerOptions.zIndex(0.0f);
}
catch (Exception ex){
Log.e(TAG, " setMarker --- " + ex.getMessage());
}
return markerOptions;
}
Notice that updateMapLocations() is called in both your onPostExecute() and the onMapReady() methods. The onPostExecute() might be finished before the onMapReady() is called. So that first when the map is ready the updateMapLocations() will run to completion when data and map are ready.
I wrote this in a text editor - so there will probably be a couple of syntax errors.
I have an an activity where the main view is Google maps. And I set up a marker when the map is initially loaded, but when I click on it I am not able to get the locality or anything. The maps appears, but I can't click on the marker, or tap or tap on the screen and hold to create a new marker. basically it cannot do anything...And i can't figure out why! Hope you guys can see something that I am not seeing.
Here is my main activity.
public class MapsActivity extends FragmentActivity {
//Maps
private GoogleMap mMap;
//Marker
private Marker marker;
//Location
private LocationListener locationListener = null;
private LocationManager locationManager = null;
private static final float DEFAULTZOOM = 15;
private double longitude_mapsActivity;
private double latitude_from_mapsActivity;
private String cityName_mapsActivity;
private String countryName_mapsActivity;
//ProgressBar
private ProgressBar myPB_MAPS;
//Buttons
private ImageButton fab_doneButton;
//SearchEditText
private EditText editText_Search;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
}
});
//Get user current location.
//myPB_MAPS = (ProgressBar) findViewById(R.id.myPB_MAPS);
//initialize your map
initMap();
//FAB button
fab_doneButton = (ImageButton) findViewById(R.id.activity_maps_FAB_done);
fab_doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (countryName_mapsActivity == null) {
Toast.makeText(MapsActivity.this, "Location is null", Toast.LENGTH_SHORT).show();
} else {
Global_Class.getInstance().getValue().countryName_GLOBAL = countryName_mapsActivity;
Global_Class.getInstance().getValue().cityName_GLOBAL = cityName_mapsActivity;
Global_Class.getInstance().getValue().longitude_user_GLOBAL = longitude_mapsActivity;
Global_Class.getInstance().getValue().latitude_user_GLOBAL = latitude_from_mapsActivity;
//Go to make sure we're sending all the GPS info, so we set geoLocationFromMapsIsPresent to true.
FinishCard.geoLocationFromMapsIsPresent();
FinishCard.setComingBackFromMaps();
Intent FinishCardIntent = new Intent(MapsActivity.this, FinishCard.class);
startActivity(FinishCardIntent);
}
}
});
//EditText
editText_Search = (EditText) findViewById(R.id.maps_EditText);
editText_Search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
}
});
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
}
private void performSearch()
{
String location = editText_Search.getText().toString();
if(location.length() == 0)
{
Toast.makeText(this,"Please enter a location",Toast.LENGTH_SHORT).show();
return;
}
//1-first step
Geocoder gc = new Geocoder(this);
List<Address> list = null;//For this function I only want a single address.
try
{
//3-Third step
list = gc.getFromLocationName(location,10);
}
catch (IOException e)
{
e.printStackTrace();
}
//4-Fourth step
Address add = list.get(0);//Give me the first and only item of the list.
//5-fifth step
String locality = add.getLocality();//So if you enter Taj mahal you get Agra, the place where its at, thats what Address locality does.
double lat = add.getLatitude();
double lng = add.getLongitude();
//GoToLocation() method
gotoLocation(lat, lng, DEFAULTZOOM);
//For Removing existing markers.
if(marker != null)
{
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(locality)
.position(new LatLng(lat, lng))
.draggable(true);
marker = mMap.addMarker(options);
}
private void gotoLocation(double lat, double lng, float zoom)
{
LatLng ll = new LatLng(lat,lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
private void setMarker(String locality, String country, double lat, double lng)
{
if(marker != null)
{
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(locality)
.position(new LatLng(lat, lng))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
.draggable(true);
if(country.length() > 0)
{
options.snippet(country);//Background highlight TEXT SUPER IMPORTANT
}
//.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
marker = mMap.addMarker(options);//So here we connect our marker to our map, which is used in initMap.
}
private void initMap()
{
if(mMap == null)
{
if(mMap != null)
{
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener()
{
#Override
public void onMapLongClick(LatLng ll) {
Geocoder gc = new Geocoder(MapsActivity.this);
List<Address> list = null;
try {
list = gc.getFromLocation(ll.latitude, ll.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address add = list.get(0);
MapsActivity.this.setMarker(add.getLocality(), add.getCountryName(), ll.latitude, ll.longitude);//this is where we set the orange marker.
latitude_from_mapsActivity= ll.latitude;
longitude_mapsActivity= ll.longitude;
countryName_mapsActivity = add.getCountryName();
cityName_mapsActivity = add.getLocality();
}
});
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker)
{
LatLng ll = marker.getPosition();
latitude_from_mapsActivity= ll.latitude;
longitude_mapsActivity = ll.longitude;
Geocoder gc = new Geocoder(MapsActivity.this);
//Global_Class.getInstance().getValue().cardLocality = "Paris";
List<Address> list = null;
try
{
list = gc.getFromLocation(ll.latitude, ll.longitude,1);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
Address add = list.get(0);
countryName_mapsActivity = add.getCountryName();
cityName_mapsActivity = add.getLocality();
return false;
}
catch (IndexOutOfBoundsException e)
{
return false;
}
}
});
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() //If you want to drag the original google maps marker you use this method, if you comment this out it will use the orange one.
{
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
Geocoder gc = new Geocoder(MapsActivity.this);
List<Address> list = null;
LatLng ll = marker.getPosition();
try {
list = gc.getFromLocation(ll.latitude, ll.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address add = list.get(0);
marker.setTitle(add.getLocality());
marker.setSnippet(add.getCountryName());
//marker.showInfoWindow();
}
});
}
}
}
}
Here is my xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.daprlabs.swipedeck.GeoLocation.MapsActivity">
<RelativeLayout
android:layout_width="340dp"
android:layout_height="50dp"
android:background="#FFFFFF"
android:elevation="10sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp">
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/maps_EditText"
android:imeOptions="actionSearch"
android:inputType="text"/>
</RelativeLayout>
<ProgressBar
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/myPB_MAPS"
android:layout_marginLeft="150dp"
android:layout_marginTop="55dp"/>
<ImageButton
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/circle_fab"
android:id="#+id/activity_maps_FAB_done"
android:layout_gravity="right|bottom"
android:src="#drawable/white_plus" />
</fragment>
You are contradicting yourself in your initMap().
Remove the following if statement:
if (mMap == null)
Also only call initMap() after mapFragment.getMapAsync returns. At this point, you know your map is ready to go.
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
initMap();
}
});
You are supposed to implement
OnMapReadyCallback
And in turn override
onMapReady
Now you can manipulate the Map within onMapReady. Before that, it is not certain that your Map has actually set properly.
Anything that manipulates the Map like loading markers over it and setting marker click listeners has to happen in onMapReady.
As an example of Map's manipulation at appropriate time, you can take hint from the following code where Map's camera is only set when it has properly set.
public class YourMapFragment extends Fragment implements OnMapReadyCallback {
...
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition,16));
mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + lat + "Lng:" + log));
}
...
}
I have a map which users can add different markers, but the problem is that when the markers have been added and the users leaves the app or navigates away from the map to a new activity and back to map the markers added have disappeared. I am relatively new to android app development, so could some one please assist me?
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_googlemaps);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
try {
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! aren't able to create your map", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public void onResume() {
super.onResume();
initilizeMap();
if (googleMap!=null){
googleMap.addMarker(new MarkerOptions().position(My Point)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_point_marker)));
}
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(xx.xxxxxxx,xx.xxxxxxzoom(9).bearing(0).build();
googleMap.setOnMapClickListener(this);
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(false);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
}
MarkerOptions markerOptions = new MarkerOptions()
.position(theLastPlaceThatTheUserLongClicked)
.icon(BitmapDescriptorFactory
.fromBitmap(bitmap));
haspMap.put(markerOptions, your_data);
googleMap.addMarker(markerOptions);
}
}
Thank you in advance!
Update
I have found this and think that this might help?
...........
WeakHashMap <Marker, Object> haspMap = new WeakHashMap <Marker, Object>();
..........
MarkerOptions markerOptions = new MarkerOptions()
.position(point)
.icon(BitmapDescriptorFactory
.fromBitmap(bitmap));
haspMap.put(markerOptions, your_data);
googleMap.addMarker(markerOptions);
}
}
I understand the use of the WeakHashMap and then the haspMap, but not quite sure what goes by your_data. I couldn't find an explanation for that?
Store all the latlng value in list ,whenever user click on map..and on onResume() traverse the complete list and set the stored latlng in map ..