Why isn't my variable updating after calling a method? - android

package my.package.name;
import android.content.DialogInterface;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
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.OnMapReadyCallback;
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 MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
int x;
#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);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
something();
System.out.println(sumX); //this prints 0
}
private void something() {
x = 6;
System.out.println(sumX); //this prints 6
}
}
It seems the order of execution is not happening like I want it to. On the console output, x = 0 gets printed before x = 6. Why is that? Does Android run method calls concurrently?

I tried your code and worked for me, otherwise to solve your problem you can try this:
try {
something();
} catch (Exception e) {
} finally {
System.out.println(x);
}
or (Not very clear)
something();
Handler handler = new Handler();
final Runnable runnable = new Runnable() {
public void run() {
System.out.println(sumX);
}
};
handler.postDelayed(runnable, 50); //50 millisec (delay)

Related

Current Location input in LatLng causing crash

I'm trying to put a marker at my current location (using the google maps api). While direct input values in the LatLng are working, indirectly calling currentLocation.getLatitude() and currentLocation.getLongitude() is crashing my application for some reason, i know it's this line because the app doesn't crash until i add this line.
Here's my MapsActivity class-
package com.example.shreyass.tourist;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.internal.IGoogleMapDelegate;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.common.api.GoogleApiClient;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{
private GoogleMap mMap;
private Location currentLocation;
GoogleApiClient googleApiClient;
#Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super`enter code here`.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
googleApiClient.connect();
// 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);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker at current location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if(ContextCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
!=PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MapsActivity.this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},1);
}
else {
currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
try this changes..
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{
private GoogleMap mMap;
private Location currentLocation;
GoogleApiClient googleApiClient;
#Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super`enter code here`.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);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
googleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if(ContextCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
!=PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MapsActivity.this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},1);
}
else {
currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker at current location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}

Hide buttons in an activity after a while in android studio

I am working on a map application, using android studio.
I have a map activity and I need some buttons on my map, for example zoom in,zoom out,search,...
I want to hide these buttons after a while and show them again onClick.
but I don't know how to do that.
here is my code
MapActivity.java
package com.example.tourismproject;
import android.location.Location;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
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.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final String TAG = MapsActivity.class.getSimpleName();
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private float zoomLevel = 15; //street view
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
//mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
and my XML file is :
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tourismproject.MapsActivity" />
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//hide buttons after 1 sec
yourbutton.setVisibility(false);
}
}, 1000);
someView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(button.getVisibility()==View.VISIBLE){
button.setVisibility(View.GONE);
} else {
button.setVisibility(View.VISIBLE);
}
}
});
Also for better usability you can add some fading animation with something like this:
ObjectAnimator alpha = ObjectAnimator.ofFloat(button, "alpha", 1, 0);
//alpha.setDelay(500);
//alpha.setDuration(1000);
alpha.start();
You can use
#Override
public void onClick(View v) {
button.setVisibility(false);
}
you can use
Thread.sleep(3000);//for three seconds
button.setVisibility(false);
to make it invisible after a while //in this case after three seconds
i hope this is helpful

Android Google Map V2 unable to alter my map within a fragment

I am building an app to track a users training session ie running.
The app should record the users location and then create a polyline from the results.
I have used the navigation drawer activity within android studio to strucure my app. However I think this has put my map fragment within a fragment.
My problem is that I do not seem to be able to set defaults for the map. For example if I try to set the map type within the setUpMap to satelite the changes never take effect. This is not limited to setting default, I am also not getting location updates.
Any help would be greatly appreciated
Here is how my map is called:
package com.example.craig.runtrackerv3;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class menu1_fragment extends Fragment {
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.activity_maps, container, false);
return rootview;
}
}
Here is the map object:
package com.example.craig.runtrackerv3;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
showCurrentLocation(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
locationManager.requestLocationUpdates(provider, 2000, 0, locationListener);
// Getting initial Location
Location location = locationManager.getLastKnownLocation(provider);
// Show the initial location
if(location != null)
{
showCurrentLocation(location);
}
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
private void showCurrentLocation(Location location){
mMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat: " + location.getLatitude() + ", Lng: " + location.getLongitude())
//.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_peterleow))
.flat(true)
.title("I'm here!"));
// Zoom in, animating the camera.
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 18));
}
}
Here is the map xml:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/map"
tools:context="com.example.craig.runtrackerv3.MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
My suspicion is I need some sort of callback but I'm not to sure how to implement it.
Any help would be greatly appreciated.
You need to use Map Fragment instead of Map Activity.
public class MapaFragment extends Fragment implements OnMapClickListener {
MapView mapView;
GoogleMap map;
.....
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map, container, false);
MapsInitializer.initialize(getActivity());
mapView = (MapView) v.findViewById(R.id.mapaPrincipal);
mapView.onCreate(savedInstanceState);
map = mapView.getMap();
if(map != null) {
map.setOnMapClickListener(this);
}
return v;
}
}
You just don't init map correctly, it tight connect to activity life cycle
GoogleMap mMap;
MapView map = (MapView) findViewById(R.id.map);
map.onCreate(mActivity.getStateBundle());
map.onResume();
map.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
initializeMap(googleMap, device);
}
});
and when you done with all call
map.onPause();
map.onDestroy();

Remove default user's location icon

Im developing an app using Google Maps v2 for Android and I managed to put a custom icon to the user's position but I can't remove the default one, so it overlays my custom icon like in the image:
(It is that big just for now :p )
My code is like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
map.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
if (location == null)
return;
mPositionMarker = map.addMarker(new MarkerOptions()
.flat(true)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.logop1))
.anchor(0.5f, 1f)
.position(new LatLng(location.getLatitude(), location.getLongitude())));
}
});
}
So:
1) Is there a way to remove the default blue dot of user's current location?
2) Will the user location be updated when I move in the "real world" (I cant test it for conectivity reasons) or do I have to write/override a method to update users position?
Thanks in advance
You will have to stop using GoogleMap.setMyLocationEnabled and write a bit more code, including having your own LocationClient and adding Circle for accuracy.
You have to do that on your own.
- set to false gmaps.getUiSettings().setMyLocationButtonEnabled(false);
create your own location button
if you get your current location, set a marker with your icon on that
if you click on your location button, move the camera and center it to the map
That will remove the blue dot
map.setMyLocationEnabled(true); remove line
Thanks joao2fast4u (lol) and ṁᾶƔƏň ツ. I followed your recomendations and I managed to make it work. Since I didn't see any answer concrete to this problem I'm posting my solution here:
package com.onsoftwares.ufvquest;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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 MapActivity extends ActionBarActivity implements LocationListener, GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {
private GoogleMap map;
private Marker mPositionMarker;
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
private LatLng mLatLng;
private boolean mUpdatesRequested = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest.setFastestInterval(1000);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
}
#Override
protected void onStart() {
super.onStart();
mLocationClient.connect();
};
#Override
protected void onStop() {
if (mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(this);
mLocationClient.disconnect();
}
super.onStop();
};
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// Get the current location
Location currentLocation = mLocationClient.getLastLocation();
// Display the current location in the UI
if (currentLocation != null) {
LatLng currentLatLng = new LatLng (currentLocation.getLatitude(), currentLocation.getLongitude());
if (mPositionMarker == null) {
mPositionMarker = map.addMarker(new MarkerOptions()
.position(currentLatLng)
.title("Eu")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.male_user_marker)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15));
} else
mPositionMarker.setPosition(currentLatLng);
}
}
}

Displaying google map in android app with specified options

I'm new to android development and I had been trying to display a map in my application for some time now. I finally managed to do it but I want to display it with some specified options such as zoom level, location, etc but its proving difficult.
The following is my .xml file
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
And the following is my .java file
package com.fourapps.cabkonnect;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import android.location.Location;
import android.graphics.Color;
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 com.google.android.gms.maps.model.PolylineOptions;
/**
* Created by nanakay on 6/6/13.
*/
public class Home extends FragmentActivity {
GoogleMap map;
private static final LatLng GOLDEN_GATE_BRIDGE = new LatLng(37.828891,-122.485884);
private static final LatLng APPLE = new LatLng(37.3325004578, -122.03099823);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (map == null) {
Toast.makeText(this, "Google maps not available", Toast.LENGTH_LONG).show();
}
}
}
The map is displaying but I would want to display it with my own options.
I would be very happy if someone could help. Thanks
First have to obtain the current location:
private Location mCurrentLocation;
mCurrentLocation = mLocationClient.getLastLocation();
Read here to know more.
And then you can animate to the location using:
LatLng myLaLn = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
CameraPosition camPos = new CameraPosition.Builder().target(myLaLn)
.zoom(15)
.bearing(45)
.tilt(70)
.build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
map.animateCamera(camUpd3);
I give you a simple but complete example to show a map and the current location:
public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationClient mLocationClient;
private Location mCurrentLocation;
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setUpLocationClientIfNeeded();
mLocationClient.connect();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (map == null) {
Toast.makeText(this, "Google maps not available",
Toast.LENGTH_LONG).show();
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
Toast.makeText(getApplicationContext(), "Waiting for location",
Toast.LENGTH_SHORT).show();
mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
#Override
public void onPause() {
super.onPause();
if (mLocationClient != null) {
mLocationClient.disconnect();
}
}
/*
* Called by Location Services when the request to connect the client
* finishes successfully. At this point, you can request the current
* location or start periodic updates
*/
#Override
public void onConnected(Bundle dataBundle) {
mCurrentLocation = mLocationClient.getLastLocation();
if (mCurrentLocation != null) {
Toast.makeText(getApplicationContext(), "Found!",
Toast.LENGTH_SHORT).show();
centerInLoc();
}
}
private void centerInLoc() {
LatLng myLaLn = new LatLng(mCurrentLocation.getLatitude(),
mCurrentLocation.getLongitude());
CameraPosition camPos = new CameraPosition.Builder().target(myLaLn)
.zoom(15).bearing(45).tilt(70).build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
map.animateCamera(camUpd3);
MarkerOptions markerOpts = new MarkerOptions().position(myLaLn).title(
"my Location");
map.addMarker(markerOpts);
}
/*
* Called by Location Services if the connection to the location client
* drops because of an error.
*/
#Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the attempt to Location Services fails.
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects. If the error
* has a resolution, try sending an Intent to start a Google Play
* services activity that can resolve error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available
*/
Log.e("Home", Integer.toString(connectionResult.getErrorCode()));
}
}
}
Note1: I omitted the "Check for Google Play Services" part by simplicity but it should be added as a good practice.
Note2: You need the google-play-services_lib project and reference it from yours.
You can find all information about interacting with google maps in android here
From the google maps documentation referenced above, just some examples:
Zoom controls:
The Maps API provides built-in zoom controls that appear in the bottom right hand corner of the map. These are enabled by default, but can be disabled by calling UiSettings.setZoomControlsEnabled(boolean).
My Location button:
The My Location button appears in the top right corner of the screen only when the My Location layer is enabled. When a user clicks the button, the camera animates to focus on the user's current location if the user's location is currently known. A click will also trigger the GoogleMap.OnMyLocationButtonClickListener. You can disable the button from appearing altogether by calling UiSettings.setMyLocationButtonEnabled(boolean).
Add a marker:
The below example demonstrates how to add a marker to a map. The marker is created at coordinates 0,0, and displays the string "Hello world" in an infowindow when clicked.
private GoogleMap mMap;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Hello world"));

Categories

Resources