Android google maps location manager not working in SupportMapFragment - android

I'm currently trying to include the google maps into my app. The main aim is to move the camera automatically to the current location of the device with a zoom after the map was loaded.
For this I need a location manager. In the below code I'm trying to implement one, but without success. I also tried to pass the context from a fragment class.
But still I'm getting this message from eclipse: The method getSystemService(String) is undefined for the type Navigation
Any ideas what I'm doing wrong?
public class Navigation extends SupportMapFragment {
private GoogleMap map;
private Context mContext;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.activity_navigation, null, false);
getContextFromConfig();
setUpMapIfNeeded();
return v;
}
private void getContextFromConfig()
{
ContextConfig config = new ContextConfig();
mContext = config.getContext();
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null) {
map = ((SupportMapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
} else {
System.out.println("Google Maps is not available.");
}
if (map != null) {
setUpMap();
}
}
private void setUpMap() {
map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("snippet"));
// Enable MyLocation Layer of Google Map
map.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
map.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);
// Show the current location in Google Map
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(14));
map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));
}
}

getSystemService() is a method of Context, not of Fragment. You probably want to do this:
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
or this:
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

Related

I can't get the location from locationlistener

I used a Fragment implements LocationListener and i tried to get my current location , but i can't get it successfully. Do i miss something ?
public class TrafficInformation extends Fragment implements LocationListener{
private MapView mapView;
private GoogleMap googleMap;
private double myLatitude,myLongitude;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.traffic_information_fragment, container, false);
mapView = (MapView) view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
//part of android 6.0 permission
int flag = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION);
if (flag != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
} else {
googleMap.setMyLocationEnabled(true);
}
// For dropping a marker at a point on the Map
//i set my current location over here-------------------
LatLng sydney = new LatLng(myLatitude, myLongitude);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
//For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(16).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return view;
}
i try to get it from this function:
#Override
public void onLocationChanged(Location location) {
myLatitude=location.getLatitude();
myLongitude=location.getLongitude();
}
i can't get myLatitude and myLongitude location , why?
any help would be grateful.
You are not calling
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this)
You are only calling
googleMap.setMyLocationEnabled(true);
This don't request for location updates... just set a pin on your position on the map.
Check here to see how to request current location:
https://developer.android.com/training/location/receive-location-updates.html

How to get current location when app launch?

In this case the map appears on the application that I'm trying to make, but when the application is opened folder appears not in the current location but in Sout Atlantic Ocean. Is there a way to bring up the current location at the time the application is opened?
Here is my code :
public class GmapFragment extends Fragment implements OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback,
LocationListener
{
GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
double longitude;
double latitude;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_gmaps, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MapFragment fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
fragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LocationManager locManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location location;
if(network_enabled){
location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
longitude = location.getLongitude();
latitude = location.getLatitude();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(-7.0559935,110.4320226))
.title("Kos Munyiq"));
mMap.addMarker(new MarkerOptions()
.position(new LatLng(-7.0500666,110.4264657))
.title("Kos Pos"));
mMap.animateCamera(CameraUpdateFactory.zoomTo(0));
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMapToolbarEnabled(false);
}
}
}
#Override
public void onLocationChanged(Location location) {
}
}
Sorry if there is something wrong with my question.
You are adding marker in someplace. Try use the following code instead of those markers..
mMap.setMyLocationEnabled(true); <<this is the main line
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
}
});
The on location change functionality will give you your position even if you change your location... If you just need your current position, static, you will just need the following code,
mMap.setMyLocationEnabled(true);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude,longitude))
.title("It's Me!"));
Then you will want to animate the camera, zoom in/zoom out a little bit.
Hope it helps. Cheers!

How to addMarker directly on GoogleMap after click button setMyLocationEnabled?

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

How can I fetch google map with current location?

I tried to fetch a google map with current location but I got this error
FATAL EXCEPTION: main java.lang.NullPointerException
in
map= ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
java code
public class MapFragment extends Fragment{
private TextView locationText;
private TextView addressText;
private GoogleMap map;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_map, container, false);
locationText = (TextView) rootview.findViewById(R.id.location);
addressText = (TextView) rootview.findViewById(R.id.address);
//replace GOOGLE MAP fragment in this Activity
return rootview;
}
public void onMapReady(GoogleMap map) {
//make the call here. it will be called once the map is ready
replaceMapFragment();
}
private void replaceMapFragment() {
map= ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Enable Zoom
map.getUiSettings().setZoomGesturesEnabled(true);
//set Map TYPE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//enable Current location Button
map.setMyLocationEnabled(true);
//set "listener" for changing my location
map.setOnMyLocationChangeListener(myLocationChangeListener());
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
return new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Marker marker;
marker = map.addMarker(new MarkerOptions().position(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");
//get current address by invoke an AsyncTask object
//new GetAddressTask(getActivity()).execute(String.valueOf(latitude), String.valueOf(longitude));
}
};
}
}
This may happened because the map is not ready at the moment.
#Override
public void onMapReady(GoogleMap googleMap) {
//make the call here. it will be called once the map is ready
replaceMapFragment();
}
In response to your comment on Kasun's answer, to display the current location marker on the map, call:
googleMap.setMyLocationEnabled(true);
Edit
import com.google.android.gms.maps.SupportMapFragment;
public class MapFragment extends SupportMapFragment
implements OnMapReadyCallback {
#Override
public void onCreate(Bundle inState) {
super.onCreate(inState);
// start a task for connecting to the map
// onMapReady() will be called when it is complete
getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap
// Enable Zoom
map.getUiSettings().setZoomGesturesEnabled(true);
//set Map TYPE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//enable Current location Button
map.setMyLocationEnabled(true);
//set "listener" for changing my location
map.setOnMyLocationChangeListener(myLocationChangeListener());
}
}

How to get the location(LatLng/Name) in a google map at the centre of map

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

Categories

Resources