blank screen after back press google map api v2 - android

I have a map named MapActivity which operated from
activity.MapActivity extends from fragment.Map loaded first time
successfully.When i am going for other fragment from activity.After
this when i pressed back button for map,map is showing blank
screen.Any idea?
MapActivity
package com.example.map;
import updatedata.FindMapDataService;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MapActivity extends Fragment implements OnMyLocationChangeListener {
public GoogleMap gmap;
public static double maillat,maillng,latitude,longitude,elat5,elng5;
public static String flat5,flng5;
public static int s,state,check;
public static long utime,ftime;
View view;
public static Runnable runn;
public static Handler handler;
public boolean wifi,gps,network,val,inter;
public void onCreate(Bundle savedInstanceState) {
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// location data find from MainActivitiy
elat5=MainActivity.lat10;
elng5=MainActivity.lng10;
// location data find from LocationFindactivity
flat5=LocationFindActivity.latt;
flng5=LocationFindActivity.lng;
// find status for opening map
s=MainActivity.status;
// find time for handler
if(ftime == 0){
ftime=15000;
}
// Load Preferences
LoadPreferences();
//get view
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try{
view = inflater.inflate(R.layout.map, container, false);
}catch(InflateException e){
e.printStackTrace();
}
//Check location data source
if(s==1){
initializemailmap();
check=1;
Log.e("Activity","link");
}else if(s==2){
elat5=Double.parseDouble(flat5);
elng5=Double.parseDouble(flng5);
check=1;
initializemailmap();
Log.e("Activity","Find");
}else{
initializemap();
check=0;
Log.e("Activity","Normal");
}
if( check == 1){
getActivity().startService(new Intent(getActivity(),FindMapDataService.class));
handler = new Handler();
handler.postDelayed(runn, 10000);
}
runn = new Runnable() {
#Override
public void run() {
flat5=FindMapDataService.latt;
flng5=FindMapDataService.lng;
if(flat5 != null && flng5 != null){
elat5=Double.parseDouble(flat5);
elng5=Double.parseDouble(flng5);
createMailMap();
}
// createMailMap();
handler.postDelayed(this, ftime);
}
};
// Show current location
gmap.setMyLocationEnabled(true);
if(check == 0){
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
double glat = location.getLatitude();
double glng = location.getLongitude();
CameraUpdate myLoc = CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder().target(new LatLng(glat,glng)).zoom(12).build());
gmap.moveCamera(myLoc);
}
return view;
}
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
double lat=arg0.getLatitude();
double lng=arg0.getLongitude();
CameraUpdate myLoc = CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder().target(new LatLng(lat,lng)).zoom(15).build());
gmap.moveCamera(myLoc);
gmap.setOnMyLocationChangeListener(null);
}
//after mail initialisation
private void initializemailmap() {
// TODO Auto-generated method stub
if(gmap == null){
Fragment ft=getFragmentManager().findFragmentById(R.id.mymap);
gmap=((SupportMapFragment) ft).getMap();
createMailMap();
} else{
createMailMap();
Log.e("Find","Create Mail Map");
}
}
//Normal initialisation
private void initializemap() {
// TODO Auto-generated method stub
if(gmap == null){
Fragment ft1=getFragmentManager().findFragmentById(R.id.mymap);
gmap=((SupportMapFragment) ft1).getMap();
}
if (gmap == null) {
Toast.makeText(getActivity(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
private void createMailMap() {
// TODO Auto-generated method stub
maillat=elat5;
// Log.e("latBrowser", Double.toString(latitude));
maillng=elng5;
// Create a LatLng object for the current location
LatLng latLng = new LatLng(maillat, maillng);
// Show the current location in Google Map
gmap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Set zooming control on goole to view location
gmap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
//Add marker at current position
MarkerOptions marker=new MarkerOptions();
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.arr));
//marker.position(latLng).anchor(1,1).rotation(90);
gmap.addMarker(marker.position(new LatLng(maillat, maillng)).title("You are here!"));
//Remove default marker
// gmap.clear();
}
//save preferences
private void SavePreferences(){
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putInt("val", state);
editor.putLong("time", utime);
editor.commit();
}
//load preferences
private void LoadPreferences(){
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
// mapstatus = sharedPreferences.getInt("val",1);
ftime=sharedPreferences.getLong("time", 1);
}
public void onResume(){
super.onResume();
}
public void onStop(){
super.onStop();
SavePreferences();
gmap = null;
}
public void onDestroyView() {
super.onDestroyView();
Fragment f = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.mymap);
if (f != null){
getFragmentManager().beginTransaction().remove(f).commitAllowingStateLoss();
}
}
public void onDestroy(){
super.onDestroy();
MainActivity.status=0;
if(check == 1){
getActivity().stopService(new Intent(getActivity(),FindMapDataService.class));
}
SavePreferences();
}
}

you need to destroy map when you are using map inside Fragment
public void onDestroy(){
gmap = null;
super.onDestroy();
MainActivity.status=0;
if(check == 1){
getActivity().stopService(new Intent(getActivity(),FindMapDataService.class));
}
SavePreferences();
}
also update in OnCreateView method
...
//Check location data source
initializemailmap();
if(s==1){
check=1;
Log.e("Activity","link");
}else if(s==2){
elat5=Double.parseDouble(flat5);
elng5=Double.parseDouble(flng5);
check=1;
initializemailmap();
Log.e("Activity","Find");
}else{
initializemap();
check=0;
Log.e("Activity","Normal");
}
...
this code from your OnCreateView menthod
i hope it helps.

In my case I changed getFragmentManager().beginTransaction() with getChildFragmentManager().beginTransaction() and everything works fine now.

Related

How to toggle Action Bar while touching the map like Uber

I have implemented a map that behaves like Uber app i.e pin in center and map drags under the pin and the pin gets the location from map. But I am not able to implement the touch event for toggling the action bar just exactly Uber do. Please help me to implement that feature. First I have used support map fragment but to set touch events a view was required so later on I used MapView.Below is my code:
package com.example.myfastapp;
import java.util.List;
import java.util.Locale;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentSender.SendIntentException;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class mapFragment extends Fragment implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
MapView mapView;
//private View touch;
private GoogleMap map;
private LatLng center;
private LatLng currentpoint;
private Geocoder geocoder;
private List<Address> addresses;
double latitude;
double longitude;
protected Context context;
SupportMapFragment mf;
View v;
private static final CharSequence[] MAP_TYPE_ITEMS = { "Road Map",
"Satellite", "Terrain" };
// A request to connect to Location Services
private LocationRequest mLocationRequest;
private TextView markerText, Address;
private LinearLayout markerLayout;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private GPSTracker gps;
// Milliseconds per second
public static final int MILLISECONDS_PER_SECOND = 1000;
// The update interval
public static final int UPDATE_INTERVAL_IN_SECONDS = 5;
// A fast interval ceiling
public static final int FAST_CEILING_IN_SECONDS = 1;
// Update interval in milliseconds
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* UPDATE_INTERVAL_IN_SECONDS;
// A fast ceiling of update intervals, used when the app is visible
public static final long FAST_INTERVAL_CEILING_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* FAST_CEILING_IN_SECONDS;
public mapFragment(Context context) {
super();
this.context = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.mapfragment, container, false);
// v.setOnDragListener(new MyDragListener());
mapView = (MapView)v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
ImageButton mapType = (ImageButton) v.findViewById(R.id.mapType);
mapType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMapTypeSelectorDialog();
}
});
ImageButton myLocationCustomButton = (ImageButton)v.findViewById(R.id.myLocationCustom);
myLocationCustomButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
gps = new GPSTracker(getActivity());
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
currentpoint = new LatLng(latitude, longitude);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(currentpoint, 18);
map.animateCamera(cameraUpdate);
map.setMyLocationEnabled(true);
}
});
markerText = (TextView) v.findViewById(R.id.locationMarkertext);
Address = (TextView) v.findViewById(R.id.adressText);
markerLayout = (LinearLayout) v.findViewById(R.id.locationMarker);
// Getting Google Play availability status
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,
getActivity(), requestCode);
dialog.show();
} else {
// Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
return v;
}
public void toggleActionBar()
{
ActionBar ab = getActivity().getActionBar();
if (ab != null)
{
if (ab.isShowing())
{
ab.hide();
}
else
{
if(!ab.isShowing())
{
ab.show();
}
}
}
}
private void setupMap() {
try {
/*map = ((SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map)).getMap();*/
map = mapView.getMap();
// Enabling MyLocation in Google Map
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
map.getUiSettings().setMyLocationButtonEnabled(false);
map.getUiSettings().setCompassEnabled(false);
map.getUiSettings().setRotateGesturesEnabled(true);
map.getUiSettings().setZoomGesturesEnabled(true);
try {
MapsInitializer.initialize(this.getActivity());
} catch (Exception e) {
e.printStackTrace();
}
PendingResult<Status> result = LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient, mLocationRequest,
new LocationListener() {
#Override
public void onLocationChanged(Location location) {
markerText.setText("Location received: "
+ location.toString());
}
});
Log.e("Reached", "here");
result.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.e("Result", "success");
} else if (status.hasResolution()) {
// Google provides a way to fix the issue
try {
status.startResolutionForResult(getActivity(), 100);
} catch (SendIntentException e) {
e.printStackTrace();
}
}
}
});
gps = new GPSTracker(getActivity());
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
currentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(currentpoint).zoom(16f).tilt(30).bearing(90).build();
map.setMyLocationEnabled(true);
map.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
map.clear();
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
//toggleActionBar();
center = map.getCameraPosition().target;
markerText.setText(" Set your Location ");
map.clear();
markerLayout.setVisibility(View.VISIBLE);
try
{
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
markerLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
LatLng latLng1 = new LatLng(center.latitude,
center.longitude);
Marker m = map.addMarker(new MarkerOptions()
.position(latLng1)
.title(" Set your Location ")
.snippet("")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.my_location)));
m.setDraggable(true);
markerLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
setupMap();
}
#Override
public void onConnectionSuspended(int cause) {
}
#Override
public void onLocationChanged(Location location) {
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected void onPreExecute() {
Address.setText(" Getting location ");
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(context, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + " ");
str.append(city + " " + region_code + " ");
str.append(zipcode + " ");
}
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0) + ", "
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
/*
* public void addMarker(double lati, double longi) {
*
* LatLng latlng = new LatLng(lati, longi);
*
* MarkerOptions mo = new MarkerOptions(); mo.position(latlng);
* mo.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_location));
* mo.title("My Location:"+ latlng); map.addMarker(mo);
*
* //map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng,
* 15));//previous code CameraPosition cameraPosition = new
* CameraPosition.Builder() .target(latlng) .zoom(11.0f) .bearing(90) //
* Orientation of the camera to east .tilt(30) // Tilt of the camera to 30
* degrees .build();
* map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
* map.setMyLocationEnabled(true);
* map.getUiSettings().setCompassEnabled(true);
* map.getUiSettings().setZoomControlsEnabled(true);
* //map.setMapType(GoogleMap.MAP_TYPE_NORMAL); }
*/
public void showMapTypeSelectorDialog() {
// Prepare the dialog by setting up a Builder.
final String fDialogTitle = "Select Map Type";
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(fDialogTitle);
// Find the current map type to pre-check the item representing the
// current state.
int checkItem = map.getMapType() - 1;
System.out.print(checkItem);
// Add an OnClickListener to the dialog, so that the selection will be
// handled.
builder.setSingleChoiceItems(MAP_TYPE_ITEMS, checkItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item)
{
// Locally create a finalised object.
// Perform an action depending on which item was
// selected.
switch (item)
{
case 1:
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 2:
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
default:
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
dialog.dismiss();
}
});
// Build the dialog and show it.
AlertDialog fMapTypeDialog = builder.create();
fMapTypeDialog.setCanceledOnTouchOutside(true);
fMapTypeDialog.show();
}
#Override
public void onResume()
{
super.onResume();
mapView.onResume();
mapView.getMap();
}
#Override
public void onPause()
{
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory()
{
super.onLowMemory();
mapView.onLowMemory();
}
}
The onCameraChangeListener is deprecated, but good news is that google has released 3 new listeners.
See: GoogleMap.OnCameraChangeListener
This interface was deprecated.
Replaced by GoogleMap.OnCameraMoveStartedListener, GoogleMap.OnCameraMoveListener and GoogleMap.OnCameraIdleListener. The order in which the deprecated onCameraChange method will be called in relation to the methods in the new camera change listeners is undefined.
I have used these listeners and now i am able get the hold and release event on map.
I believe you should add an onMarkerDragListener to your map object and do your code inside.
map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
});
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"/>
<ImageButton
android:id="#+id/fabButton"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_gravity="bottom|right"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:background="#drawable/fab_bcg"
android:src="#drawable/ic_favorite_outline_white_24dp"
android:contentDescription="Desc"/>
This is methods for show and hide views
private void hideViews() {
mToolbar.animate().translationY(-mToolbar.getHeight()).setInterpolator(new AccelerateInterpolator(2));
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mFabButton.getLayoutParams();
int fabBottomMargin = lp.bottomMargin;
mFabButton.animate().translationY(mFabButton.getHeight()+fabBottomMargin).setInterpolator(new AccelerateInterpolator(2)).start();
}
private void showViews() {
mToolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
mFabButton.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
}

Every time I click on button rangeincrement and rangeDecrement, the application stops. anyone have some solution?

I am trying to write code on button click in a fragment,but the buttons are not working. The buttons are set to increase and decrease the value of textview (rangeText).
I have implemented OnClickListener to my fragment.
I want to know where is the mistake.
package com.neoresearch.bookmyspace;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* A fragment that launches other parts of the demo application.
*/
public class ParkingFinderMapFragment extends Fragment implements View.OnClickListener {
LinearLayout layoutOfPopup;
PopupWindow popupMessage;
Button popupButton, insidePopupButton, searchButton, rangeIncrement, rangeDecrement;
TextView rangeText;
TextView name, contact, address, availability;
AutoCompleteTextView searchText;
LatLng latLng;
MarkerOptions markerOptions;
MapView mMapView;
GoogleMap googleMap;
private EditText editText;
String string;
private View v;
int range;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
v = inflater.inflate(R.layout.fragment_parking_finder_map, container,
false);
searchText = (AutoCompleteTextView) v.findViewById(R.id.search_on_map);
searchButton = (Button) v.findViewById(R.id.button_search);
rangeIncrement = (Button) v.findViewById(R.id.range_increment);
rangeDecrement = (Button) v.findViewById(R.id.range_decrament);
rangeText = (TextView) v.findViewById(R.id.range_select);
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 = 17.385044;
double longitude = 78.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);
LatLng indore = new LatLng(22.7000, 75.9000);
final MarkerOptions marker2 = new MarkerOptions().position(indore).title("Indore");
googleMap.addMarker(marker2);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(22.7000, 75.9000)).zoom(8).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
PopupOnMap pop = new PopupOnMap(getActivity());
pop.show();
pop.setName("prafull", marker.getTitle(), "8269564260");
return false;
}
});
searchButton.setOnClickListener(this);
rangeDecrement.setOnClickListener(this);//these are my buttons
rangeIncrement.setOnClickListener(this);
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.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();
}
//here is onclick listeners
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_search:
break;
case R.id.range_increment:
range = Integer.parseInt(rangeText.getText().toString());
if (range > 0 && range < 20) {
range = range++;
}
rangeText.setText(range);
break;
case R.id.range_decrament:
range = Integer.parseInt(rangeText.getText().toString());
if (range > 0 && range < 20) {
range = range--;
}
rangeText.setText(range);
break;
}
}
}
Make the following changes to your onClick() method :
case R.id.range_increment:
range = Integer.parseInt(rangeText.getText().toString());
if (range > 0 && range < 20) {
range = range++;
}
rangeText.setText(String.valueOf(range));
break;
case R.id.range_decrament:
range = Integer.parseInt(rangeText.getText().toString());
if (range > 0 && range < 20) {
range = range--;
}
rangeText.setText(String.valueOf(range));
break;

How to transfer data from one activity to another? Android application [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 8 years ago.
I want to trasfer data (a longitude and a latitude) from one activity to another. The goal is to transfer this data to the camera, to see how the objects (augmented reality) move in real-time.
LocationGoogleMap.class
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.beyondar.android.plugin.googlemap.GoogleMapWorldPlugin;
import com.beyondar.android.world.GeoObject;
import com.beyondar.android.world.World;
import com.example.pfg_v7.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class LocationGoogleMap extends FragmentActivity implements
OnMarkerClickListener, OnClickListener, LocationListener {
private GoogleMap mMap;
private GoogleMapWorldPlugin mGoogleMapPlugin;
private World mWorld;
Marker mMark;
private LocationManager oLoc;
private Location currentLoc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_google);
Button myLocationButton = (Button) findViewById(R.id.myLocationButton);
myLocationButton.setVisibility(View.VISIBLE);
myLocationButton.setOnClickListener(this);
Criteria oGPSSettings = new Criteria();
oGPSSettings.setAccuracy(Criteria.ACCURACY_FINE);
oGPSSettings.setSpeedRequired(true);
oGPSSettings.setAltitudeRequired(true);
oGPSSettings.setBearingRequired(true);
oGPSSettings.setCostAllowed(false);
oGPSSettings.setPowerRequirement(Criteria.POWER_MEDIUM);
oLoc = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = oLoc.getBestProvider(oGPSSettings, true);
if (provider != null) {
oLoc.requestLocationUpdates(provider, 1000, 1, this);
} else {
Toast.makeText(getBaseContext(), "No GPS", Toast.LENGTH_SHORT)
.show();
finish();
}
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (mMap == null) {
return;
}
// We create the world and fill the world
mWorld = CreateWorld.generateObjects(this);
// As we want to use GoogleMaps, we are going to create the plugin and
// attach it to the World
mGoogleMapPlugin = new GoogleMapWorldPlugin(this);
// Then we need to set the map into the GoogleMapPlugin
mGoogleMapPlugin.setGoogleMap(mMap);
// Now that we have the plugin created let's add it to our world.
// NOTE: It is better to load the plugins before start adding object in
// to the world.
mWorld.addPlugin(mGoogleMapPlugin);
mMap.setOnMarkerClickListener(this);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mGoogleMapPlugin.getLatLng(), 15));
mMap.animateCamera(CameraUpdateFactory.zoomTo(19), 2000, null);
}
#Override
public void onLocationChanged(Location location) {
currentLoc = location;
LatLng oPos = new LatLng(currentLoc.getLatitude(),
currentLoc.getLongitude());
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (mMap != null) {
mMap.clear();
mMark = mMap.addMarker(new MarkerOptions().position(oPos).title(
"My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(oPos, 17));
}
// We create the world and fill the world
mWorld = CreateWorld.generateObjects(this);
// As we want to use GoogleMaps, we are going to create the plugin and
// attach it to the World
mGoogleMapPlugin = new GoogleMapWorldPlugin(this);
// Then we need to set the map into the GoogleMapPlugin
mGoogleMapPlugin.setGoogleMap(mMap);
// Now that we have the plugin created let's add it to our world.
// NOTE: It is better to load the plugins before start adding object in
// to the world.
mWorld.addPlugin(mGoogleMapPlugin);
}
/*
*
* mMap = ((SupportMapFragment)
* getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); if
* (mMap == null) { return; }
*
* // We create the world and fill the world mWorld =
* CreateWorld.generateObjects(this);
*
*
*
* // As we want to use GoogleMaps, we are going to create the plugin and //
* attach it to the World mGoogleMapPlugin = new GoogleMapWorldPlugin(this);
* // Then we need to set the map into the GoogleMapPlugin
* mGoogleMapPlugin.setGoogleMap(mMap); // Now that we have the plugin
* created let's add it to our world. // NOTE: It is better to load the
* plugins before start adding object in // to the world.
* mWorld.addPlugin(mGoogleMapPlugin);
*
* //NO
* AÑADIDO//////----------------------------------------////////////////
* ////////////////////////////////////////
* mMap.setOnMarkerClickListener(this);
*
* mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mGoogleMapPlugin.getLatLng
* (), 15)); mMap.animateCamera(CameraUpdateFactory.zoomTo(19), 2000, null);
* //NO
* AÑADIDO/////-----------------------------------------////////////////
* /////////////////////////////////////////
*
* // Lets add the user position to the map GeoObject user = new
* GeoObject(1000l); user.setGeoPosition(mWorld.getLatitude(),
* mWorld.getLongitude()); user.setImageResource(R.drawable.flag);
* user.setName("User position"); mWorld.addBeyondarObject(user);
*
* BeyondarLocationManager.addWorldLocationUpdate(mWorld);
* BeyondarLocationManager.addGeoObjectLocationUpdate(user);
*
* // We need to set the LocationManager to the BeyondarLocationManager.
* BeyondarLocationManager .setLocationManager((LocationManager)
* getSystemService(Context.LOCATION_SERVICE));
*/
#Override
public boolean onMarkerClick(Marker marker) {
// To get the GeoObject that owns the marker we use the following
// method:
GeoObject geoObject = mGoogleMapPlugin.getGeoObjectOwner(marker);
if (geoObject != null) {
Toast.makeText(
this,
"Click on a marker owned by a GeoOject with the name: "
+ geoObject.getName(), Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
protected void onResume() {
super.onResume();
// When the activity is resumed it is time to enable the
// BeyondarLocationManager
oLoc.removeUpdates(this);
oLoc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
}
#Override
protected void onPause() {
super.onPause();
// To avoid unnecessary battery usage disable BeyondarLocationManager
// when the activity goes on pause.
oLoc.removeUpdates(this);
}
#Override
public void onClick(View v) {
// When the user clicks on the button we animate the map to the user
// location
LatLng userLocation = new LatLng(currentLoc.getLatitude(),
currentLoc.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
mMap.animateCamera(CameraUpdateFactory.zoomTo(19), 2000, null);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
oLoc.removeUpdates(this);
oLoc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
}
#Override
public void onProviderEnabled(String provider) {
oLoc.removeUpdates(this);
oLoc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
Toast.makeText(getBaseContext(), provider + " is enabled.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
oLoc.removeUpdates(this);
Toast.makeText(getBaseContext(), provider + " is disabled.",
Toast.LENGTH_SHORT).show();
}
}
CameraWithLocation.class
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import com.beyondar.android.fragment.BeyondarFragmentSupport;
import com.beyondar.android.world.World;
public class CameraWithLocation extends FragmentActivity implements
OnSeekBarChangeListener, OnClickListener {
private BeyondarFragmentSupport mBeyondarFragment;
private World mWorld;
private SeekBar mSeekBarMax, mSeekBarMin;
private Button mShowMap;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
loadViewFromXML();
// We create the world and fill it ...
mWorld = CreateWorld.generateObjects(this);
// .. and send it to the fragment
mBeyondarFragment.setWorld(mWorld);
// We also can see the Frames per seconds
mBeyondarFragment.showFPS(true);
}
private void loadViewFromXML() {
setContentView(R.layout.camera_with_location);
mBeyondarFragment = (BeyondarFragmentSupport) getSupportFragmentManager()
.findFragmentById(R.id.beyondarFragment);
mSeekBarMax = (SeekBar) findViewById(R.id.seekBarMax);
mSeekBarMin = (SeekBar) findViewById(R.id.seekBarMin);
mSeekBarMax.setOnSeekBarChangeListener(this);
mSeekBarMin.setOnSeekBarChangeListener(this);
mSeekBarMax.setMax(100);
mSeekBarMin.setMax(100);
mShowMap = (Button) findViewById(R.id.showMapButton);
mShowMap.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == mShowMap) {
Intent intent = new Intent(this, LocationGoogleMap.class);
startActivity(intent);
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (seekBar == mSeekBarMax) {
mBeyondarFragment.setMaxFarDistance(progress);
} else if (seekBar == mSeekBarMin) {
mBeyondarFragment.setMinFarDistanceSize(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
CreateWorld.class
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.beyondar.android.plugin.googlemap.GoogleMapWorldPlugin;
import com.beyondar.android.world.GeoObject;
import com.beyondar.android.world.World;
import com.example.pfg_v7.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class CreateWorld{
public static final int LIST_TYPE_EXAMPLE_1 = 1;
public static World sharedWorld;
public static World generateObjects(Context context) {
if (sharedWorld != null) {
return sharedWorld;
}
sharedWorld = new World(context);
// The user can set the default bitmap. This is useful if you are
// loading images form Internet and the connection get lost
sharedWorld.setDefaultImage(R.drawable.beyondar_default_unknow_icon);
// User position (you can change it using the GPS listeners form Android
// API)
sharedWorld.setGeoPosition(40.332177, -3.766126);
// Create an object with an image in the app resources.
GeoObject go1 = new GeoObject(1l);
go1.setGeoPosition(40.390691, -3.636787);
go1.setImageResource(R.drawable.rectangle);
go1.setName("CercaDeCasa");
GeoObject go2 = new GeoObject(2l);
go2.setGeoPosition(40.391076, -3.635275);
go2.setImageResource(R.drawable.rectangle);
go2.setName("Cruce Superior");
GeoObject go3 = new GeoObject(3l);
go3.setGeoPosition(40.390821, -3.635967);
go3.setImageResource(R.drawable.rectangle);
go3.setName("Cruce del parque");
GeoObject go4 = new GeoObject(4l);
go4.setGeoPosition(40.390288, -3.635356);
go4.setImageResource(R.drawable.rectangle);
go4.setName("Callejuela");
// Add the GeoObjects to the world
sharedWorld.addBeyondarObject(go1);
sharedWorld.addBeyondarObject(go2);
sharedWorld.addBeyondarObject(go3);
sharedWorld.addBeyondarObject(go4);
return sharedWorld;
}
}
To sum up: I'd need to give to the Camera class the information about my location.
For example :
In MainActivity :
Intent intent = new Intent();
intent.setClass(this, Other_Activity.class);
intent.putExtra("EXTRA_ID", "SOME DATAS");
startActivity(intent);
In Other_Activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String datas= extras.getString("EXTRA_ID");
if (datas!= null) {
// do stuff
}
}
More informations here :
http://developer.android.com/reference/android/content/Intent.html
taken from here: Simple example for Intent and Bundle
Check this link please..
It says..
Use this to "put" the file...
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String keyIdentifer = null;
i.putExtra("STRING_I_NEED", strName);
startActivity(i);
Then, to retrieve the value try something like:
String newString;
if (savedInstanceState == null) {
extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}

onMarkerClick not working (v2)

I'm having some troubles with onMarkerClick
Basically for now I just want that when ANY marker previously created starts the same activity when clicked. I will implement the filtering of the marker later on.
What I get now is no error. Simply nothing happens when the marker is clicked.
Here is my source:
I'm looping through a database to populate the map and then the markers are displayed
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class NevianoMaps extends Activity implements OnMarkerClickListener{
private GoogleMap googleMap;
DatabaseHandler db = new DatabaseHandler(this);
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.neviano_maps);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(double value, double value)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
//Luoghi di interesse check
if (getIntent().getIntExtra("str1", 0) == 0){
for(int x = 1; x < 6; x = x+1) {
latitude = db.getCultura(x).getCoordLat();
longitude = db.getCultura(x).getCoordLong();
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title(db.getCultura(x).getName()));
}
}
if (getIntent().getIntExtra("str1", 1) == 1){
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(double value, double value)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.title("Sport"));
}
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public boolean onMarkerClick(Marker arg0) {
Intent i = new Intent(this, informazioni.class);
//i.putExtra("str1", db.getCulturaName(arg0.getTitle()).getDescription());
startActivity(i);
return false;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Hope somebody can help! Thank you
In your initilizeMap() method, please add this line after you've got your map:
googleMap.setOnMarkerClickListener(this);

Google Map API 2 not showning current location

I am try to showing current location using android google map api 2, I run this on my phone which is wifi enable.
But it always shows Longitude and Latitude 0.0 , 0.0 .
Here is my code
package com.google.map;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.map.R;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener{
private GoogleMap googlemap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isGooglePlay())
{
setContentView(R.layout.activity_main);
setUpMap();
}
}
#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
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(item.getItemId() == R.id.action_legalnotices)
{
startActivity(new Intent(this, LegalNoticesActivity.class));
}
return super.onOptionsItemSelected(item);
}
private boolean isGooglePlay()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if(status == ConnectionResult.SUCCESS)
{
return true;
}
else
{
((Dialog)GooglePlayServicesUtil.getErrorDialog(status, this, 10)).show();
Toast.makeText(getApplicationContext(), "Google play is not available.", Toast.LENGTH_LONG).show();
}
return false;
}
#SuppressLint("NewApi") private void setUpMap()
{
if(googlemap == null)
{
googlemap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
if(googlemap != null)
{
// map code
googlemap.setMyLocationEnabled(true);
googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LocationManager lo = (LocationManager) getSystemService(LOCATION_SERVICE);
String provider = lo.getBestProvider(new Criteria(),true);
if(provider == null)
{
onProviderDisabled(provider);
}
else
{
onProviderEnabled(provider);
}
Location loc = lo.getLastKnownLocation(provider);
if(loc != null)
{
onLocationChanged(loc);
}
googlemap.setOnMapLongClickListener(onLongClickMapSettings());
}
}
}
private OnMapLongClickListener onLongClickMapSettings() {
// TODO Auto-generated method stub
return new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng arg0) {
// TODO Auto-generated method stub
Log.i(arg0.toString(),"Long Click");
}
};
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latlng = new LatLng(location.getLatitude(),location.getLongitude());
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
googlemap.moveCamera(CameraUpdateFactory.zoomTo(5));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Location lo = new Location(provider);
LatLng latlng = new LatLng(lo.getLatitude(),lo.getLongitude());
Log.i(latlng.toString(),"Current Location" );
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
googlemap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 5));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Here is the Log cat value of my android application.
05-07 22:16:31.636: I/lat/lng: (0.0,0.0)(17967): Current Location
Move your Log.i(latlng.toString(),"Current Location" ); code to the onLocationChanged-method, you don't have a location yet in onProviderEnabled.
mMap.setMyLocationEnabled(true); // just add one line it wil work.

Categories

Resources