I want the map in this application to start with the current location of the user but it keeps starting with the default location being the location with latitude = 0 and longitude = 0.
It also doesn't work when I walk around with phone in hand..
This is my code:
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
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 LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LocationManager locationManager;
private double longitude;
private double latitude;
public Criteria criteria;
public String bestProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getLocation();
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
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();
}
}
}
protected void getLocation() {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
//You can still do this if you like, you might get lucky:
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
Log.e("TAG", "GPS is on");
latitude = location.getLatitude();
longitude = location.getLongitude();
}
else{
//This is what you need:
locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Location"));
}
#Override
public void onLocationChanged(Location location) {
//remove location callback:
locationManager.removeUpdates(this);
//open the map:
latitude = location.getLatitude();
longitude = location.getLongitude();
}
// ... other LocationListener methods that I left empty. I removed to shorten the code
}
}
Could you please tell me where's the problem? I've tried many fixes from StackOF but I couldn't get it to work.
Related
Below is my MapsActivity.java,
I'm trying to getCurrentLocation and place the marker there.
When I run app I am unable to see the marker on my map. What went wrong?
Thanks for the help.
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.bustracker.usc.myapplication.R;
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.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationManager manager;
private LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("INSIDE ONCREATE", "TRUE");
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);
//get the location service
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
//request the location update thru location manager
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;
}
Log.d("BFORE ISPROVIDERENABLED", "TRUE");
if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get the latitude and longitude from the location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.d("LATLNG", latitude+" " +longitude);
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
String result = addresses.get(0).getSubLocality() + ":";
result += addresses.get(0).getLocality() + ":";
result += addresses.get(0).getCountryCode();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title(result));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}else if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get the latitude and longitude from the location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
String result = addresses.get(0).getSubLocality() + ":";
result += addresses.get(0).getLocality() + ":";
result += addresses.get(0).getCountryCode();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title(result));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
/**
* 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 onPause() {
super.onPause();
manager.removeUpdates(locationListener);
Log.i("onPause...","paused");
}
}
Above is my MapsActivity.java,
I'm trying to getCurrentLocation and place the marker there.
When I run app I am unable to see the marker on my map. What went wrong?
Thanks for the help.
Try to create the markers and all things about the map inside the onMapReady method, if it doesn't work try seeing if you are getting your location properly
Hope it helps you, Pd: sorry for my english
Make sure you are getting valid latLng
OR
If you want to add custom icon to set marker add it like:
map.addMarker(new MarkerOptions().position(latLng).title(result)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
the only reason i'm asking this again, is because i've tried all the answers and its not working for me i'm trying to get the current user location but it's not working so this is what i've been trying to do, btw i already setted up all the permissions neeeded and i keep getting the double android location.getlatitude on a null object reference error and fatal execption main , pleaaase help me
this my GPSTRACKER Java class code :
package com.example.nefissa.androidtest;
import android.*;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
public class GPSTracker extends Service implements LocationListener{
private final Context context;
boolean isGPSEnabled =false;
boolean isNetworkEnabled =false;
boolean canGetLocation =false;
Location location;
protected LocationManager locationManager;
public GPSTracker(Context context){
this.context=context;
}
// create a GetLocation Method //
public Location getLocation(){
try{
locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);
if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED ){
if(isGPSEnabled){
if(location==null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,100000,10,this);
if(locationManager!=null){
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
// if location is not found from GPS then it will found from network //
if(location==null){
if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,100000,10,this);
if(locationManager!=null){
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
}
}
}catch(Exception e){
}
return location;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#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) {
}
}
and My Main Activity code :
package com.example.nefissa.androidtest;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
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.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private GPSTracker gpsTracker;
private Location mLocation;
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
gpsTracker= new GPSTracker(getApplicationContext());
mLocation=gpsTracker.getLocation();
latitude= mLocation.getLatitude();
longitude= mLocation.getLongitude();
// 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(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("you are here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
After onMapReady is called, you'd better to initialize gpsTracker.
gpsTracker= new GPSTracker(getApplicationContext());
if(gpsTracker!=null){
mLocation=gpsTracker.getLocation();
latitude= mLocation.getLatitude();
longitude= mLocation.getLongitude();
}
And I think gpsTracker.getLocation have to change to logic.
please read a android gps guide.
Try using
GPS Tracker
public GPSTracker(Activity activity) {
this.mActivity = activity;
getLocation();
}
public void getLocation() {
try {
locationManager = (LocationManager) mActivity
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled || !isNetworkEnabled) {
showSettingsAlert();
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to ic_check GPS/wifi enabled
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
also from Activity call as
onCreate
//
gps = new GPSTracker(SignUpActivity.this);
if (gps.canGetLocation) {
lat = String.valueOf(gps.getLatitude());
lng = String.valueOf(gps.getLongitude());
}
Comment below if you still got issue
I'm using GPS to get my location in an android app. But when I create a LocationManager it returns null pointer exception. Even though the permissions are set on the androidMainFest.xml and also for the app, still it returns the following exception. Can anyone help in advance. Thank You!
Code :
package com.example.pavsaranga.scat;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.google.android.gms.location.LocationListener;
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.MarkerOptions;
public class Map extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
double longitude, latitude;
String bestProvider;
LocationManager lm;
Location location;
Criteria criteria;
LocationListener locList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomGesturesEnabled(true);
try {
boolean permissionGranted = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
if (permissionGranted) {
setMyLocation();
} else {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 200);
}
} catch(Exception e){
e.printStackTrace();
}
}
private void setMyLocation() {
try {
lm = (LocationManager) this.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) {
Toast.makeText(Map.this, "Please Grant Permission.", Toast.LENGTH_SHORT).show();
} else {
criteria = new Criteria();
bestProvider = String.valueOf(lm.getBestProvider(criteria, true)).toString();
location = lm.getLastKnownLocation(bestProvider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
else{
lm.requestLocationUpdates(bestProvider, 2000, 0, (android.location.LocationListener) locList);
}
LatLng myLocation = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(myLocation).title("You Are Here!"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
}
} catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 200: {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(Map.this, "Thank You, Permission Granted!.", Toast.LENGTH_SHORT).show();
setMyLocation();
}
}
}
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
Exception :
java.lang.IllegalArgumentException: invalid listener: null
MainFest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
LocationManager isn't returning null. The error is that you are passing a null LocationListener.
You need to initialize loclist before passing it to requestLocationUpdates
You are declaring locList and passing it in to the lm.requestLocationUpdates(bestProvider, 2000, 0, (android.location.LocationListener) locList); method. It doesn't look like you are initializing it though.
That is what the exception it telling you, you are passing in null where it is expecting a listener.
You can remove the locList declaration and try making the following change:
change
lm.requestLocationUpdates(bestProvider, 2000, 0, (android.location.LocationListener) locList);
to
lm.requestLocationUpdates(bestProvider, 2000, 0, new LocationListener(){
// #Override
public void onStatusChanged(String provider, int status, Bundle extras) {
/*
* Called when the provider status changes.
* This method is called when a provider is unable to fetch a location
* or if the provider has recently become available after a period of unavailability.
*/
}
// #Override
public void onLocationChanged(Location location) {
/*
* Called when the location has changed.
*/
}
});
So i am new to database programming as well as android programming, i am trying to get a user's location and store the location into the parse.com database. I believe my code is along the right path, can someone assist me with the issue?
import android.content.Context;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;
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.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;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.SaveCallback;
import com.parse.SignUpCallback;
public class MapsActivity extends FragmentActivity implements RoutingListener {
protected GoogleMap mMap;
protected LatLng start;
protected LatLng end;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mMap = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
try {
setUpMapIfNeeded();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
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();
}
}
}
private void setUpMap() {
// Enable MyLocation Layer of Google Map
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
// Get longitude of the current location
String userId = "O6pGXcJy3C";
//String username = "Nick";
ParseObject globeobject = new ParseObject("global");
globeobject.put("username","Alana");
globeobject.put("userID",userId);
final ParseGeoPoint point = new ParseGeoPoint(latitude, longitude);
globeobject.put("Location", point);
}
}
#Override
public void onRoutingFailure() {
// The Routing request failed
}
#Override
public void onRoutingStart() {
// The Routing Request starts
}
}
I believe you have done the needful.
At the of "final ParseGeoPoint point = new ParseGeoPoint(latitude, longitude);
globeobject.put("Location", point);" lines put
globeobject.saveInBackground();
This is my Activity:
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
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.
private LocationManager locationManager;
private String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
addMaracanazinho();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void addMaracanazinho()
{
LatLng pos = new LatLng(-34.642491, -58.642841);
mMap.addMarker(new MarkerOptions()
.title("Maracanazinho")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(pos));
}
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)
{
mMap.setMyLocationEnabled(true);
}
}
}
}
I want that my app start with a zoom in my current location. I looked for some codes but noone have the answer that I want. Can someone tell me what I should add?
I find this: How would I make my google maps app start with zoom on my current location
But I don't understand how put this in my code.
Thanks and sorry for my bad english.
change your setUpMapIfNeeded method to following and add the rest of code as well. Basically you need to register a LocationListener with the location manager of the system. You get a callback as onLocationChanged(Location l). This Location l is the users position, then you set this new location to your map. Simple.
private void setUpMapIfNeeded()
{
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, this.locationListener);
// 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)
{
mMap.setMyLocationEnabled(true);
}
}
}
private LocationListener locationListener = new MyLocationListener(){
#Override
public void onLocationChanged(Location location) {
// called when the listener is notified with a location update from the GPS
LatLng userPosition = new LatLng(location.getLatitude(),
location.getLongitude());
if (mMap != null){
mMap .moveCamera(CameraUpdateFactory.newLatLngZoom(userPosition,
15));
}
}
#Override
public void onProviderDisabled(String provider) {
// called when the GPS provider is turned off (user turning off the GPS on the phone)
}
#Override
public void onProviderEnabled(String provider) {
// called when the GPS provider is turned on (user turning on the GPS on the phone)
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the status of the GPS provider changes
}
};
Used animateCamera for that like
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longitude), 18.0f));
In your MapsActivity file -> Change setUpMapIfNeeded() function:
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LocationManager locationManager;
private String provider;
...
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)
{
mMap.setMyLocationEnabled(true);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(myLocation.getLatitude(), myLocation.getLongitude()))
.zoom(14).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
}
}
You can also set the Zoom by setting the number (Here Zoom is 14).