I'm trying to mess around with the Maps API V2 to get more familiar with it, and I'm trying to start the map centered at the user's current location. Using the map.setMyLocationEnabled(true); statement, I am able to show my current location on the map. This also adds the button to the UI that centers the map on my current location.
I want to simulate that button press in my code. I am familiar with the LocationManager and LocationListener classes and realize that using those is a viable alternative, but the functionality to center and zoom in on the user's location seems to already be built in through the button.
If the API has a method to show the user's current location, there surely must be an easier way to center on the location than to use the LocationManager/LocationListener classes, right?
Try this coding:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
After you instansiated the map object (from the fragment) add this -
private void centerMapOnMyLocation() {
map.setMyLocationEnabled(true);
location = map.getMyLocation();
if (location != null) {
myLocation = new LatLng(location.getLatitude(),
location.getLongitude());
}
map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
Constants.MAP_ZOOM));
}
if you need any guidance just ask but it should be self explantory - just instansiate the myLocation object for a default one...
youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));
16 is the zoom level
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(11);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
});
try this code :
private GoogleMap mMap;
LocationManager locationManager;
private static final String TAG = "";
#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(map);
mapFragment.getMapAsync(this);
arrayPoints = new ArrayList<LatLng>();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
LatLng myPosition;
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
LatLng coordinate = new LatLng(latitude, longitude);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 19);
mMap.animateCamera(yourLocation);
}
}
}
Dont forget to add permissions on AndroidManifest.xml.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Here's how to do it inside ViewModel and FusedLocationProviderClient, code in Kotlin
locationClient.lastLocation.addOnSuccessListener { location: Location? ->
location?.let {
val position = CameraPosition.Builder()
.target(LatLng(it.latitude, it.longitude))
.zoom(15.0f)
.build()
map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
}
}
private void setUpMapIfNeeded(){
if (mMap == null){
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();//invoke of map fragment by id from main xml file
if (mMap != null) {
mMap.setMyLocationEnabled(true);//Makes the users current location visible by displaying a blue dot.
LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE);//use of location services by firstly defining location manager.
String provider=lm.getBestProvider(new Criteria(), true);
if(provider==null){
onProviderDisabled(provider);
}
Location loc=lm.getLastKnownLocation(provider);
if (loc!=null){
onLocationChanged(loc);
}
}
}
}
// Initialize map options. For example:
// mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
#Override
public void onLocationChanged(Location location) {
LatLng latlng=new LatLng(location.getLatitude(),location.getLongitude());// This methods gets the users current longitude and latitude.
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));//Moves the camera to users current longitude and latitude
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng,(float) 14.6));//Animates camera and zooms to preferred state on the user's current location.
}
// TODO Auto-generated method stub
check this out:
fun requestMyGpsLocation(context: Context, callback: (location: Location) -> Unit) {
val request = LocationRequest()
// request.interval = 10000
// request.fastestInterval = 5000
request.numUpdates = 1
request.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
val client = LocationServices.getFusedLocationProviderClient(context)
val permission = ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION )
if (permission == PackageManager.PERMISSION_GRANTED) {
client.requestLocationUpdates(request, object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
val location = locationResult?.lastLocation
if (location != null)
callback.invoke(location)
}
}, null)
}
}
and
fun zoomOnMe() {
requestMyGpsLocation(this) { location ->
mMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(
LatLng(location.latitude,location.longitude ), 13F ))
}
}
This is working Current Location with zoom for Google Map V2
double lat= location.getLatitude();
double lng = location.getLongitude();
LatLng ll = new LatLng(lat, lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));
In kotlin, you will get the current location then move the camera like this
map.isMyLocationEnabled = true
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
if (location != null) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(location.latitude, location.longitude), 14f))
}
}
Also you can animate the move by using this function instead
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.latitude, location.longitude), 14f))
Related
I have an activity with a mapView. Currently i am able to add a fix location by adding the corresponding long and lat into my code.
I would love to get the app to replace those long and lat with my current position.
I've been trying many different ways but I am unable to figure how to do that.
My code looks as following:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
GoogleMap mMap
#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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Copenhagen and move the camera
LatLng Copenhagen = new LatLng(55.67594 , 12.56553);
mMap.addMarker(new MarkerOptions().position(Copenhagen).title("Marker in CBS"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(Copenhagen));
//zoom to position with level 15
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(Copenhagen, 15);
googleMap.animateCamera(cameraUpdate);
}
}
use this code to get your current location first :
public void getCurrentLocation() {
if (isPermisionAccess()) {
locationManager = (LocationManager) mActivity.getSystemService(LOCATION_SERVICE);
if (locationManager != null) {
Location gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location netLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gpsLocation != null) {
currentlatitude = gpsLocation.getLatitude();
currentlongitude = gpsLocation.getLongitude();
} else if (netLocation != null) {
currentlatitude = netLocation.getLatitude();
currentlongitude = netLocation.getLongitude();
}
}
}
}
private boolean isPermisionAccess() {
return (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
}
then :
// Add a marker in myLocation and move the camera
LatLng myLocation = new LatLng(currentlatitude , currentlongitude );
mMap.addMarker(myLocation).title("Marker in CBS"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation ));
//zoom to position with level 15
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(myLocation , 15);
googleMap.animateCamera(cameraUpdate);
and do not forget that :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
I'm trying to set the marker on my current location, so I tried to convert a Location to a LatLng class:
LatLng mCurrentPlace= new LatLng(location.getLatitude(),location.getLongitude());
Then I recalled the addMarker method:
mMap.addMarker(new MarkerOptions()
.title(getString(R.string.default_info_title))
.position(mCurrentPlace)
.snippet(getString(R.string.default_info_snippet)))
But Launching the application by "Run", it arrested.
Where am I goning wrong?
Thanks.
public void moveMap(GoogleMap gMap, double latitude, double longitude) {
Log.v(TAG, "mapMoved: " + gMap);
LatLng latlng = new LatLng(latitude, longitude);
CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(latlng, 6);
gMap.addMarker(new MarkerOptions().position(latlng));
gMap.moveCamera(cu);
}
Call this method where you want location and marker and in on mapasync callback method.
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(context);
gMap = googleMap;
gMap.getUiSettings().setMapToolbarEnabled(false);
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if(items.get(getLayoutPosition())!=null )
moveMap(gMap,latitude, longitude);
}
public void initializeMapView() {
if (mapView != null) {
// Initialise the MapView
mapView.onCreate(null);
// Set the map ready callback to receive the GoogleMap object
mapView.getMapAsync(this);
}
}
Override onMapReadyCallback method and do this.
Call initializeMapView method in onCreate() or In adapter onBindViewHolder
Try using the LatLng.Builder
LatLng.Builder builder = LatLng.newBuilder();
builder.setLatitude(location.getLatitude());
builder.setLongitude(location.getLongitude());
latLng = builder.build();
MAP Activity
public class MapsActivity2 extends FragmentActivity implements
OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener {
private GoogleMap mMap;
LatLng loc;
Location location;
private double currentLatitude = 0;
private double currentLongitude = 0;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
// 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);
locationManager = (LocationManager) getSystemService(Context.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 atLnmove 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.newLg(sydney));
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;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(MapsActivity2.this);
}
public double getLatitude(){
if(location != null){
currentLatitude = location.getLatitude();
}
// return latitude
return currentLatitude;
}
public double getLongitude(){
if(location != null){
currentLongitude = location.getLongitude();
}
// return longitude
return currentLongitude;
}
#Override
public boolean onMyLocationButtonClick() {
location=mMap.getMyLocation();
currentLatitude=getLatitude();
currentLongitude=getLongitude();
LatLng currentLocation = new LatLng(currentLatitude, currentLongitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
mMap.addMarker(new MarkerOptions().position(currentLocation).title("Marker in Current Location"));
return false;
}
}
Resource XML
<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.atziant.parashar.gmapsapi.MapsActivity2" />
public class location_a extends Fragment {
TextView location;
MapView mMapView;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.location_a, container, false);
location = (TextView) rootView.findViewById(R.id.add);
location.setText("Plot -315\nNext to Taj Hotel\nNear layout\nBangalore - 5600092\nKarnataka");
setUpMapIfNeeded();
return rootView;
}
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.
SupportMapFragment mMap = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map_fragment));
//Toast.makeText(getActivity(), "come in" + mMap, Toast.LENGTH_SHORT).show();
//mMap = fm.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
Toast.makeText(getActivity(), "come in", Toast.LENGTH_SHORT).show();
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(12.9120074,77.64910951)).title("Winfo Global"));
mMap.addMarker(new MarkerOptions().position(new LatLng(13.0120074,77.94910951)).title("xyz builder"));
// Enable MyLocation Layer of Google Map
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getActivity().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);
Location myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation!=null) {
double longitude = myLocation.getLongitude();
double latitude = myLocation.getLatitude();
String locLat = String.valueOf(latitude) + "," + String.valueOf(longitude);
// set map type
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
/// double latitude = myLocation.getLatitude();
// Get longitude of the current location
///double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
LatLng myCoordinates = new LatLng(latitude, longitude);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(myCoordinates, 12);
mMap.animateCamera(yourLocation);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(myCoordinates) // Sets the center of the map to LatLng (refer to previous snippet)
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
// mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));
}
}
HERE mMap shows always NULL so it not enter into if statment
if (mMap != null) {Toast.makeText(getActivity(), "comein", Toast.LENGTH_SHORT).show();
setUpMap();
}
pls help me to solve problem
It always null if Google Play services APK is not available in application, please can you check with your code
Try following code
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap mMap = mapFrag.getMap();
Check here for full source code and sample
Edit
Make sure you have written following code in your layout to get map fragment from id.
<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"/>
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17);
how can I redirect my current Location when I open the Google Map
here is my code in SetUpMap()
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
mMap.setMyLocationEnabled(true);
And also how can I change the Marker ? I only get that blue circle in my location. I want to change it to a Pin
If you want to open map with your location through any activity then use this code
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345"));
startActivity(intent);
If you are using Google map then using location find lat long and pass this lat long in maps object
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);
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
Get the current location of the user as soon as your Map is ready and you need to animate the camera like this
Location location = this.mGoogleMap.getMyLocation();
if (location != null) {
LatLng target = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition position = this.mGoogleMap.getCameraPosition();
Builder builder = new CameraPosition.Builder();
builder.zoom(15);
builder.target(target);
this.mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(builder.build()));
}
So, getMyLocation() has to fetch the location of the user. Use can use PROVIDERS to fetch the location. You can also listen to location using LocationListener using GoogleApiClient. Kindly read the documentation of Getting the Last Known Location and Receiving Location Updates before posting here.
To give the custom marker for your location there is something called addMarker
mGoogleMap.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLogitude()))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
You can try with this code, We can get our location in google map by NETWORK_PROVIDER. NETWORK_PROVIDER pick your location from your WIFI location or your network provider companies like(IDEA,AIRTEL,VODAPHONE) .
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
LocationManager location_manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener listner = new getlatlngListner();
location_manager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 2000, 2000, listner);
location_manager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} catch (Exception e) {
e.printStackTrace();
}
private MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.visible(true);
mMarkerOptions.icon(BitmapDescriptorFactory.fromBitmap(Your bitmap));
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng mPos = new LatLng(location.getLatitude(),location.getLongitude());
mMarkerOptions.position(mPos);
mMap.addMarker(mMarkerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(mPos));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
});
I have integrated Google Maps in my Android project. I am getting the view of the map on my device. I want to set the marker to my current location. I have done the following coding but it gives me a Null Pointer Exception on line 43 which is the following line
mMap.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Hello world"));
My codes are as below. Please guide me step by step as to what is going wrong.
public class location extends Activity implements LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.map_location);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.the_map)).getMap();
mMap.setMyLocationEnabled(true);
//mMap.addMarker(new MarkerOptions());
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Hello world"));
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
mMap.animateCamera(cameraUpdate);
// locationManager.removeUpdates(this);
}
Try below Code it worked for me..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_location);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
LocationListener locationListener = new LocationListener() {
void onLocationChanged(Location location) {
// redraw the marker when get location update.
drawMarker(location);
}
if(location!=null){
//PLACE THE INITIAL MARKER
drawMarker(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);
}
}
private void drawMarker(Location location){
googleMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
googleMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + location.getLatitude() + "Lng:"+ location.getLongitude()));
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title("ME"));
}
Ur code seems to be correct. Just check ur location object, it might be null.
#Override
public void onLocationChanged(Location location) {
// Add a marker in Sydney and move the camera
mLocation = location;
LatLng myLocation = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(myLocation)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.title("My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
Log.d("location", "Latitude:" + mLocation.getLatitude() + "\n" + "Longitude:" + mLocation.getLongitude());
}