I'm creating an app where the user needs to see his/her geo location with getMyLocation(), but this is returning null. Is there any solution for this, because I did read that the getMyLocation() method is always returning null. I'm new to Google Maps, so any help will be appreciated!
Code:
GoogleMap map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
Location myLocation = map.getMyLocation();
if( myLocation != null ){
helper.showToast( "Latitude: " + myLocation.getLatitude() + "\nLongitude: " + myLocation.getLongitude() );
}
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();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
}
});
}
}
}
call this function in on create function
I don't like new google maps API because of their limited and defects. In your case I think the best way is to use LocationManager and LocationListener classes. You'll get location, when your phone will find satellites and then you can add the marker on the map. Also you can use getLastKnownLocation() method if you need to get location quickly. I think google maps getMyLocation()
method return null because the phone don't have much time to know it's location, when app starts up. And in Google Maps API v2 there is no some kind of onLocationChanged()
method. I don't like this API.
I have done this way:
private GoogleMap mGoogleMap;
private SupportMapFragment mMapFragment;
on onCreate():
mMapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
mGoogleMap = mMapFragment.getMap();
mGoogleMap.setOnMyLocationChangeListener(myLocationChangeListener);
Now add MyLocationChangeListener:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
Log.i(TAG, "Latitude: "+String.valueOf(location.getLatitude())+" - Longitude: "+String.valueOf(location.getLongitude()));
}
};
Hope this will help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With