0

I am having some prolems with my google maps app. For now the app was only suppost to get my location em zoom in it, but is not working. My location aways ends in the top of the map. Here is my code: MainActivity:

public class MainActivity extends Activity implements LocationListener {

private GoogleMap googleMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (isGooglePlayOk()) {

        setContentView(R.layout.activity_main);
        setMap();
        googleMap.setMyLocationEnabled(true);


    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    switch (item.getItemId()) {
    case R.id.action_legalnotices:
        startActivity(new Intent(this, LegalNoticeActivity.class));
        return true;

    default:
        return false;
    }
}

private boolean isGooglePlayOk() {
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

    if (status == ConnectionResult.SUCCESS) {
        return (true);
    }

    else {
        ((Dialog) GooglePlayServicesUtil.getErrorDialog(status, this, 10))
                .show();

    }
    return (false);

}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setMap() {

    if (googleMap == null) {

        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.main.map)).getMap();
        if (googleMap != null) {

        }

        googleMap.setMyLocationEnabled(true);
        LocationManager la = (LocationManager) getSystemService(LOCATION_SERVICE);

        String provider = la.getBestProvider(new Criteria(), true);
        Location loc = la.getLastKnownLocation(provider);
        if (provider != null) {
            onLocationChanged(loc);

        }

        googleMap.setOnMapLongClickListener(onLongClickMapSettiins());

    }
}

private OnMapLongClickListener onLongClickMapSettiins() {
    // TODO Auto-generated method stub

    return new OnMapLongClickListener() {

        @Override
        public void onMapLongClick(LatLng point) {
            Toast.makeText(getApplicationContext(), "OK",
                    Toast.LENGTH_SHORT).show();

        }
    };
}

@Override
public void onLocationChanged(Location location) {

    LatLng latlong = new LatLng(location.getLatitude(),
            location.getLongitude());

    googleMap.setMyLocationEnabled(true);

    CameraPosition cp = new CameraPosition.Builder().target(latlong)
            .zoom(15).build();

    googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cp));

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}
 }

activity_main:

    <?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+main/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"/>

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mapateste"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />
    <!--
     The following two permissions are not required to use
     Google Maps Android API v2, but are recommended.
    -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="(My Api is working fine)" />

        <activity
            android:name="com.example.mapateste.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.mapateste.LegalNoticeActivity"
            android:label="@string/title_activity_legal_notice" >
        </activity>
    </application>

I can only test in my device. The map is working fine but i cannot get my position on the center of the screen right away only clicking at the mylocationbutton. Somebody can help me?

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
Lucas Legey
  • 1
  • 1
  • 1

8 Answers8

2

Just declare a point where you want to center your point.

  LatLng cur_Latlng = new LatLng(21.0000, 78.0000);
  gm.moveCamera(CameraUpdateFactory.newLatLng(cur_Latlng));
  gm.animateCamera(CameraUpdateFactory.zoomTo(4));

the desired zoom level is in the range of 2.0 to 21.0.

GrIsHu
  • 29,068
  • 10
  • 64
  • 102
Shadow
  • 6,864
  • 6
  • 44
  • 93
1

Your min sdk is 8. You should use SupportMapFragment. Your class must extend FragmentActivtiy

Check the line above developers guide heading in the below link

https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/MapFragment

<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/map"  
android:layout_width="match_parent"
android:layout_height="match_parent"/>

Use SupportMapFragment

SupportMapFragment fm = (SupportMapFragment)  getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap mMap = fm.getMap(); 

Make sure you have added support library

Also make sure you imported the below

import android.support.v4.app.FragmentActivity;  
import com.google.android.gms.maps.SupportMapFragment

To zoom

 CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latlong,20);
 googleMap.moveCamera(update);
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Ok, now im using MapFragment. But still not working. He set the position way bellow the right location. – Lucas Legey Sep 19 '13 at 16:46
  • @LucasLegey may be this can help http://stackoverflow.com/questions/15625970/offseting-the-center-of-the-mapfragment-for-an-animation-moving-both-the-target and if your min sdk is 11 and below use SupportMapFragment – Raghunandan Sep 19 '13 at 16:55
1
// try this
@Override
public void onLocationChanged(Location location) {

        LatLng latlong = new LatLng(location.getLatitude(),
                location.getLongitude());

        googleMap.animateCamera(CameraUpdateFactory.newLatLng(latlong));
        googleMap.animateCamera(CameraUpdateFactory.zoomBy(15));

}
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
1

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));
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Shreyans Patel
  • 129
  • 1
  • 10
1

Note that the My Location layer does not return any data. If you wish to access location data programmatically, use the Location API.

In your MainActivity (onCreate Method)

mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(MainActivity.this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

On method onMapReady

@Override
public void onMapReady(GoogleMap googleMap) {

    GoogleMap mMap = googleMap;
    // Set blue point on the map at your cuurent location
    mMap.setMyLocationEnabled(true);
    // Show zoon controls on the map layer
    mMap.getUiSettings().setZoomControlsEnabled(true);
    //Show My Location Button on the map
    mMap.getUiSettings().setMyLocationButtonEnabled(true);
}

on method onConnected

@Override
public void onConnected(Bundle bundle) {

    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) {
        LocationListener.latlonInit= new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude());
        CameraPosition target = CameraPosition.builder().tilt(66.0f).target(LocationListener.latlonInit)
                .zoom(MainActivity.ZOOM).build();
        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(target));
    }
}
SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
0

If you want to automatically zoom to some point in google maps v2 u can do like this

private float previousZoomLevel = 13.00f;
LatLng zoomPoint = new LatLng(12.977286, 77.632720);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(zoomPoint,previousZoomLevel));

here previousZoomLevel is level of zoom

NARESH REDDY
  • 682
  • 4
  • 11
0

You class should extend Fragment Activity

public class MainActivity extends FragmentActivity {
//assign any arbitrary value to GPS_ERRODIALOG_REQUEST
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap googlemap;

}

for Google Service Ok method I would do Following:

public boolean isGooglePlayOk(){
    int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

    if (isAvailable == ConnectionResult.SUCCESS) {
        return true;
    }
    else if(GooglePlayServicesUtil.isUserRecoverableError(isAvailable)){
    Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
    dialog.show();

}
else {
    Toast.makeText(this, "Can't connect to Goolge Play", Toast.LENGTH_SHORT).show();
}
return false;

}

In the .xml file, when you declare the fragment, you need to support Map Fragment since your min skd is 8:

<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:maps="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
score
  • 521
  • 1
  • 8
  • 22
0

activity_map.xml is for displaying map if condition is true for setMap else go to you regular activity_main.xml.

public class MainActivity extends FragmentActivity {
    GoogleMap mMap;


if (isGooglePlayOk()) {

        setContentView(R.layout.activity_map);

        if (setMap()) {
            mMap.setMyLocationEnabled(true);
        }
        else {
            //your code
        }
    }
    else {
        setContentView(R.layout.activity_main);
    }

method for setMap:

private boolean setMap() {
    if (mMap == null) {
        SupportMapFragment mapFrag =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mMap = mapFrag.getMap();
    }
    return (mMap != null);
}
score
  • 521
  • 1
  • 8
  • 22