Search code examples
androidlocationgoogle-maps-api-2

Google Map Not Showing (Zoom to) Current Location After Set Latitude and Longitude manually


I want to show my current location using custom Latitude and Longitude, I have set latitude and longitude in Location object like this :

Location location = new Location ("");
location.setLatitude(lat);
location.setLongitude(lon);

After that I call onLocationChanged(location) method, where the method is like this :

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

    mLatitude = location.getLatitude();
    mLongitude = location.getLongitude();
    LatLng latLng0 = new LatLng(mLatitude, mLongitude);

    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng0));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));

}

The map was show, but not showing my current location with blue dot like usual, anybody can help ?


Solution

  • You can try to run your code in GoogleMap.OnMapLoadedCallback Likes:

    mGoogleMap.setOnMapLoadedCallback(new OnMapLoadedCallback(){
      @Override
      public void onMapLoaded() {
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng0));
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
      }
    });
    

    Update:

    mGoogleMap.setOnMapLoadedCallback(new OnMapLoadedCallback(){
          @Override
          public void onMapLoaded() {
            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng0,12));
          }
        });
    

    Using

    mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng0,12));
    

    Instead of

    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng0));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
    

    Because the code CameraUpdateFactory.zoomTo(12) is not set Latitude and Longitude, so the values will be inited with [0,0]. That's will let your map center to [0,0]