谷歌地图v2中心mylocation

时间:2013-09-19 04:34:13

标签: android google-maps mylocationoverlay

我在谷歌地图应用程序中遇到了一些问题。现在,应用程序只能让我的位置放大,但不起作用。我的位置在地图的顶部结束。这是我的代码: 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"/>

清单:

<?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>

我只能在我的设备上测试。地图工作正常,但我不能立即在屏幕中心位置,只需点击mylocationbutton。有人可以帮帮我吗?

8 个答案:

答案 0 :(得分:2)

只需声明您想要集中点的点。

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

所需的缩放级别在2.0到21.0的范围内。

答案 1 :(得分:1)

你的min sdk是8.你应该使用SupportMapFragment。您的课程必须延长FragmentActivtiy

检查以上链接

中开发人员指南标题上方的行

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"/>

使用SupportMapFragment

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

确保您已添加支持库

同时确保导入以下内容

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

缩放

 CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latlong,20);
 googleMap.moveCamera(update);

答案 2 :(得分: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));

}

答案 3 :(得分:1)

这是适用于Google Map V2缩放的当前位置

 double lat= location.getLatitude();
 double lng = location.getLongitude();
 LatLng ll = new LatLng(lat, lng);
 googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));

答案 4 :(得分:1)

请注意,“我的位置”图层不会返回任何数据。如果您希望以编程方式访问位置数据,请使用Location API。

在您的MainActivity(onCreate方法)

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

关于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);
}
关于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));
    }
}

答案 5 :(得分:0)

如果你想在google maps v2中自动缩放到某个点,你可以这样做

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

这里previousZoomLevel是缩放级别

答案 6 :(得分:0)

您的课程应该扩展片段活动

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

}

对于Google Service Ok方法我会这样做:

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;

}

在.xml文件中,当你声明片段时,你需要支持Map Fragment,因为你的min skd是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" />

答案 7 :(得分:0)

activity_map.xml用于显示map,如果condition为true,则返回常规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);
    }

setMap的方法:

private boolean setMap() {
    if (mMap == null) {
        SupportMapFragment mapFrag =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mMap = mapFrag.getMap();
    }
    return (mMap != null);
}
相关问题