Android谷歌地图。在移动地图相机

时间:2017-02-28 07:07:02

标签: android google-maps-api-3 google-maps-android-api-2 mapactivity

我的应用程序中有以下代码(目的是拥有一个GoogleMaps片段):

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.HashMap;
import java.util.List;

public class MapsActivity extends Activity implements LocationListener {

private GoogleMap mMap;        

private static final LatLng position_gps = new LatLng([defined,position]);
int MY_PERMISSIONS_REQUEST_FINE_LOCATION;

private static final LatLng position_gps_track1 = new LatLng([something], [something]);

/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    LocationManager locationManager;

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                MY_PERMISSIONS_REQUEST_FINE_LOCATION);
        return;
    }
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(new Criteria(), true);
    Location location = locationManager.getLastKnownLocation(provider);
    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    if (mMap != null) {
        mMap.addMarker(new MarkerOptions().position(position_gps_track1).title("T1 - Thomas"));

        LatLng pos_gps;
        if (location == null) {    
            pos_gps = position_gps;     
        } else {                    
            pos_gps = new LatLng(location.getLatitude(), location.getLongitude());
        }
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos_gps, 15));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
        mMap.setMyLocationEnabled(true);                       
        mMap.getUiSettings().setCompassEnabled(true);          
        mMap.getUiSettings().setZoomControlsEnabled(true);    
    } else {
        Toast.makeText(this, "Services GoogleMap indisponibles!", Toast.LENGTH_SHORT).show();
    }

    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).addApi(LocationServices.API).build();


}

@Override
public void onLocationChanged(Location location) {

    int latitude = (int) (location.getLatitude());
    int longitude = (int) (location.getLongitude());
    LatLng position_gps = new LatLng(location.getLatitude(), location.getLongitude());
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position_gps, 15));
}


public Action getIndexApiAction() {
    Thing object = new Thing.Builder()
            .setName("Maps Page") // TODO: Define a title for the content shown.
            // TODO: Make sure this auto-generated URL is correct.
            .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
            .build();
    return new Action.Builder(Action.TYPE_VIEW)
            .setObject(object)
            .setActionStatus(Action.STATUS_TYPE_COMPLETED)
            .build();
}

@Override
public void onStart() {
    super.onStart();
    client.connect();
    AppIndex.AppIndexApi.start(client, getIndexApiAction());
}

@Override
public void onStop() {
    super.onStop();
    AppIndex.AppIndexApi.end(client, getIndexApiAction());
    client.disconnect();
}
}

我希望在活动开始时让地图关注当前位置,但是在方法onCreate()上,位置变量始终为null,并且地图关注于我定义的位置。

请问,如何确保在最终初始化位置时,地图会放大我当前的位置?

THX。

1 个答案:

答案 0 :(得分:2)

你需要使用:

你的onCreate()

中的

// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
        .findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

现在覆盖onMapReady()函数并使用以下代码:

    @Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMyLocationEnabled(true);
    mMap.addMarker(new MarkerOptions().position(position_gps_track1).title("T1 - Thomas"));

    LatLng pos_gps;
    if (location == null) {
        pos_gps = position_gps;
    } else {
        pos_gps = new LatLng(location.getLatitude(), location.getLongitude());
    }
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos_gps, 15));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
    mMap.getUiSettings().setCompassEnabled(true);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    }
你应该用XML格式

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

您的班级必须实施OnMapReadyCallback

public class MapsActivity extends Activity implements LocationListener ,OnMapReadyCallback { }