Search code examples
androidgoogle-mapsgoogle-maps-api-2

Move Map in Android V2


I have implemented Google maps v2 for Android app. My location, marker everything is showing fine, but when I am on move OnMylocationChange is called and marker is updated, but I have to scroll up or down as the view of my location goes off the map.

How do I update my map to scroll with my current location? Like Google Maps App.

@Override
public void onMyLocationChange(Location location) 
{

    if (markermylocation != null)
    {
        markermylocation.remove();
    }

    curlat = location.getLatitude();
    curlong = location.getLongitude();

    myLocation(curlat, curlong, username, imageURL, ZOOMVALUE);
}


private void myLocation(double lat, double lng, String name, String url, float zoom)
{
    if(firsttime  == 1)
    {
        LatLng ll = new LatLng(lat,lng);
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
        googleMap.animateCamera(update);
        firsttime = 0;
    }

    final String uname = name; 
    curlat = lat;
    curlong = lng;

    Picasso.with(getActivity()).load(url).resize(120, 120).transform(transformation).into(new Target() 
    {
        @Override
        public void onBitmapFailed(Drawable arg0) 
        {
            markerOptionsmylocaiton = new MarkerOptions().position(new LatLng(curlat, curlong)).icon(BitmapDescriptorFactory.fromResource(R.drawable.profilepic)).title(uname).anchor(0.5f, 1f);
            markermylocation = googleMap.addMarker(markerOptionsmylocaiton);          
        }

        @Override
        public void onBitmapLoaded(Bitmap b, LoadedFrom arg1) 
        {

            bitmapMarkermylocation = BitmapDescriptorFactory.fromBitmap(b);

            if(b != null)
            {
                markerOptionsmylocaiton = new MarkerOptions().position(new LatLng(curlat, curlong)).icon(bitmapMarkermylocation).title(uname).anchor(0.5f, 1f);
            }
            else
            {
                markerOptionsmylocaiton = new MarkerOptions().position(new LatLng(curlat, curlong)).icon(BitmapDescriptorFactory.fromResource(R.drawable.profilepic)).title(uname).anchor(0.5f, 1f);
            }

            markermylocation = googleMap.addMarker(markerOptionsmylocaiton);       
        }

        @Override
        public void onPrepareLoad(Drawable arg0) 
        {

        }
    });
    }

Thanks!


Solution

  • I think you just have to remove the if (firsttime == 1) conditional, then the map should recenter whenever your location is updated.

        LatLng ll = new LatLng(lat,lng);
        CameraUpdate update = null;
    
        if(firsttime  == 1) {
            update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
            firsttime = 0;
        } else {
            update = CameraUpdateFactory.newLatLng(ll);
        }
        googleMap.animateCamera(update);
    

    is there a reason you have that in there?