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
Related
I want to show Multiple Markers at runtime on the screen which have different id's that received from the server and longitude and latitude also change or save on server.
** Code work fine in 1 to 1 tracking but not work on multiple Id's PLEASE HELP ME..**
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
static final LatLng HAMBURG1 = new LatLng(74.3226214, 31.5003567);
static final LatLng HAMBURG = new LatLng(74.3229122, 31.5003193);
private static MainActivity instance;
private static final int ERROR_DIALOG_REQUEST = 9001;
GoogleMap mMap;
int i = 0;
protected static String longitudeServer;
protected static String latitudeServer;
protected static String uniqueidSserver;
protected static String latitudeLast;
protected static String logitudeLast;
protected static String uniqueidlast;
protected static double latilasdoublet;
protected static double longilastdouble;
double latitude = 0;
double longitude = 0;
private GoogleApiClient mLocationClient;
private com.google.android.gms.location.LocationListener mListener;
private Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (servicesOK()) {
setContentView(R.layout.activity_map);
if (initMap()) {
// gotoLocation(SEATTLE_LAT, SEATTLE_LNG, 15);
mLocationClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mLocationClient.connect();
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(this, "Map not connected!", Toast.LENGTH_SHORT).show();
}
} else {
setContentView(R.layout.activity_main);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//Add menu handling code
switch (id) {
case R.id.mapTypeNone:
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
case R.id.mapTypeNormal:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.mapTypeSatellite:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.mapTypeTerrain:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.mapTypeHybrid:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
}
return super.onOptionsItemSelected(item);
}
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog =
GooglePlayServicesUtil.getErrorDialog(isAvailable, this, ERROR_DIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, "Can't connect to mapping service", Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap() {
if (mMap == null && i == 0) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
return (mMap != null);
}
private void gotoLocation(double lat, double lng, float zoom) {
LatLng latLng = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
mMap.moveCamera(update);
}
public void showCurrentLocation(MenuItem item) {
Location currentLocation = LocationServices.FusedLocationApi
.getLastLocation(mLocationClient);
if (currentLocation == null) {
Toast.makeText(this, "Couldn't connect!", Toast.LENGTH_SHORT).show();
} else {
LatLng latLng = new LatLng(
currentLocation.getLatitude(),
currentLocation.getLongitude()
);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
latLng, 10
);
mMap.animateCamera(update);
}
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show();
mListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(MainActivity.this, "Location : " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_LONG).show();
if (i == 0) {
gotoLocation(location.getLatitude(), location.getLongitude(), 15);
i = 1;
}
AppUtill.UniqueId();
if (AppStatus.getInstance(getContext()).isOnline()) {
new JSONAsyncTask().execute("http://ip/hajjapi/api/GPSLocator/GetLocations");
} else {
Toast.makeText(MainActivity.this, "Turn On your WIFI ", Toast.LENGTH_LONG).show();
}
///HOW I CAN DISPLAY MULTIPLE MARKERS WHICH HAVE DIFFERENT ID'S RECEIVED FROM THE SERVER PLEASE HELP ME PLEASE...
if (marker != null) {
marker.remove();
}
MarkerOptions options = new MarkerOptions().title("User Name").position(new LatLng(latilasdoublet, longilastdouble)).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
marker = mMap.addMarker(options);
}
};
LocationRequest request = LocationRequest.create();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setInterval(5000);
request.setFastestInterval(5000);
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, request, mListener);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void showcurrentLocation() {
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
i = 1;
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(data);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
longitudeServer = obj.getString("longi");
latitudeServer = obj.getString("lati");
uniqueidSserver = obj.getString("uniqueid");
}
////LAST LONGITUDE AND LATITUDE THAT RECEIVED FROM SERVER
List<String> longitude = Arrays.asList(longitudeServer);
logitudeLast = longitude.get(longitude.size() - 1);
System.out.println(logitudeLast + " logitude ");
List<String> latitude = Arrays.asList(latitudeServer);
latitudeLast = latitude.get(latitude.size() - 1);
System.out.println(latitudeLast + " latitude ");
List<String> uniqueid = Arrays.asList(uniqueidSserver);
uniqueidlast = uniqueid.get(uniqueid.size() - 1);
System.out.println(uniqueidlast + " unique id ");
latilasdoublet = Double.parseDouble(latitudeLast);
longilastdouble = Double.parseDouble(logitudeLast);
return true;
}
//------------------>>
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if (result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStop() {
super.onStop();
startService(new Intent(getContext(), Services.class));
}
public MainActivity() {
instance = this;
}
public static Context getContext() {
return instance;
}
}
you are using only two double variables for lat and lng. create an arrayList of LatLng objects. for all the urls you get in response, add the LatLng to the arrayList.
add a field
private ArrayList<LatLng> latLngList;
initialize in oncreate function
latLngList = new ArrayList<>();
instead of
latilasdoublet = Double.parseDouble(latitudeLast);
longilastdouble = Double.parseDouble(logitudeLast);
add
for(int i=0; i< latitude.size(); i++){
LatLng latLng = new LatLng(Double.parseDouble(latitude.get(i)), Double.parseDouble(longitude.get(i)));
latLngList.add(latLng);
}
in place of
MarkerOptions options = new MarkerOptions().title("User Name").position(new LatLng(latilasdoublet, longilastdouble)).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
marker = mMap.addMarker(options);
use
ArrayList<MarkerOptions> list = new ArrayList<>();
for (LatLng object : latLngList){
MarkerOptions options = new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
mMap.addMarker(options);
list.add(options); //if you want to keep track of all your markers
}
use mMap.clear() to clear all markers and clustering refer
More info on markers.
I am new to android and developing an application which shows nearby places. It also have search functionality and searching is working properly. The problem is how to make searchView widget in action bar as autocomplete.
More precisely:
The problem is that this code autocompletes user text entry with suggestions in the searchview widget by getting data from google places api. On item selection of a suggested place, the selection does not get displayed in the searchview.
For example, if a person types "Berl" in the searchview, the autocomplete displays Berlin as a suggestion. But when the user selects Berlin from the list, the searchview box still displays Berl and not Berlin, Germany as it is in the suggestion list. I want to take the string that the user selects and display it in the search box
Here is my Main Activity:
GoogleMap mGoogleMap;
private Marker[] placeMarkers;
private final int MAX_PLACES = 20;
private MarkerOptions[] places;
private LocationManager locMan;
private int userIcon, foodIcon, otherIcon;
private SupportMapFragment mapFragment;
private Marker userMarker;
Button pt;
//GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar ac=getSupportActionBar();
ac.show();
ac.setDisplayShowTitleEnabled(true);
ac.setTitle("Near By Mosque");
ac.setDisplayUseLogoEnabled(true);
userIcon = R.drawable.marker_img;
foodIcon = R.drawable.nearby_ic;
if(mGoogleMap==null){
//map not instantiated yet
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mGoogleMap = fragment.getMap();
}
if(mGoogleMap != null){
//ok - proceed
}
handleIntent(getIntent());
mGoogleMap.setMapType(mGoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.setMyLocationEnabled(true);
placeMarkers = new Marker[MAX_PLACES];
updatePlaces();
}
private void handleIntent(Intent intent){
if(Intent.ACTION_SEARCH.equals(intent.getAction()))
{
String query = intent.getStringExtra(SearchManager.QUERY);
doSearch(query);
}
else if(Intent.ACTION_VIEW.equals(intent.getAction()))
{
getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleIntent(intent);
}
private void doSearch(String query){
Bundle data = new Bundle();
data.putString("query", query);
getSupportLoaderManager().restartLoader(0, data, this);
}
private void getPlace(String query){
Bundle data = new Bundle();
data.putString("query", query);
getSupportLoaderManager().restartLoader(1, data, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
//searchView.setSearchableInfo(PlaceProvider.DETAILS_URI);
searchView.setIconifiedByDefault(true);
AutoCompleteTextView searchTextView =
(AutoCompleteTextView) searchView.findViewById(R.id.abs__search_src_text);
if (searchTextView != null) {
searchTextView.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
searchTextView.setTypeface(Typeface.MONOSPACE);
}
searchView.getClass();
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem query) {
switch(query.getItemId()){
case R.id.abs__list_item:
Log.i("menuitme", query.toString());
onSearchRequested();
break;
}
return super.onMenuItemSelected(featureId, query);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle query) {
CursorLoader cLoader = null;
if(arg0==0)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[]{ query.getString("query") }, null);
else if(arg0==1)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[]{ query.getString("query") }, null);
Log.i("new loader", cLoader.toString());
return cLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
showLocations(c);
Log.i("cursor", c.toString());
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}
private void showLocations(Cursor c){
MarkerOptions markerOptions = null;
LatLng position = null;
//mGoogleMap.clear();
while(c.moveToNext()){
markerOptions = new MarkerOptions();
position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2)));
markerOptions.position(position);
markerOptions.title(c.getString(0));
mGoogleMap.addMarker(markerOptions);
}
if(position!=null){
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
mGoogleMap.animateCamera(cameraPosition);
}
}
private void updatePlaces(){
//update location
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location lastLoc = null;
lastLoc=locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
LatLng lastLatLng = new LatLng(lat, lng);
Log.i("latlng",lastLatLng.toString());
if(userMarker!=null) userMarker.remove();
userMarker = mGoogleMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastLoc.getLatitude(), lastLoc.getLongitude()), 15.0f));
String types = "mosque";
try {
types = URLEncoder.encode(types, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=3000&sensor=true" +
"&types=" + types +
"&key=AIzaSyCJv8kyIgi7hStqFN3qR-DXF6YMuQ2M6Y0";
new GetPlaces().execute(placesSearchStr);
}
private class GetPlaces extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute()
{
Dialog.setMessage("Please wait...");
Dialog.show();
}
#Override
protected String doInBackground(String... placesURL) {
// TODO Auto-generated method stub
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
//execute search
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
HttpGet placesGet = new HttpGet(placeSearchURL);
HttpResponse placesResponse = placesClient.execute(placesGet);
StatusLine placeSearchStatus = placesResponse.getStatusLine();
if (placeSearchStatus.getStatusCode() == 200) {
//we have an OK response
HttpEntity placesEntity = placesResponse.getEntity();
InputStream placesContent = placesEntity.getContent();
InputStreamReader placesInput = new InputStreamReader(placesContent);
BufferedReader placesReader = new BufferedReader(placesInput);
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
Log.i("line", lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}finally {
placesClient.getConnectionManager().shutdown();
}
}
Log.i("post", placesBuilder.toString());
return placesBuilder.toString();
}
protected void onPostExecute(String result) {
//parse place data returned from Google Places
try
{
if(Dialog.isShowing())
{
Dialog.dismiss();
}
// do your Display and data setting operation here
}
catch(Exception e)
{
}
if(placeMarkers != null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
try {
//parse JSON
JSONObject resultObject = new JSONObject(result);
JSONArray placesArray = resultObject.getJSONArray("results");
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p=0; p<placesArray.length(); p++) {
//parse each place
boolean missingValue=false;
LatLng placeLL=null;
String placeName="";
String vicinity="";
Log.i("place array", places.toString());
int currIcon = otherIcon;
try{
//attempt to retrieve place data values
missingValue=false;
JSONObject placeObject = placesArray.getJSONObject(p);
JSONObject loc = placeObject.getJSONObject("geometry").getJSONObject("location");
placeLL = new LatLng(
Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
JSONArray types = placeObject.getJSONArray("types");
for(int t=0; t<types.length(); t++){
//what type is it
String thisType=types.get(t).toString();
vicinity = placeObject.getString("vicinity");
placeName = placeObject.getString("name");
Log.i("placename",placeName);
Log.i("types", types.toString());
if(thisType.contains("mosque")){
currIcon = foodIcon;
break;
}
}
}
catch(JSONException jse){
missingValue=true;
jse.printStackTrace();
}
Log.i("marker", places.toString());
if(missingValue) places[p]=null;
else
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
}
catch (Exception e) {
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length; p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=mGoogleMap.addMarker(places[p]);
}
}
}
}
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
updatePlaces();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.v("MyMapActivity", "status changed");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.v("MyMapActivity", "provider enabled");
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.v("MyMapActivity", "provider disabled");
}
#Override
protected void onResume() {
super.onResume();
if(mGoogleMap!=null){
}
}
#Override
protected void onPause() {
super.onPause();
if(mGoogleMap!=null){
locMan.removeUpdates(this);
}
}
}
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.
I want show own loaction from a address was input by user use LocationOverlay and show position by a small dot or anything by icon....(ex: can show this position by a flag.png )But now i don't know how show it on map.Can you help me!
source code:
public class Main extends MapActivity implements LocationListener {
private static double lat;
private static double lon;
private MapController mapControl;
private MapView mapView;
LocationManager locman;
Location loc;
String provider = LocationManager.GPS_PROVIDER;
String TAG = "GPStest";
Bundle locBundle;
private int numberSats = -1;
private float satAccuracy = 2000;
private float bearing;
private double altitude;
private float speed;
private String currentProvider;
private TextView txt;
private double lat1;
private double lon1;
private Drawable marker;
private Geocoder gcoder;
private MyLocationOverlay me = null;
long GPSupdateInterval; // In milliseconds
float GPSmoveInterval; // In meters
private MyMyLocationOverlay myLocationOverlay;
private List<Overlay> mapOverlays;
public DisplayOverlay displayOverlay;
private EditText address;
Button test;
private Button btnMylocation;
private Button btnAddrress;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_long_van_map);
gps();
btnMylocation = (Button) findViewById(R.id.button1);
// get my location
btnMylocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
gps();
}
});
gcoder = new Geocoder(this);
me = new MyLocationOverlay(this, mapView);
address = (EditText) findViewById(R.id.editText1);
btnAddrress = (Button) findViewById(R.id.button2);
//Get postion from address
btnAddrress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String add = address.getText().toString();
try {
List<Address> addresses = gcoder
.getFromLocationName(add, 1);
if (addresses == null) {
// return point;
}
// just get first item of list address
Address add2 = addresses.get(0);
lat1 = add2.getLatitude();
lon1 = add2.getLongitude();
} catch (IOException e) {
}
GeoPoint newPoint = new GeoPoint((int) (lat1 * 1e6),
(int) (lon1 * 1e6));
mapControl.animateTo(newPoint);
marker = getResources().getDrawable(R.drawable.startpoint);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
//mapView.getOverlays().add(new SitesOverlay(marker));
mapView.getOverlays().add(me);
}
});
}
//Info gps of me
public void gps() {
updateGPSprefs();
locman = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Listener for GPS Status...
final GpsStatus.Listener onGpsStatusChange = new GpsStatus.Listener() {
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_STARTED:
// Started...
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
// First Fix...
Toast.makeText(Main.this, "GPS has First fix",
Toast.LENGTH_LONG).show();
break;
case GpsStatus.GPS_EVENT_STOPPED:
// Stopped...
break;
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
// Satellite update
break;
}
//GpsStatus status = locman.getGpsStatus(null);
// Not presently doing anything with following status list for
// individual satellites
// Iterable<GpsSatellite> satlist = status.getSatellites();
}
};
locman.addGpsStatusListener(onGpsStatusChange);
locman.requestLocationUpdates(provider, GPSupdateInterval,
GPSmoveInterval, this);
Log.i(TAG, locman.toString());
// Add map controller with zoom controls
mapView = (MapView) findViewById(R.id.Mapview);
mapView.setSatellite(false);
mapView.setTraffic(false);
mapView.setBuiltInZoomControls(true); // Set android:clickable=true in
// main.xml
int maxZoom = mapView.getMaxZoomLevel();
int initZoom = (int) (0.95 * (double) maxZoom);
mapControl = mapView.getController();
mapControl.setZoom(initZoom);
// Set up compass and dot for present location map overlay
List<Overlay> overlays = mapView.getOverlays();
myLocationOverlay = new MyMyLocationOverlay(this, mapView);
overlays.add(myLocationOverlay);
// Set up overlay for data display
displayOverlay = new DisplayOverlay();
mapOverlays = mapView.getOverlays();
mapOverlays.add(displayOverlay);
txt = (TextView) findViewById(R.id.textView1);
txt.setText(LongVanMap.gettext());
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// Called when location has changed
centerOnLocation();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
locman.removeUpdates(this);
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
locman.requestLocationUpdates(provider, GPSupdateInterval,
GPSmoveInterval, this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
centerOnLocation();
}
// Method to assign GPS prefs
public void updateGPSprefs() {
int gpsPref = Integer.parseInt(Prefs
.getGPSPref(getApplicationContext()));
switch (gpsPref) {
case 1:
GPSupdateInterval = 5000; // milliseconds
GPSmoveInterval = 1; // meters
break;
case 2:
GPSupdateInterval = 10000;
GPSmoveInterval = 100;
break;
case 3:
GPSupdateInterval = 125000;
GPSmoveInterval = 1000;
break;
}
}
}
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.maps_screen);
initActionBar();
String address = getIntent().getExtras().getString("address");
String title = getIntent().getExtras().getString("title");
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
Geocoder geoCoder = new Geocoder(this);
List<Address> addresses;
try {
Log.i("maps", "getting geopoint for address: " + address);
addresses = geoCoder.getFromLocationName(address, 1);
if (addresses == null || addresses.isEmpty()) {
Log.i("maps", "couldn't get any matches for the following address: " + address);
isInvalidLocation = true;
showInvalidAddressDialog();
return;
}
Address location = addresses.get(0);
GeoPoint point = coordinatesToGeoPoint(location.getLatitude(), location.getLongitude());
Drawable marker = getResources().getDrawable(R.drawable.da_marker_red);
MapOverlay adPos = new MapOverlay(marker,mapView);
List<Overlay> overlays = mapView.getOverlays();
OverlayItem overlayItem = new OverlayItem(point, title, address);
adPos.addOverlay(overlayItem);
overlays.add(adPos);
MapController mapcontroller = mapView.getController();
mapcontroller.animateTo(point);
mapcontroller.setCenter(point);
mapcontroller.setZoom(12);
} catch (Exception ex) {
Log.e("geocoder", "error using geocoder", ex);
}
}
So I put my connectivity tests in and stop my JSON call for map pins. However, even with this done if the user taps on the map the app crashes.
It seems to be calling a method in the Google API's maps.jar for touch events but I do not have access to these right?
so how do test for it or is there a better way to check for this?
public class Map_Activity extends MapActivity implements LocationListener {
/** Called when the activity is first created. */
MapView map;
private MyLocationOverlay me = null;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
String towers;
int lat;
int longi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
map = (MapView) findViewById(R.id.mapview);
Touchy t = new Touchy();
overlayList = map.getOverlays();
overlayList.add(t);
// //////////////////////////////////// Where the maps opens up to and
// zoom
map.getController().setCenter(getPoint(40.801531, -81.405661));
map.getController().setZoom(15);
Drawable marker = getResources().getDrawable(R.drawable.pin_yellow);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
map.getOverlays().add(new SitesOverlay(marker));
me = new MyLocationOverlay(this, map);
map.getOverlays().add(me);
// d = getResources().getDrawable(R.drawable.pin_blue);
// Geo Location of phone
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location location = lm.getLastKnownLocation(towers);
if (location != null) {
lat = (int) (location.getLatitude() * 1E6);
longi = (int) (location.getLongitude() * 1E6);
// GeoPoint ourLocation = new GeoPoint(lat, longi);
// OverlayItem overlayItem = new OverlayItem(ourLocation,
// "Quit hitting your self", "");
// CustomPinpoint custom = new CustomPinpoint(d, Map_Activity.this);
// custom.insertPinpoint(overlayItem);
// overlayList.add(custom);
} else {
// Toast.makeText(MapsActivity.this, "Couldn't get provider",
// Toast.LENGTH_SHORT).show();
}
initLocation();
}
private void initLocation() {
lm = (LocationManager) this.getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 500, this);
}
#Override
public void onResume() {
super.onResume();
me.enableCompass();
lm.requestLocationUpdates(towers, 500, 1, this);
}
#Override
public void onPause() {
super.onPause();
me.disableCompass();
lm.removeUpdates(this);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay {
public boolean onTouchEvent(MotionEvent e, MapView m) {
return false;
}
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
public SitesOverlay(Drawable marker) {
super(marker);
if (isNetworkAvailable() == true) {
boundCenterBottom(marker);
// //////////////////////////////////////////////////////////////////////
String result = queryRESTurl("http://www.mywesite.com/json.json");
Log.e("Spot 1", "");
JSONObject json;
JSONObject json2;
// JSONObject data;
try {
json = new JSONObject(result);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
for (int i = 0; i < valArray.length(); i++) {
Log.e(nameArray.getString(i), valArray.getString(i));
json2 = new JSONObject(valArray.getString(i));
JSONArray nameArray2 = json2.names();
JSONArray valArray2 = json2.toJSONArray(nameArray2);
for (int a = 0; a < valArray2.length(); a++) {
// add to maps here
items.add(new OverlayItem(getPoint(
valArray2.getDouble(3),
valArray2.getDouble(2)), valArray2
.getString(1), valArray2.getString(0)));
Log.e(nameArray2.getString(a),
valArray2.getString(a));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Pin Locations
populate();
} else {
AlertDialog.Builder ad = new AlertDialog.Builder(
Map_Activity.this);
ad.setIcon(android.R.drawable.ic_dialog_alert);
ad.setTitle("OH NO!");
ad.setMessage("To view the latest information you need a data or wi-fi connection");
ad.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
ad.show();
}
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
protected boolean onTap(int i) {
// Toast.makeText(MapsActivity.this,
// items.get(i).getSnippet(),Toast.LENGTH_SHORT).show();
OverlayItem item = items.get(i);
AlertDialog.Builder dialog = new AlertDialog.Builder(
Map_Activity.this);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return (true);
}
#Override
public int size() {
return (items.size());
}
}
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
List<Overlay> overlays = map.getOverlays();
me = new MyLocationOverlay(this, map);
overlays.add(me);
me.enableMyLocation();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public String queryRESTurl(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
instream.close();
return result;
}
} catch (ClientProtocolException e) {
Log.e("REST", "There was a protocol based error", e);
} catch (IOException e) {
Log.e("REST", "There was an IO Stream related error", e);
}
return null;
}
/*
* Check for Connectivity
*/
public boolean isNetworkAvailable() {
Context context = getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}