public class MainActivity extends FragmentActivity{
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
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() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
//mMap.setMyLocationEnabled(true);
}
}
This is my Activity.
I want to start my app with my current location. I looked for some codes but none have the answer that I want. Can someone tell me what I should add?
Did you try:
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
Please use Android's LocationManager to get Lat/Lng with respect to your current services. Please refer to this answer that explains the usage of LocationManager.
After getting a Location object from the LocationManager, use the lat/lng to position the map like this.
Related
I have followed some online tutorials for adding markers to the google maps api in android. There code is structured differently from mine but in general I saw them do it in the onCreate method. Below I have a really basic code to try and get a marker in the middle of the map, however, I get a null pointer exception. Does anyone know of a simple fix to this?
Here is the error in detail and below is my method. I have map declared as a global variable.
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
serviceManager = ServiceManager.getInstance(getActivity());
userID = getString(R.string.mobile_health_client_user_id);
client = MobileIOClient.getInstance(getContext(), userID);
//client = MobileIOClient.getInstance(userID);
map.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Hello world"));
}
I have also ran through the google tutorial which overrides onMapReady() but that method did not work for me either. I am not sure how to get it working in my code and can't find adequate resource online to assist me. Any help would be appreciated.
Thanks
You should not be interacting with the map object in your activity or fragment's onCreate() method. The simple reasoning being that the map probably isn't ready yet. The proper way to handle this is to implement the OnMapReadyCallback interface and add you marker in your implementation of the onMapReady(GoogleMap googleMap) function.
Your solution will need to be slightly different if you are using a MapFragment vs a MapView, but the general idea remains the same.
Example:
public class MyActivity extends Activity implements OnMapReadyCallback {
.
.
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap; // Set your local instance of GoogleMap for future use
map.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Hello world"));
}
.
.
}
If you are using a MapView, you will need to get a handle to your view in your layout and explicitly call map.getMapAsync(this) in order to attach the onMapReady() listener.
I hope this helps!
Here is the code I use:
public class Map extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
public GoogleApiClient mGoogleApiClient;
public static final String TAG = Map.class.getSimpleName();
public LocationRequest mLocationRequest;
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// 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);
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(1 * 1000); // 1 second, in milliseconds
}
/**
* 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.
* 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;
LatLng here = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(here).title("Here!"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(here));
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = null;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
};
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#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();
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude,longitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
Write simply in onMapReadygoogleMap.addMarker(new MarkerOptions().position(new LatLng(0, 0));
I made a code.
In this code, when i click a map, there will be a marker on clicked point.
This is my Code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(getApplicationContext(), "oh, no", Toast.LENGTH_LONG).show();
}
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
String lat = String.valueOf(point.latitude);
String lng = String.valueOf(point.longitude);
MarkerOptions marker = new MarkerOptions().position(
new LatLng(point.latitude, point.longitude)).title("ok");
mMap.addMarker(marker);
}
});
}
}
Question :
What i want is that when i click SetMylocationEnable button, there also added a new marker. And because i want marker is only one in whole map, another marker that has been in the map before is to be removed. How can i do it? Would you teach me?
You can see what button i saying is, in picture. (picture is from : Enable my location icon Googlemap v2)
mMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
Location location = getLocation();
MarkerOptions marker = new MarkerOptions().position(
new LatLng(location.getLatitude(), location.getLongitude())).title("ok");
mMap.addMarker(marker);
return true;
}
});
private Location getLocation() {
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
return locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
}
keep a reference to the marker, if the reference is null then create the marker as you have done, if it is not, then edit the marker and change its location
I new in coding google map,
my question is how i control the user gestur drag , zoom in and zoom out.
because my code always back to the current location of user when i zoomin/out, nad when i drag/ scroll up, down, left, right. always back to the current possition .
its my code for current loc user
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
}
};
You can use a boolean to move the camera only the first time:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener {
private GoogleMap mMap;
private Marker mMarker;
private boolean firstTime = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
}
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if (firstTime) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
firstTime = false;
}
}
}
NOTE: Take into account that this example uses GoogleMap.OnMyLocationChangeListener only because that is the method that you are using in your question, but it's deprecated and you must use the FusedLocationProviderApi according to the documentation:
public final void setOnMyLocationChangeListener
(GoogleMap.OnMyLocationChangeListener listener)
This method was deprecated. use
com.google.android.gms.location.FusedLocationProviderApi instead.
FusedLocationProviderApi provides improved location finding and power
usage and is used by the "My Location" blue dot. See the
MyLocationDemoActivity in the sample applications folder for example
example code, or the Location Developer Guide.
Guys I'm implementing google maps in my android app and instread of creating a marker i've placed a marker image in the middle of map. Now I want that whenever user drags the map i get the location at the centre of the map(where i've placed my image look like a marker).
My map activity is :
public class MapActivity extends FragmentActivity implements LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
TextView Title;
FrameLayout goback;
Location myLocation;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
setUpMapIfNeeded();
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = supportMapFragment.getMap();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
//try
Title=(TextView)findViewById(R.id.map_title);
Title.setText(getIntent().getExtras().getString("Header"));
goback=(FrameLayout)findViewById(R.id.frame_layout);
setUpMapIfNeeded();
// mMap.setMyLocationEnabled(true);
}
#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() {
}
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.marker);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(5));
CameraPosition ll=mMap.getCameraPosition();
Toast.makeText(getApplicationContext(),""+ll,Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
please help me in doing so, thank you :)
First you can get referance of your map container, and calculate center point by dividing 2 width and height.
View containerView=findViewById(R.id.mapContainer);
LatLng centerPoint= this.map.getProjection().fromScreenLocation(new Point(((int)containerView.getWidth/2),((int)(containerView.getHeight/2)));
you can get the center this way:
mMap.getCameraPosition().target
where mMap is the GoogleMap instance from your activity. This will return a LatLng object which basically represents the center of the map. Note that the GeoPoint class is not anymore available.
According to http://developer.android.com/reference/com/google/android/gms/maps/model/CameraPosition.html
target is "The location that the camera is pointing at." (tested it with the sample code and it worked ok for me)
Let me know if this helped you.
Cheers!
You can use this method
MapView.getProjection().fromPixels(x, y)
Where x is half your map width and y is half the height. This should return you a coordinates object which in turn will give you your longitude and latitude of the center of your map
More information on it can be seen here
Google finally added a callback for location changes in the Android API v2! However, I cannot intuitively get it to work, and Google does not have much documentation for it. Has anyone gotten it to work? What more do I need?
public class ... extends SupportMapFragment implements GoogleMap.OnMyLocationChangeListener {
GoogleMap map;
LocationManager locationManager;
String provider;
#Override
public void onActivityCreated(android.os.Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
map = getMap();
if (map != null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager =(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(criteria, false);
}
}
#Override
public void onResume() {
super.onResume();
while(map == null) {
map = getMap();
map.setMyLocationEnabled(true);
map.setOnMyLocationChangeListener(this);
}
}
#Override
public void onMyLocationChange(Location loc) {
//implementation
}
}
This is how I do to navigate to the center of the map when we get the first location-update.
my class header:
public class FragActivity extends SherlockFragmentActivity implements OnMyLocationChangeListener
private GoogleMap mMap;
my mMap-setup:
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = customMapFragment.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null)
setUpMap();
}
setUpMap-method:
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
}
and my onlocationchange:
#Override
public void onMyLocationChange(Location lastKnownLocation) {
CameraUpdate myLoc = CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder().target(new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude())).zoom(6).build());
mMap.moveCamera(myLoc);
mMap.setOnMyLocationChangeListener(null);
}
Works like a charm