getMap to getMapAsync covert error - java

I never try Google Map. This is a client project where they use
compile project(':google-play-services_lib')
I have to improve their design to support the latest version of android that's way
compile 'com.android.support:appcompat-v7:25.1.1'
it shows me an error so I try this link.
It say It can be fixed by updating the Google Play Services dependency to 6.1.+. .
Then I use
compile 'com.google.android.gms:play-services:10.2.0'
to support latest version of android.
Then it shows me error getMap() so I convert it to getMapAsync() but what are duing is private static GoogleMap googlemap; then assign it like this:
googlemap=((MapFragment)getFragmentManager().findFragmentById(R.id.places_map)).getMap();
When i convert it to
googlemap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
It show me error. What to do
public class Frnt_mapActivity extends AppCompatActivity implements OnMapReadyCallback {//implements OnMapClickListener, OnMarkerDragListener {
public static double Shop_lat;
public static double Shop_lng;
public String Shop_title;
public String Shop_address;
public String Shop_icons;
ProgressDialog mDialog;
JSONObject jsonobject3;
JSONArray jsonarray3;
// Google Map
//private static GoogleMap googlemap;
public static EditText edit_search;
public static Button btn_search;
ArrayList<SearchBeams> getAllimgs;
// Location
ArrayList<String> world_locationlist;
ArrayList<LocationBeams> worldlocation;
// Looking for
ArrayList<String> looking_forlist;
ArrayList<LookingForBeams> world_looking_for;
public static ArrayList<SearchBeams> searchdata_list;
public static ArrayList<NormalSearchBeams> normlSearchList;
public static String mid;
public static String mpost_title;
public static String mimage;
public static List<String> imglist;
ArrayList<All_products_lat_long> venueList;
Spinner mySpinner2;
public static ArrayList<SearchBeams> GetIMG;
public static TextView txtlocation;
public static TextView txtlookingfor;
public static ArrayList<All_products_lat_long> mpItm;
String vals;
private int i;
private Intent intent;
HashMap<Marker, Integer> hashMap = new HashMap<Marker, Integer>();
public static LatLng latlong;
#Override
public void onMapReady(GoogleMap map) {
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frnt_map_activity);
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mySpinner2 = (Spinner) findViewById(R.id.spin_looking_for);
// Spinner adapter
txtlookingfor = (TextView) findViewById(R.id.country);
txtlocation = (TextView) findViewById(R.id.rank);
SupportMapFragment mapFragment=getSupportFragmentManager().findFragmentById(R.id.places_map).getMapAsync(this);
googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googlemap.setMyLocationEnabled(true);
googlemap.getUiSettings().setZoomControlsEnabled(true);
googlemap.getUiSettings().setMyLocationButtonEnabled(true);
googlemap.getUiSettings().setCompassEnabled(true);
googlemap.getUiSettings().setRotateGesturesEnabled(true);
googlemap.getUiSettings().setZoomGesturesEnabled(true);
googlemap.setMyLocationEnabled(true);
intent=new Intent(Frnt_mapActivity.this,MainActivity.class);
googlemap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
i=hashMap.get(arg0);
intent.putExtra("PRODUCT_ID", venueList.get(i).getId());
startActivity(intent);
//overridePendingTransition( R.anim.slide_right, R.anim.slide_left );
}
});
new Frnt_mIcons_Activity().execute();
new LocationList().execute();
new LookingForList().execute();
edit_search = (EditText)findViewById(R.id.txt_search);
btn_search = (Button)findViewById(R.id.btn_search);
btn_search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text;
text=edit_search.getText().toString();
// text!=null &&
if(text.equals("") && text.startsWith(" ")==false){
new GetSearch_data().execute();
/*new Get_normal_search().execute();
edit_search.setText("");*/
}else
new Get_normal_search().execute();
edit_search.setText("");
//new GetSearch_data().execute();
}
});
}
They are calling googlemap and also adding marks. how i can implement it
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try{
if(bd!=null){
Marker marker=googlemap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
.title(venue.getPost_title())
.icon(bd));
hashMap.put(marker, k);
}
}catch (Exception e){
e.printStackTrace();
}
}
switch (Integer.parseInt(venueList.get(k).getId()))
{
case 5689 :
Marker marker=googlemap.addMarker(new MarkerOptions()
.position(new LatLng(la, ln))
.title(venueList.get(k).getPost_title())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.fruitandveg)));
hashMap.put(marker, k);
break;
case 5779 :
Marker marker1=googlemap.addMarker(new MarkerOptions()
.position(new LatLng(la, ln))
.title(venueList.get(k).getPost_title())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.coffee)));
hashMap.put(marker1, k);
break;
.....}

This is a client project where they use compile project(':google-play-services_lib')
So, you replace that with this (notice the -maps)
compile 'com.google.android.gms:play-services-maps:10.2.0'
Then it shows me error getMap() so I convert it to getMapAsync()
Which is correct, but
You really should not have a static map variable. If there are static variables all over the app, something is wrong in the design.
When i convert it to googlemap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this); It show me error
Well, yes that'll error
1) getActivity() is not necessary. You already are in an Activity class
2) getSupportFragmentManager() will only be available if you extends AppCompatActivity (or FragmentActivity) in the class definition
3) getMapAsync(this) will not work unless you implements OnMapReadyCallback on the class definition.
If you do all that, then you will have something like
import com.google.android.gms.maps.OnMapReadyCallback;
public class YourActivity extends AppCompatActivity
implements OnMapReadyCallback {
private void SupportMapFragment mMapFragment;
// private GoogleMap mMap; // Commented so you don't use in onCreate
#Override
public void onMapReady(GoogleMap map) {
// this.mMap = map;
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// TODO: call other map setup methods
}
// Inside onCreate
mMapFragment = getSupportFragmentManager().findFragmentById(R.id.map);
mMapFragment.getMapAsync(this);
// Don't do this in onCreate
// googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}

Related

SmartLocationLibrary location is always null

I'm trying to learn SmartLocationLibrary for Android to get location and the location I get from it is always null, so I get null object reference errors when I try to do something with it.
I made a Utility class for SmartLocatonLibrary
public class LocationUtil implements OnLocationUpdatedListener, OnActivityUpdatedListener {
private final String TAG = "LocationUtil: ";
private Location location;
private DetectedActivity activity;
private LocationGooglePlayServicesProvider provider;
private Context context;
public LocationUtil(Context context) {
this.context = context;
}
/**
* If lastLocation is not null then the location is set to last location recorded by phone
*/
public void getLastLocation(){
Location lastLocation = SmartLocation.with(context).location().getLastLocation();
if(lastLocation != null){
location = lastLocation;
}
DetectedActivity detectedActivity = SmartLocation.with(context).activity().getLastActivity();
if(detectedActivity != null) activity = detectedActivity;
}
/**
* Basically this starts the location tracking
* If you want one tick of location use .oneFix() on the smartLocation builder
* If you want continous tracking just don't add the .oneFix()
*/
public void startLocation(){
provider = new LocationGooglePlayServicesProvider();
provider.setCheckLocationSettings(true);
SmartLocation smartLocation = new SmartLocation.Builder(context).logging(true).build();
smartLocation.location(provider)
.continuous()
.start(this);
smartLocation.activity()
.start(this);
}
/**
* This stops the tracking
*/
public void stopLocation(){
SmartLocation.with(context).location().stop();
Log.d(TAG, "stopLocation: Location Stopped");
SmartLocation.with(context).activity().stop();
Log.d(TAG, "stopLocation: Activity Recognition Stopped");
}
#Override
public void onActivityUpdated(DetectedActivity detectedActivity) {
this.activity = detectedActivity;
}
#Override
public void onLocationUpdated(Location location) {
this.location = location;
}
//--------SETTERS----------
public void setProvider(LocationGooglePlayServicesProvider provider) {
this.provider = provider;
}
//--------GETTERS----------
public Location getLocation() {
return location;
}
public LocationGooglePlayServicesProvider getProvider() {
return provider;
}
}
And here is the Maps Activity that use it
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private final String TAG = "MAPY";
private int LOCATION_PERMISSION_ID = 1001;
private GoogleMap mMap;
Location location;
LocationUtil locationUtil = new LocationUtil(MapsActivity.this);
Button centerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
centerButton = findViewById(R.id.centerCameraBtn);
centerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(location != null)
mMap.moveCamera((CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()))));
}
});
}
#Override
protected void onStop() {
super.onStop();
locationUtil.stopLocation();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Check for permissions if they are not granted request them
if (ContextCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_ID);
return;
} else{
locationUtil.startLocation();
}
locationUtil.getLastLocation();
Log.d(TAG, "onMapsReady.lat: " + location.getLatitude() + " onMapsReady.lng: " + location.getLongitude());
location = locationUtil.getLocation();
LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(currentLocation).title("My current location").snippet("This is a sinppet"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(locationUtil.getProvider() != null){
locationUtil.getProvider().onActivityResult(requestCode, resultCode, data);
}
}
}
I did it like the author of the library showed here but it doesn't work. And the funny thing is it worked yesterday. I'm testing it on my personal phone. The location, mobile data and wifi are turned on and working fine. I got the permissions, i added the permissions to the manifest(both FINE and COARSED) and in my dependencies are
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:support-media-compat:28.0.0'
implementation 'io.nlopez.smartlocation:library:3.3.3'
implementation 'com.google.android.gms:play-services-maps:16.0.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
I really don't know whats going on, please help me.
OK so this doesn't work because I want to log the value of the location variable that hasn't been initialised. Debugging it with debugger shows that I'm getting the location. But to be more funny since this is a project just to test the library in the main app the same Utility class won't fetch me a location even if I'm doing everything same as here...

Heat Maps are not displaying in fragment

I'm trying to display heatmap points in android using google maps utility library, nothing is displayed on the map. I don't know if I need something else, I've looked at examples but in my case it doesn't work. I'm using fragments.
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
private HeatmapTileProvider mProvider;
protected LatLng mCenterLocation = new LatLng( 39.7392, -104.9903 );
public MapFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
mMapView = (MapView) rootView.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();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// For showing a move to my location button
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
LatLng colorado = new LatLng(39.7392, -104.9903);
googleMap.addMarker(new MarkerOptions().position(colorado).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(colorado).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
addHeatMap();
}
});
return rootView;
}
public void addHeatMap(){
ArrayList<LatLng> locations = generateLocations();
mProvider = new HeatmapTileProvider.Builder().data(locations).build();
mProvider.setRadius(HeatmapTileProvider.DEFAULT_RADIUS );
googleMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
}
private ArrayList<LatLng> generateLocations() {
ArrayList<LatLng> locations = new ArrayList<LatLng>();
double lat;
double lng;
Random generator = new Random();
for (int i = 0; i < 1000; i++) {
lat = generator.nextDouble() / 3;
lng = generator.nextDouble() / 3;
if (generator.nextBoolean()) {
lat = -lat;
}
if (generator.nextBoolean()) {
lng = -lng;
}
locations.add(new LatLng(mCenterLocation.latitude + lat, mCenterLocation.longitude + lng));
}
return locations;
}
#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();
}
}
Checking the Heatmaps guide, I don't see any issues about it. Try to call clearTileCache(), its indicated in its API reference that you should call it after setRadius.

Google Maps How to - MY LOCATION Android - Crashing/NotWorking

Using Default Google Maps Activity from Android Studio and want to use MY Location displayed on a marker on a map plus the my location blue google button which is usually located bottom right.
Have looked over hundreds of examples and code and nothing is working.
package com.example.br.nightlyfegooglemap;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,OnInfoWindowClickListener,
OnMyLocationChangeListener, GoogleMap.OnMyLocationChangeListener {
private GoogleMap mMap;
protected GoogleApiClient mGoogleApiClient;
private static final String STATE_IN_PERMISSION="inPermission";
private static final int REQUEST_PERMS=1337;
private boolean needsInit=false;
private boolean isInPermission=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (savedInstanceState==null) {
needsInit=true;
}
else {
isInPermission=
savedInstanceState.getBoolean(STATE_IN_PERMISSION, false);
}
onCreateForRealz(canGetLocation());
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_IN_PERMISSION, isInPermission);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions,
int[] grantResults) {
isInPermission=false;
if (requestCode==REQUEST_PERMS) {
if (canGetLocation()) {
onCreateForRealz(true);
}
else {
finish(); // denied permission, so we're done
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
if (needsInit) {
CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,-73.98180484771729));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
mMap.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
mMap.setOnInfoWindowClickListener(this);
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
}
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, marker.getTitle(), Toast.LENGTH_LONG).show();
}
#Override
public void onMyLocationChange(Location lastKnownLocation) {
Log.d(getClass().getSimpleName(),
String.format("%f:%f", lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude()));
}
private void onCreateForRealz(boolean canGetLocation) {
if (canGetLocation) {
if (readyToGo()) {
setContentView(R.layout.activity_maps);
MapFragment mapFrag=
(MapFragment)getFragmentManager().findFragmentById(
R.id.map);
mapFrag.getMapAsync(this);
}
}
else if (!isInPermission) {
isInPermission=true;
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMS);
}
}
private void addMarker(GoogleMap map, double lat, double lon,
int title, int snippet) {
map.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
.title(getString(title))
.snippet(getString(snippet)));
}
private boolean canGetLocation() {
return(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)==
PackageManager.PERMISSION_GRANTED);
}
}
ERRORS
//CANNOT RESOLVE SYMBOLS FOR THESE
OnInfoWindowClickListener,
OnMyLocationChangeListener
new PopupAdapter
readyToGo
//REQUIRES PERMISSION
mMap.setMyLocationEnabled(true);
//DEPRECATED
mMap.setOnMyLocationChangeListener(this);

Can't Create ClusterManager For Android Google Maps

I'm trying to use Google Maps clustering in my Android project.
Currently for a start I actually copied the code from the demo
https://github.com/googlemaps/android-maps-utils
(which runs fine for me)
On my project, however, on
mClusterManager = new ClusterManager<MyItem>(this, getMap());
it throws:
java.lang.ClassCastException: android.widget.ImageView cannot be cast to com.google.maps.android.ui.RotationLayout
I can't even figure out what why is any there casting?
Basically took the activity (and all needed related classes) from
https://github.com/googlemaps/android-maps-utils/blob/master/demo/src/com/google/maps/android/utils/demo/BigClusteringDemoActivity.java
public class ClusteringDemoActivity extends BaseDemoActivity {
private ClusterManager<MyItem> mClusterManager;
#Override
protected void startDemo() {
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(51.503186, -0.126446), 10));
mClusterManager = new ClusterManager<MyItem>(this, getMap());
getMap().setOnCameraChangeListener(mClusterManager);
try {
readItems();
} catch (JSONException e) {
Toast.makeText(this, "Problem reading list of markers.", Toast.LENGTH_LONG).show();
}
}
private void readItems() throws JSONException {
InputStream inputStream = getResources().openRawResource(R.raw.radar_search);
List<MyItem> items = new MyItemReader().read(inputStream);
mClusterManager.addItems(items);
}
public static void launch(Context context) {
context.startActivity(new Intent(context, ClusteringDemoActivity.class));
}
}
public abstract class BaseDemoActivity extends FragmentActivity {
private GoogleMap mMap;
protected int getLayoutId() {
return R.layout.map;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutId());
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap != null) {
return;
}
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap != null) {
startDemo();
}
}
/**
* Run the demo-specific code.
*/
protected abstract void startDemo();
protected GoogleMap getMap() {
setUpMapIfNeeded();
return mMap;
}
}
public class MyItem implements ClusterItem {
private final LatLng mPosition;
public MyItem(double lat, double lng) {
mPosition = new LatLng(lat, lng);
}
#Override
public LatLng getPosition() {
return mPosition;
}
}
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
and have on my build.gradle
compile 'com.google.android.gms:play-services-maps:8.4.0'
compile 'com.google.maps.android:android-maps-utils:0.3+'
Does anyone have any idea, please?
Incase this can help anyone -
I had in my own project a layout named text_bubble.xml
This clashed with a layout of the library, by the same name, and it caused the exception.
Simply renaming my layout resolved this.

How can I send current location from one activity to another?

I am using map to get current location and now I want to send my current location to another activity which has form to input all the data.
I am confused about which variables and methods I should use to send the location data.
ChooseFromMapActivity
This is the activity where I am getting my current location. And now on Click of useLocation layout I want to send this location to the edit text of another activity i.e GoSendActivity.
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
private LinearLayout useLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
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(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.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(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
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 String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
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 + "");
}
} else {
}
} catch (IOException 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) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
GoSendActivity
This is my GoSendActivity which has edit text view. I want to get the current location on edttxt_from text view.
public class GoSend extends AppCompatActivity {
LatLng latLng;
private GoogleMap mMap;
MarkerOptions markerOptions;
LinearLayout ll;
Toolbar toolbar;
EditText editTextLocation;
EditText edtxt_from;
EditText edtxt_to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
setUI();
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void setUI() {
ll = (LinearLayout) findViewById(R.id.LinearLayoutGoSend);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("GO-SEND");
try {
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
edtxt_from=(EditText)findViewById(R.id.editText_from);
edtxt_to=(EditText)findViewById(R.id.editText_to);
edtxt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
edtxt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
}
}
Location class
public class Location {
private int id;
private String mFrom_loc;
private String mTo_loc;
private String mFromloc_details;
private String mToloc_details;
private String mItems_details;
public Location(int id,String mFrom_loc,String mFromloc_details,String mTo_loc,String mToloc_details,String mItems_details)
{
this.id=id;
this.mFrom_loc=mFrom_loc;
this.mFromloc_details=mFromloc_details;
this.mTo_loc=mTo_loc;
this.mToloc_details=mToloc_details;
this.mItems_details=mItems_details;
}
public Location(String mFrom_loc){
this.mFrom_loc=mFrom_loc;
}
public Location(){}
public int getId(int id){return id;}
public String getmFrom_loc(String mFrom_loc){return mFrom_loc;}
public String getmTo_loc(String mTo_loc){return mTo_loc;}
public String getmFromloc_details(String mFromloc_details){return mFromloc_details;}
public String getmToloc_details(String mToloc_details){return mToloc_details;}
public String getmItems_details(String mItems_details){return mItems_details;}
public void setId(){this.id=id;}
public void setmFrom_loc(){this.mFrom_loc=mFrom_loc;}
public void setmTo_loc(){this.mTo_loc=mTo_loc;}
public void setmFromloc_details(){this.mFromloc_details=mFromloc_details;}
public void setmToloc_details(){this.mToloc_details=mToloc_details;}
public void setmItems_details(){this.mItems_details=mItems_details;}
}
How can I achieve this?? Please help..
try this :
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChooseFromMapActivity.this , GoSendActivity.class);
intent.putExtra("Latitude", latitude);
intent.putExtra("Longitude", longitude);
startActivity(intent);
}
});
And inside onCreate of GoSendActivity,get latitude and longitude like this :
Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("Latitude");
double longitude = extras.getDouble("Longitude");
}
Now you can set latitude and longitude to your edittext edittext.setText(String.valueOf(latitude));
Apart from passing the data to the next activity using intents, you can also use shared preferences, TinyDB lib achieves great results for caching data. Yoou will need to sync this in your gradle file :
compile 'com.mukesh:tinydb:1.0.1'
then in your onCreate in each activity you will be using the same, initialize the tinyDB by passing application context
TinyDB tinyDB = new TinyDB(getApplicationContext());
With that you can store and retrieve any data within the app using a key-value pair,example to store your coordinates, just call :
tinyDB.putDouble("latitude",latitude);
tinyDB.putDouble("longitude",longitude);
And you can retrieve the data this way:
double latitude = tinyDB.getDouble("latitude");
double longitude = tinyDB.getDouble("longitude");
This class supports all data formats, from Strings,Double,Float and even objects such as ararayLists. Would highly recommend you to try it out.
Make this class as serialisable and put it into intent using bundle.putSerializable("myclaa",location).
Class Location implements Seraializable{
}

Categories