android - ProgressDialog while loading Google Maps - android

I have an Activity that implements Google Maps.When I start it, the activity stops for a few seconds, until the Map is completely loaded.
I would like to use a ProgressDialog until the map does not load, but I can not start it in a background thread, since the map must be loaded in the main thread, as explained in this link.
How can I make it without using the AsyncTask?
Otherwise, is there a way to start the activity immediately and show the not loaded map with the gray background as does the Google Maps application?
That's the code of the onCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mappa);
databaseHelper = new MyDatabaseHelper(this);
Bundle b = getIntent().getExtras();
String placeAddress= "";
if(b != null)
placeAddress= b.getString("indirizzo");
setUpMapIfNeeded();
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
gMap.setMyLocationEnabled(true);
UiSettings settings = gMap.getUiSettings();
settings.setMyLocationButtonEnabled(true);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
double lat = location.getLatitude();
double lng = location.getLongitude();
position = new LatLng(lat, lng);
if(!placeAddress.equals("")){
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> indirizzi = null;
try {
indirizzi = geocoder.getFromLocationName(placeAddress, 1);
} catch (IOException e) {
e.printStackTrace();
}
double latLuogo = indirizzi.get(0).getLatitude();
double lngLuogo = indirizzi.get(0).getLongitude();
LatLng luogo = new LatLng(latLuogo, lngLuogo);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(luogo)
.zoom(15)
.build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
else{
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(position)
.zoom(15)
.build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
LocationListener listener = new LocationListener() {
public void onLocationChanged(Location location){
//makeUseOfNewLocation(location);
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
locationManager.requestLocationUpdates(provider, 0, 10, listener);
ConnectivityManager connMngr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMngr.getActiveNetworkInfo();
if(checkConnection(netInfo) == true ){
loadFromDatabase(); //load markers
gMap.setInfoWindowAdapter(new InfoWindowAdapter(){
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
String nome = marker.getTitle();
String indirizzo = marker.getSnippet();
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
TextView title = (TextView)v.findViewById(R.id.titleInfoWindow);
title.setText(nome);
TextView snippet = (TextView)v.findViewById(R.id.snippetInfoWindow);
snippet.setText(indirizzo);
ImageView imView = (ImageView)v.findViewById(R.id.info_windowImageView);
impostaImmagine(imView, nome);
return v;
}
});
gMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
final String nome = marker.getTitle();
final String indirizzo = marker.getSnippet();
startLuogoActivity(nome, indirizzo);
}
});
final Geocoder geocoder = new Geocoder(this, Locale.getDefault());
gMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
List<Address> addresses = null;
if(checkConnection(netInfo) == true){
try {
addresses = geocoder.getFromLocation(point.latitude, point.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if(addresses!=null){
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
String indirizzo = address + ", " + city + ", " + country;
final Dialog addByClickDialog = onCreateDialogADDByClick(getBaseContext(), indirizzo);
addByClickDialog.show();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(50);
}else{
final Dialog nessunaConnessioneDialog = onCreateDialogNessunaConnessione(getBaseContext());
nessunaConnessioneDialog.show();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(50);
}
}
else{
final Dialog nessunaConnessioneDialog = onCreateDialogNessunaConnessione(getBaseContext());
nessunaConnessioneDialog.show();
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(50);
}
}
});
Button addButton = (Button)findViewById(R.id.addButton);
final Dialog addDialog;
if(checkConnection(netInfo) == false){
addDialog = onCreateDialogADD(getBaseContext(), false);
}else{
addDialog = onCreateDialogADD(getBaseContext(), true);
}
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
addDialog.show();
}
});
Button deleteButton = (Button)findViewById(R.id.deleteButton);
final Dialog deleteDialog;
if(checkConnection(netInfo) == false){
deleteDialog = onCreateDialogDELETE(getBaseContext(), false);
}else{
deleteDialog = onCreateDialogDELETE(getBaseContext(), true);
}
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteDialog.show();
}
});
}

Check the answer by #commonsware on ProgressDialog not shown in UIThread question. It might not be a good idea to use ProgressDialog for a MapActivity because time it takes to display a MapView is mostly dependent upon the Internet connection back to the Google Maps servers. You have no way to know when the MapView is done loading, so you have no way to know when to dismiss the dialog. But still if you are very sure that it will always load and will take less time, then you can read more here. You may also want to see the relate question which points to same link: Android : showDialog when setContentView loading
Hope this helps.

I finally solved the problem!I used the code present in this tutorial.
All I had to do is to load the map and the markers in the point of this code where is present the "setContentView(R.layout.main);" call.

Follow below Steps:
1)Implements GoogleMap.OnMapLoadedCallback.
Callback interface for when the map is ready to be used.
2)ProgressDialog code inside onCreate Method.
//show Progress
3)onMapReady method
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "OnMapReady");
mMap = googleMap;
mMap.setOnMapLoadedCallback(this);
3)onMapLoaded() call when maps loads.
public void onMapLoaded() {
// hide progress
}
Please check point 3 it is important.

Related

how to update map icon via Handler

I am a very novice programmer.
I am using a handler to get my location data from a service to my main activity but I would like to update the map using the code from the service.
The GPS coordinates are correctly sent via the handler, but I seem to be stuck on how to use the handler to actually present the data by updating the map/ icons on the map.
The map keeps putting the marker at 0.0, nor does it position the map at the new location sent via the handler.
//get GPS latitude and Longitude from service here
private void displayLatLong() {
final TextView latitudeView = (TextView) findViewById(R.id.latitude);
final TextView longitudeView = (TextView) findViewById(R.id.longitude);
final TextView latitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);
final TextView longitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
double latitude = 0.0;
double longitude = 0.0;
//latitudeCoords = "not empty"; //debug
//longitudeCoords = "not empty"; //debug
if(bound && locationService != null) {
latitude = locationService.getLastLatitude();
longitude = locationService.getlastLongitude();
}
String latitudeStr = String.format(Locale.getDefault(), "%1$, .5f lat", latitude);
String longitutdeStr = String.format(Locale.getDefault(), "%1$, .5f long", longitude);
latitudeView.setText(latitudeStr);
longitudeView.setText(longitutdeStr);
latCoords = latitude;
longCoords = longitude;
// longitudeCoordsView.setText(longitudeCoords); //debug
// latitudeCoordsView.setText(longitudeCoords); //debug
handler.postDelayed(this, 1000);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Bind location service here so it keeps running even if activity is stopped.
Intent intent = new Intent(this, LocationService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
displayDistance();
displayLatLong();
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
LatLng player= new LatLng(latCoords, longCoords);
mMap.addMarker(new MarkerOptions().position(player).title("current player position"));//set marker with player position and description
mMap.moveCamera(CameraUpdateFactory.newLatLng(player)); //move Camera to player position
}locat
You just need to update the map once you get the location.
Add a method that will update the map:
private void updateMapLocation() {
LatLng player= new LatLng(latCoords, longCoords);
mMap.addMarker(new MarkerOptions().position(player).title("current player position"));//set marker with player position and description
mMap.moveCamera(CameraUpdateFactory.newLatLng(player)); //move Camera to player position
}
Then call this method once you have the latCoords and longCoords member variables populated:
//get GPS latitude and Longitude from service here
private void displayLatLong() {
final TextView latitudeView = (TextView) findViewById(R.id.latitude);
final TextView longitudeView = (TextView) findViewById(R.id.longitude);
final TextView latitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);
final TextView longitudeCoordsView = (TextView) findViewById(R.id.latitudecoordsView);
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
double latitude = 0.0;
double longitude = 0.0;
if(bound && locationService != null) {
latitude = locationService.getLastLatitude();
longitude = locationService.getlastLongitude();
}
String latitudeStr = String.format(Locale.getDefault(), "%1$, .5f lat", latitude);
String longitutdeStr = String.format(Locale.getDefault(), "%1$, .5f long", longitude);
latitudeView.setText(latitudeStr);
longitudeView.setText(longitutdeStr);
latCoords = latitude;
longCoords = longitude;
// Add call to update map with location:
if (latCoords > 0 && longCoords > 0) {
updateMapLocation()
}
handler.postDelayed(this, 1000);
}
});
}

Change or Update Google Map marker in a second fragment on location update from first fragment in a pageviewer

i am new to android (2weeks old), i am having difficulties updating google map marker on fragment in pager viewer
After getting user longitude and latitude when photo is taken with camera from first fragment, i want to update marker or if possible recreate map with new marker on google map in second fragment.
After using interface to transfer data from fragment1(ImageFragment) to fragment2(MapFragment), i still cant update the map, i am having error on this line and anything relate to GoogleMap
googleMap.addMarker(marker);// null pointer exeception here
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));// and null pointer exeception here too
i still get nullpointer exception error on this line below. // adding marker googleMap.addMarker(marker); this is my logcat
Caused by: java.lang.NullPointerException at com.solexadex.itrak.i_trak.MapFragment.displayMapOnFragment(‌​MapFragment.java:101‌​)
These are my code: MapFragment Class
public class MapFragment extends Fragment implements ImageFragment.DisplayMapOnFragment {
//-------------- class variables
private MapView mMapView;
private GoogleMap mGoogleMap;
private GoogleMap googleMap;
private FragmentActivity myContext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_map, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 7.385044;
double longitude = 9.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
#Override
public void displayMapOnFragment(double latitude, double longitude) {
//initilizeMap();
// latitude and longitude
// double latitude = 9.155543;
//double longitude = 7.321151;//9.155543, 7.321151
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
//googleMap.
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}}
And ImageFragment Class below
public class ImageFragment extends Fragment {
private Context mContext;
double longitude, latitude;
public String street,city, state, country,zip,knownName,iDate;
private final Context dialogContext = getActivity();
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888;
FloatingActionButton button;
ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflater = getActivity().getLayoutInflater();
final View rootView = inflater.inflate(R.layout.fragment_image,
container, false);
mContext=getActivity().getApplicationContext();
button = ( FloatingActionButton) rootView.findViewById(R.id.fab);
imageView = (ImageView) rootView.findViewById(R.id.imageView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// now access the TextView as you want
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
// convert byte array to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
byteArray.length);
imageView.setImageBitmap(bitmap);
//call
this.getCoord();
}
}
}
public interface OnDataPass {
public void onDataPass(double uLat, double uLong);
}
public interface OnDataPass2 {
public void onDatapass2(String address, String city, String state, String postalCode, String KnowName, String createdDate);
}
public interface DisplayMapOnFragment {
public void displayMapOnFragment(double mapLat, double mapLong);
}
OnDataPass dataPasser;
OnDataPass2 dataPasser2;
DisplayMapOnFragment displayMapOnFragment;
#Override
public void onAttach(Activity a) {
super.onAttach(a);
try {
displayMapOnFragment = (DisplayMapOnFragment) a;
dataPasser = (OnDataPass) a;
dataPasser2 = (OnDataPass2) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString()
+ " must implement OnDataPass");
}
}
public void passData(double uLong, double uLat) {
dataPasser.onDataPass(uLong, uLat);
}
int aCount=20; //initialize counter to loop getCoord method if 0.0 is returned so as to ge value that is not 0.0
public void getCoord()
{
MapFragment mf = new MapFragment();
NewTrackActivity newTrackActivity=new NewTrackActivity();
TrackGPS gps = new TrackGPS(mContext);
if(gps.canGetLocation()){
longitude = gps.getLongitude();
latitude = gps.getLatitude();
if(aCount!=20)
Toast.makeText(mContext,"Retrying to get Coordinate: "+aCount+"\nLongitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude), Toast.LENGTH_LONG).show();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
//Log.e("latitude", "inside latitude--" + latitude);
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
street = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getLocality();
state = addresses.get(0).getAdminArea();
country = addresses.get(0).getCountryName();
zip = addresses.get(0).getPostalCode();
knownName = addresses.get(0).getFeatureName();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
iDate=dateFormat.format(date);
// locationTxt.setText(address + " " + city + " " + country);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
newTrackActivity.onDataPass( longitude, latitude);
newTrackActivity.onDatapass2( street, city, state, zip, knownName, iDate);
if(Double.compare(latitude,0.00)==0 && aCount>0) {
aCount--;
getCoord();
}
if(aCount<=1) {
Toast.makeText(mContext,"Please retake photo to get current position coordinate", Toast.LENGTH_LONG).show();
aCount=20; //reset count
}else
{
Toast.makeText(mContext,"Coordinates found", Toast.LENGTH_LONG).show();
}
newTrackActivity.displayMapOnFragment(latitude, longitude);
// Supply value
// Bundle args = new Bundle();
// args.putDouble("latitude", latitude);
//args.putDouble("longitude", longitude);
//mf.setArguments(args);
}
else
{
gps.showSettingsAlert(mContext);
}
}
}
Fragment_map.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

How to get multiple data from ArrayList and display it in snippet google map android?

I am doing a google map project where I have to fetch the data (title and snippet description) from Array List (which is retrieved from server) and display it in title and snippet dynamically. Since the description in the snippet is lengthy, the whole description is not displayed. The following is my code.
I am able to get a title and a snippet when I tap the marker. What I need is, the snippet should show the lengthy description which comes from server. At present what happens is, there is one title line and one snippet line. The description is shown half in the snippet. If I am not clear please let me know. Need to solve this.
#SuppressLint("NewApi")
public class GoogleActivity extends FragmentActivity implements LocationListener {
private LocationManager locationManager;
private static final long MIN_TIME = 700;
private static final float MIN_DISTANCE = 800;
private Location mLocation;
// Google Map
private GoogleMap googleMap;
LatLng myPosition;
// All static variables
static final String URL = "http://webersspot.accountsupport.com/gmaptrial/onedb/phpsqlajax_genxml.php";
// XML node keys
static final String KEY_PID = "pro"; // parent node
static final String KEY_NAME = "Name";
static final String KEY_DESCRIPTION = "Description";
static final String KEY_LAT = "Latitude";
static final String KEY_LONG = "Longitude";
ArrayList<HashMap<String, String>> storeMapData = new ArrayList<HashMap<String, String>>();
private ShareActionProvider mShareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//open the map
openTheMap();
/*
// Get Location Manager and check for GPS & Network location services
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// Build the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Not Active");
builder.setMessage("Please enable Location Services and GPS");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
// Show location settings when the user acknowledges the alert dialog
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
Dialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
*/
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER
new LongOperation().execute("");
new MapOperation().execute(googleMap);
}
/* open the map */
private void openTheMap() {
try {
if(googleMap == null) {
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = mapFragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); // Hybrid for satellite with place name
googleMap.setMyLocationEnabled(true); // enable user location button.
googleMap.setInfoWindowAdapter(null) ;
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
googleMap.setTrafficEnabled(true); // enable road
zoomMap();
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/* zoom current location */
private void zoomMap() {
int zoomScale = 12;
double currentLat = mLocation.getLatitude();
double currentLon = mLocation.getLongitude();
googleMap.moveCamera(CameraUpdateFactory
.newLatLngZoom(new LatLng(currentLat, currentLon), zoomScale));
}
public List<HashMap<String, String>> prepareData(){
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
//List<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XmlParser parser = new XmlParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_PID);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
System.out.println("OOOOOOOOOOOOOOOOOOO ::: "+e.getAttribute(KEY_NAME));
// adding each child node to HashMap key => value
map.put(KEY_NAME, e.getAttribute(KEY_NAME).toString());
map.put(KEY_DESCRIPTION ,e.getAttribute(KEY_DESCRIPTION).toString());
map.put(KEY_LAT, e.getAttribute(KEY_LAT).toString());
map.put(KEY_LONG ,e.getAttribute(KEY_LONG).toString());
// adding HashList to ArrayList
menuItems.add(map);
storeMapData = menuItems;
}
return menuItems;
}
public void onMapReady(final GoogleMap map) {
ArrayList<HashMap<String, String>> processData = storeMapData;
System.out.println( "kjkasdc "+processData);
for (int i=0; i< processData.size(); i++){
final double lat = Double.parseDouble(processData.get(i).get(KEY_LAT));
System.out.println("MAP LAT ::::::::::::::::::::::::: "+lat);
final double lon = Double.parseDouble(processData.get(i).get(KEY_LONG));
System.out.println("MAP LON ::::::::::::::::::::::::: "+lon);
final String address = processData.get(i).get(KEY_DESCRIPTION);
System.out.println("MAP ADDRESS ::::::::::::::::::::::::: "+address);
final String name = processData.get(i).get(KEY_NAME);
System.out.println("MAP ADDRESS ::::::::::::::::::::::::: "+name);
runOnUiThread(new Runnable() {
#Override
public void run() {
map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title(name).snippet(address).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
}
});
}
}
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.share_menu, menu);
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_item_share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT,"Download");
intent.putExtra(Intent.EXTRA_TEXT,"Download Hill Top Beauty Parlour App - Maroli from Google Play Store: https://play.google.com/store/apps/details?id=beauty.parlour.maroli");
return intent;
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
prepareData();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
System.out.println("Executed");
}
#Override
protected void onPreExecute() {
System.out.println("Execution started");
}
#Override
protected void onProgressUpdate(Void... values) {
System.out.println(" -- -- -- "+values);
}
}
private class MapOperation extends AsyncTask<GoogleMap, Void, String> {
#Override
protected String doInBackground(GoogleMap... params) {
GoogleMap map = params[0];
onMapReady(map);
return "Executed";
}
#Override
protected void onPostExecute(String result) {
System.out.println(result);
}
#Override
protected void onPreExecute() {
System.out.println("Execution started");
}
#Override
protected void onProgressUpdate(Void... values) {
System.out.println(" -- -- -- "+values);
}
}
class MyInfoWindowAdapter implements InfoWindowAdapter{
private final View myContentsView;
MyInfoWindowAdapter(){
myContentsView = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
}
#Override
public View getInfoContents(Marker marker) {
TextView tvTitle = ((TextView)myContentsView.findViewById(R.id.title));
tvTitle.setText(marker.getTitle());
TextView tvaddress = ((TextView)myContentsView.findViewById(R.id.snippet));
tvaddress.setText(marker.getTitle());
return myContentsView;
}
#Override
public View getInfoWindow(Marker marker) {
// TODO Auto-generated method stub
return null;
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
googleMap.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
At present I am able to get a title and a snippet when I tap the marker. What I need is, the snippet should show the lengthy description which comes from server. At present what happens is, there is one title line and one snippet line. The description is shown half in the snippet. If I am not clear please let me know. Need to solve this.
You would need to check the layout of your custom info window and make sure that the Textview for description accepts more than 1 line. Setting the lines or maxLines property in the layout or in the code will help you achieve this. Make sure also that the layout_height and layout_width is properly set.
You may refer to this question -> Custom info window for google maps android as a guide on how to create a custom info window

Large number of markers adding in android google map version 2 unable to execute Progress update of asynchronous background task

public class PositionUpdate1 extends AsyncTask<Void, Void, Location>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(NearByAttractions2.this);
dialog.setMessage("Loading Places........");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Location doInBackground(Void...arg0)
{
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
runOnUiThread(new Thread()
{
public void run()
{
String xml = ParseXMLMethods2.getXML();
Document doc = ParseXMLMethods2.XMLfromString(xml);
NodeList children = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < children.getLength(); i++)
{
Element e = (Element)children.item(i);
alist.add(ParseXMLMethods2.getValue(e,KEY_TITLE));
}
arr = new String[alist.size()];
alist.toArray(arr);
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, NearByAttractions2.this, requestCode);
dialog.show();
}else
{
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 20000, 0, NearByAttractions2.this);
map.setMyLocationEnabled(true);
}
}
});
publishProgress();
return null;
}
#Override
protected void onPostExecute(Location loc)
{
dialog.dismiss();
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener()
{
#Override
public void onInfoWindowClick(Marker marker)
{
Intent intent = new Intent(NearByAttractions2.this,Activity2.class);
intent.putExtra("Clubname", marker.getTitle());
intent.putExtra("Username", Username);
intent.putExtra("ID2", UserID);
startActivity(intent);
}
});
{
}
}
#Override
protected void onProgressUpdate(Void... values)
{
dialog.dismiss();
geoCoder = new Geocoder(NearByAttractions2.this, Locale.getDefault());
try
{
for(int i = 0;i<arr.length;i++)
{
addresses = geoCoder.getFromLocationName(arr[i], 1);
if(addresses.toString().contains("Address"))
{
Address address = addresses.get(0);
double lat = address.getLatitude();
double lng = address.getLongitude();
combine = new LatLng(lat, lng);
map.addMarker(new MarkerOptions()
.title(arr[i])
.position(combine));
}
else
{
}
}
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),"some attractions are unavailable at this moment due to slow internet connection",Toast.LENGTH_LONG).show();
}
}
}
in the above code my requirement is map open after populating array mentioned at doing background method and then markers will add whenever I drag map means after populating array I want to use UI component and marker adding will be done at background under Progress update.How can I fulfill my requirement without clustering in android?

Get map center point on scrolling Google maps v2 in android?

Hi iam doing an app very in my app there is a map page so i implemented Google Maps V2 and i have a issue i when i scroll the map i want to get the center points of the map that is if i scroll the map and i leave it then it gets the center points of the map so can any one can suggest to solve this issue it may be helpful Thank you in advance.......
Note : I have Used a Google Maps V2 so please post related to that .
public class Mapview extends FragmentActivity implements OnMapClickListener, OnCameraChangeListener{
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Location myLocation;
TextView tvLocInfo;
GPSTracker gps;
public double Latitude,Longitude;
String Datetime, addr,RegUID;
public String lat,longd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = mySupportMapFragment.getMap();
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
myMap.setMyLocationEnabled(true);
myMap.setOnMapClickListener(this);
Projection P = myMap.getProjection();
Log.e("lat", String.valueOf(Latitude));
Log.e("lat", String.valueOf(Longitude));
Button mDone = (Button) findViewById(R.id.button1);
mDone.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SimpleDateFormat")
public void onClick(View v) {
//Toast.makeText(getBaseContext(), "latitude"+lat+""+"longitude"+longd , Toast.LENGTH_LONG).show();
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
Datetime = timeStamp.toString();
Log.e("t", Datetime);
RegUID = Utils.RegisterUserId;
Log.e("t", RegUID);
final ProgressDialog dialog = ProgressDialog.show(Mapview.this, "", Utils.Loading, true);
dialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#SuppressWarnings("unused")
public void run()
{
try
{
String EMPLOYEE_SERVICE_URI = Utils.Request+"UserID="+RegUID+"&Location="+URLEncoder.encode(addr,"UTF-8")+"&Latitude="+lat+"&Longitude="+longd+"&RequestDate="+URLEncoder.encode(Datetime,"UTF-8");
Log.e(EMPLOYEE_SERVICE_URI, EMPLOYEE_SERVICE_URI);
JSONObject JObject = Utils.getResult(EMPLOYEE_SERVICE_URI);
//Toast.makeText(Mapview.this,JObject.toString(), Toast.LENGTH_LONG).show();
if(JObject!=null)
{
if(JObject.getBoolean("Valid"))
{
AlertDialog alertDialog = new AlertDialog.Builder(Mapview.this).create();
Utils.callAlert(JObject.getString("Message"), alertDialog);
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(Mapview.this).create();
Utils.callAlert(JObject.getString("Message"), alertDialog);
}
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(Mapview.this).create();
Utils.callAlert(JObject.getString("Message"), alertDialog);
}
}
catch (Exception e)
{
//Toast.makeText(Mapview.this,e.toString(), Toast.LENGTH_LONG).show();
Log.e("Exception", e.toString());
}
dialog.dismiss();
}//run() ends
}, 5000);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.i("test","onScroll");
return false;
}
#Override
public void onMapClick(LatLng point) {
Log.e("lat", String.valueOf(point.latitude));
Log.e("lat", String.valueOf(point.longitude));
Latitude =point.latitude;
Longitude = point.longitude;
lat = String.valueOf(point.latitude);
longd = String.valueOf(point.longitude);
myMap.moveCamera(CameraUpdateFactory.newLatLng(point));
gps = new GPSTracker(Mapview.this);
// check if GPS enabled
if(gps.canGetLocation())
{
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(Latitude, Longitude, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
addr = new String(strReturnedAddress);
tvLocInfo.setText(addr.toString());
//Toast.makeText(getApplicationContext(), addr.toString(),Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Gps location address is unavailable please try again later",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
}
}
You can use:-
myMap.setOnCameraChangedListener(this);
And in the listener:-
onCameraChange(CameraPosition position) {
LatLng target = position.target;
// do what you need with the position here
}
I'm not sure about the index out of bounds. But to set a default map position you could use something like below:-
private void setDefaultMapPosition(LatLng latLng) {
CameraPosition camPos =
new CameraPosition.Builder().target(latLng)
.zoom(A_DEFAULT_MAP_ZOOM)
.bearing(0)
.tilt(0)
.build();
myMap.moveCamera(
CameraUpdateFactory.newCameraPosition(camPos));
}
The interface OnCameraChangeListener has been deprecated. You can now use now OnCameraIdleListener
Called when camera movement has ended, there are no pending animations
and the user has stopped interacting with the map.
and fetch the coordinates of the center by doing:
val centerCoordinates = mMap.cameraPosition.target

Categories

Resources