java - 如何在开始时设置位置 - Google Maps API V2

标签 java android google-maps gps

嗨,目前,当我启动应用程序时,它会显示整个世界地图,当我按下 GPS 按钮时,它会放大到我当前的位置。我希望当 Activity 开始时它已经放大到您当前的位置。这是源代码:

public class MainActivity extends Activity {

    // Google Map
    private GoogleMap googleMap;

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

        try {
            // Loading map
            initilizeMap();

            // Changing map type
            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            // googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            // googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            // googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            // googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

            // Showing / hiding your current location
            googleMap.setMyLocationEnabled(true);

            // Enable / Disable zooming controls
            googleMap.getUiSettings().setZoomControlsEnabled(true);

            // Enable / Disable my location button
            googleMap.getUiSettings().setMyLocationButtonEnabled(true);

            // Enable / Disable Compass icon
            googleMap.getUiSettings().setCompassEnabled(true);

            // Enable / Disable Rotate gesture
            googleMap.getUiSettings().setRotateGesturesEnabled(true);

            // Enable / Disable zooming functionality
            googleMap.getUiSettings().setZoomGesturesEnabled(true);



        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        initilizeMap();
    }

    /**
     * function to load map If map is not created it will create it for you
     * */
    private void initilizeMap() {
        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }




}

最佳答案

您需要使用位置监听器获取当前位置并为其设置动画相机。

首先在您的 Activity 中实现 LocationListener,如下所示:

public class BasicMapActivity_new extends Activity implements LocationListener 

现在在您的Activity onCreate(....)

中实现以下代码
private LocationManager locationManager;
private String provider;

 LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    boolean enabledGPS = service
            .isProviderEnabled(LocationManager.GPS_PROVIDER);
    boolean enabledWiFi = service
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (!enabledGPS) {
        Toast.makeText(BasicMapActivity_new.this, "GPS signal not found", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }
    else if(!enabledWiFi){
           Toast.makeText(BasicMapActivity_new.this, "Network signal not found", Toast.LENGTH_LONG).show();
           Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
           startActivity(intent);
    }

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use
    // default
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    //getCurrentLocation();

    // Initialize the location fields
    if (location != null) {
       // Toast.makeText(BasicMapActivity_new.this, "Selected Provider " + provider,
                //Toast.LENGTH_SHORT).show();
        onLocationChanged(location);
    } else {

        //do something
    }
    initilizeMap();

现在实现onLocationChanged(.....)

        Marker startPerc=null;
    @Override
    public void onLocationChanged(Location location) {

        double lat =  location.getLatitude();
        double lng = location.getLongitude();

        LatLng coordinate = new LatLng(lat, lng);

        startPerc = mMap.addMarker(new MarkerOptions()
             .position(coordinate)
             .title("Current Location")
             .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));  

      mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 18.0f));

 }

并实现

@Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
  }

@Override
protected void onResume() {
    super.onResume();
     locationManager.requestLocationUpdates(provider, 400, 1, this);
    initilizeMap();
  }

并在您的 manifest.xml 文件中添加以下权限

  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

关于java - 如何在开始时设置位置 - Google Maps API V2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22673084/

相关文章:

java - "cast"ObservableList<Foo> 到 List<IFoo> 的干净解决方案?

java - 使用递归查找整数数组的平均值

java - 使用 Maven Relelase 插件准备发布阶段出错

android - Listview 未包装的弹出窗口

javascript - Html5 多点位置

java.lang.AbstractMethodError

android - 获取外部卡上的所有 MP3 文件

android - AndEngine - 播放声音时滞后

google-maps - 使用 `PolyUtil.encode()` 在 Google map 上保存重要的多边形是否安全?

java - 在桌面应用程序上使用 Google Maps API