So i am doing a project that i only need to get the location, i don't need to show the map or anything like that. I created the GoogleMap mGoogleMap; in the beginning of the class. When asking for the permission of location and course to the user i have this code:
public class Distance extends Activity implements Runnable {
//...
GoogleMap mGoogleMap;
protected LocationManager locationManager;
Location location;
//...
public void onCreate(Bundle savedInstanceState) {
//...
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
} else {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},
TAG_CODE_PERMISSION_LOCATION);
}
//...
The first time i ran the application it worked but the other times got this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(boolean)' on a null object reference.
That error is in the line that have: mGoogleMap.setMyLocationEnabled(true);
I know that i need to initialize the googleMap object because it is blank but i don't know how. Help?
Init the map this way:
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// Add a marker in Sydney, Australia, and move the camera.
LatLng sydney = new LatLng(-34, 151);
mGoogleMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
Related
My basic location application doesent work on my Galaxy A20 running API 29 but works fine on all my emuultors running the same API. im not sure what the problem could be as im not experianced with LOGCAT but the error states as following:
Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference.
THE ERROR IS ON LINE 117 on my project (At the end). But ive highlighted it here
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this , Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER ,0 ,0 , locationListener);
}
}
}
#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;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Marker in user house"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (ContextCompat.checkSelfPermission(this , Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this , new String[]{Manifest.permission.ACCESS_FINE_LOCATION} , 1);
}
else{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER , 0 , 0 , locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()); // ◅ THE ERROR OCCOURS HERE********
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Marker in user house"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
}
}
}
Maybe your phone has not managed to get a GPS fix yet. Check if lastKnowLocation is null before using it, and test the app outside where your phone can "see" the sky.
I am trying to get my updated location from my app. however my app does not check this block of code
public void onSuccess(Location location)
{} inside mFusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener(){} and returns me null location. Even my device location is turned on and the map shows my location. My code for accessing updated location is below:
protected void onCreate(Bundle savedInstanceState) {
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show();
if (mLocationPermissionGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
}
private void getDeviceLocation(){
try {
if(mLocationPermissionGranted) //true in my case
{
mFusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
moveCamera(new LatLng(location.getLatitude(),location.getLongitude()),17);
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()),12),2000,null);
}
else{
Toast.makeText(MapsActivity.this, "Unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException ex){
}
}
I am getting the following exceptions in stacktrace
09-11 15:12:14.525 5864-5864/? E/Zygote: v2
09-11 15:12:14.530 5864-5864/? E/Zygote: accessInfo : 0
09-11 15:12:27.333 5864-5864/com.example.muzammil.maptestingproject E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib, /vendor/lib]]
09-11 15:12:39.327 5864-5864/com.example.muzammil.maptestingproject E/art: The String#value field is not present on Android versions >= 6.0
Everything else is correct including manifest permissions and gradle dependencies. May be any body help me in solving my problem. Thanks in advance.
Fused Location Provider will give the location if at least one client is connected to it. If the client connects, it will immediately try to get a location. If your activity is the first client to connect and you call getLastLocation() that might not be enough time for the first location to come in.
getLastLocation() is suitable where a location is needed immediately or none at all can be used. If you really want to wait for a location it's best to use requestLocationUpdates() and wait for the callback rather than busy waiting in a thread.
Here is the method to get location using requestLocationUpdates()
LocationCallback locationCallback;
LocationRequest locationRequest;
FusedLocationProviderClient fusedLocationClient;
void getLocation() {
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(30 * 1000)
.setFastestInterval(5 * 1000);
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
//Location received
}
};
fusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
And don't forget to remove location updated in onStop or onDestroy
fusedLocationClient?.removeLocationUpdates(locationCallback)
Hey Im new to Android and wondering if someone can help me. I have a MapsActivity which crashes when navigating to it. I think I've narrowed down to exactly where it is from looking through the errors but I cant figure out what to change.
I've added the whole MapsActivity class below. The problem is occuring in the onConnected method on this line mLocationManager.requestLocationUpdates(provider, 5000, 0, this);
. Android Studio recommends I cast 'this' to LocationListener but this doesn't work and the error I get from doing so is listed below the MapsActivity code.
I have also tried entering mLocationListener in the place of 'this' but doesn't work and I get errors which are listed below too.
ANY HELP IS GREATLY APPRECIATED. THANKS!
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 2;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationManager mLocationManager;
private Location mLastLocation;
private LocationListener mLocationListener;
private String mLatitude;
private String mLongitude;
#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);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
//create instance of location manager and get location service
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
/**
* 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));
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
//mLocationManager.removeUpdates((LocationManager) this);
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = mLocationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(provider, 5000, 0, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
mLatitude = String.valueOf(mLastLocation.getLatitude());
mLongitude = String.valueOf(mLastLocation.getLongitude());
Toast.makeText(this, mLatitude + " , " + mLongitude, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Permission denied, please accept permission..", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults){
switch (requestCode){
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION:{
//if request cancelled the results array is empty
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//do task you wish to do
//Intent intent = (new Intent(this, MapsActivity.class));
//startActivity(intent);
}else{
//permission denied, disable functionality(GPS)
}
return;
}
//other cases go here
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
}
}
Casting errors -
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a8460p.locationotes, PID: 23305
java.lang.ClassCastException: com.example.a8460p.locationotes.MapsActivity cannot be cast to android.location.LocationListener
at com.example.a8460p.locationotes.MapsActivity.onConnected(MapsActivity.java:106)
at com.google.android.gms.common.internal.zzm.zzq(Unknown Source)
at com.google.android.gms.internal.zzaal.zzo(Unknown Source)
at com.google.android.gms.internal.zzaaj.zzvE(Unknown Source)
at com.google.android.gms.internal.zzaaj.onConnected(Unknown Source)
at com.google.android.gms.internal.zzaan.onConnected(Unknown Source)
at com.google.android.gms.internal.zzzy.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzl$1.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzf$zzj.zzwZ(Unknown Source)
at com.google.android.gms.common.internal.zzf$zza.zzc(Unknown Source)
at com.google.android.gms.common.internal.zzf$zza.zzu(Unknown Source)
at com.google.android.gms.common.internal.zzf$zze.zzxa(Unknown Source)
at com.google.android.gms.common.internal.zzf$zzd.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Replacing 'this' with mLocationListener errors -
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a8460p.locationotes, PID: 24073
java.lang.IllegalArgumentException: invalid listener: null
at android.location.LocationManager.checkListener(LocationManager.java:1733)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:461)
at com.example.a8460p.locationotes.MapsActivity.onConnected(MapsActivity.java:106)
at com.google.android.gms.common.internal.zzm.zzq(Unknown Source)
at com.google.android.gms.internal.zzaal.zzo(Unknown Source)
at com.google.android.gms.internal.zzaaj.zzvE(Unknown Source)
at com.google.android.gms.internal.zzaaj.onConnected(Unknown Source)
at com.google.android.gms.internal.zzaan.onConnected(Unknown Source)
at com.google.android.gms.internal.zzzy.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzl$1.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzf$zzj.zzwZ(Unknown Source)
at com.google.android.gms.common.internal.zzf$zza.zzc(Unknown Source)
at com.google.android.gms.common.internal.zzf$zza.zzu(Unknown Source)
at com.google.android.gms.common.internal.zzf$zze.zzxa(Unknown Source)
at com.google.android.gms.common.internal.zzf$zzd.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Make MapsActivity implements android.location.LocationListener instead of com.google.android.gms.location.LocationListener
For First crash: this crash is occuring due to the incorrect import for location listener class which you have implements to your Activity.
Change com.google.android.gms.location.LocationListener with android.location.LocationListener
and for second crash use bellow LocationListener, this crash is occuring due your null reference of location listener object.
private LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
Your requestLocationUpdates could not find instance of Listener so add MapsActivity.this to requestLocationUpdates
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(provider, 5000, 0, MapsActivity.this);//Changed here
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
mLatitude = String.valueOf(mLastLocation.getLatitude());
mLongitude = String.valueOf(mLastLocation.getLongitude());
Toast.makeText(this, mLatitude + " , " + mLongitude, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Permission denied, please accept permission..", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
I have a mapsview and it works fine when using getMap() although it shows me a depricated warning. But when i change getMap() to getMapAsync() the app will crash.
Here's my code
public class MapsActivity extends AppCompatActivity implements GoogleMap.OnInfoWindowClickListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnInfoWindowCloseListener,
LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMapAsync(this);
mMap.setOnInfoWindowClickListener(this);
mMap.setOnInfoWindowCloseListener(this);
mMap.setOnMarkerDragListener(this);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
markerPoints.add(latLng);
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(latLng);
}
});
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
//Getting the coordinates
toLatitude = marker.getPosition().latitude;
toLongitude = marker.getPosition().longitude;
dest = new LatLng(toLatitude, toLongitude);
mMap.animateCamera(CameraUpdateFactory.newLatLng(dest));
return ((toLatitude == my_marker.getPosition().latitude) && (toLongitude == my_marker.getPosition().longitude));
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
}
private void setUpMap() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(MapsActivity.this, "Anda harus menyetujuinya agar dapat menikmati semua fitur yang ada", Toast.LENGTH_LONG).show();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder()
.zoom(15) // Sets the zoom
.target(new LatLng(-6.597629,106.79957))
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
Here's the xml layout
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
What's wrong with my code? Any help will be greatly appreciated.
Thanks.
I suppose that mMap is the GoogleMap object here.What you are doing is using mMap before it gets initialized so it must be throwing null pointer exception.
Make sure to use mMap object in onMapReady Callback.Hope it solves
your problem.So, in short all you need to do is place all your mMap
usages in onMap Ready callback
At the moment of getMapAsync call the onMapReady is not done. Be sure that ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) is not null or onMapReady() has finished with success.
Hi currently when i start the application it shows the whole map of the world, when i press the gps button then it zooms into my current location. I want it that when the activity starts it already zooms into your current location. Here is the source code:
public class MainActivity extends Activity {
// Google Map
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
/**
* 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();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
}
You need to get Current Location using Location Listener and animate Camera on that.
First implement LocationListener to your Activity like:
public class BasicMapActivity_new extends Activity implements LocationListener
Now Implement following code in your Activity onCreate(....)
private LocationManager locationManager;
private String provider;
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(BasicMapActivity_new.this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else if(!enabledWiFi){
Toast.makeText(BasicMapActivity_new.this, "Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
//getCurrentLocation();
// Initialize the location fields
if (location != null) {
// Toast.makeText(BasicMapActivity_new.this, "Selected Provider " + provider,
//Toast.LENGTH_SHORT).show();
onLocationChanged(location);
} else {
//do something
}
initilizeMap();
And now implement onLocationChanged(.....)
Marker startPerc=null;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng);
startPerc = mMap.addMarker(new MarkerOptions()
.position(coordinate)
.title("Current Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 18.0f));
}
And also implement
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
initilizeMap();
}
And also add below permission in your manifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I guess you could use something like :
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 5,
center: new google.maps.LatLng(53.671068, -130.25128),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
Google developer page has a lot of sample code using Google Maps API. Check this out : Simple Google Maps
Thanks,
Noel