【问题标题】:Android - Zoom to the user location and display the mapAndroid - 缩放到用户位置并显示地图
【发布时间】:2017-10-04 14:30:00
【问题描述】:

我是安卓的初学者。所以请帮忙!现在单击按钮,相机会缩放到用户位置,但我希望它在创建活动后缩放。并在用户移动时更改位置。

package com.example.mapdemo;

import android.Manifest;
import android.content.pm.PackageManager; 
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.MarkerOptions;



public class MyLocationDemoActivity extends AppCompatActivity
        implements
        OnMyLocationButtonClickListener,
        OnMapReadyCallback,
        ActivityCompat.OnRequestPermissionsResultCallback {
    double lat=0,lng=0;
    /**
     * Request code for location permission request.
     *
     * @see #onRequestPermissionsResult(int, String[], int[])
         */
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

    /**
 * Flag indicating whether a requested permission has been denied after returning in
 * {@link #onRequestPermissionsResult(int, String[], int[])}.
 */
private boolean mPermissionDenied = false;

private GoogleMap mMap;

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

    SupportMapFragment mapFragment =
            (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap map) {
    mMap = map;

    try {
        // Customise the styling of the base map using a JSON object defined
        // in a raw resource file.
        boolean success = mMap.setMapStyle(
                MapStyleOptions.loadRawResourceStyle(
                        this, R.raw.mapstyle_night));

        if (!success) {
            Log.e("MapsActivityRaw", "Style parsing failed.");
        }
    } catch (Resources.NotFoundException e) {
        Log.e("MapsActivityRaw", "Can't find style.", e);
    }
    //mMap.setOnMyLocationButtonClickListener(this);
    enableMyLocation();
    LatLng loc = new LatLng(lat, lng);
    mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}

/**
 * Enables the My Location layer if the fine location permission has been granted.
 */
private void enableMyLocation() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        // Permission to access the location is missing.
        PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                Manifest.permission.ACCESS_FINE_LOCATION, true);
    } else if (mMap != null) {
        // Access to the location has been granted to the app.
        mMap.setMyLocationEnabled(true);
    }
}

@Override
public boolean onMyLocationButtonClick() {
    Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
    // Return false so that we don't consume the event and the default behavior still occurs
    // (the camera animates to the user's current position).
    return false;
}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
        return;
    }

    if (PermissionUtils.isPermissionGranted(permissions, grantResults,
            Manifest.permission.ACCESS_FINE_LOCATION)) {
        // Enable the my location layer if the permission has been granted.
        enableMyLocation();
    } else {
        // Display the missing permission error dialog when the fragments resume.
        mPermissionDenied = true;
    }
}

@Override
protected void onResumeFragments() {
    super.onResumeFragments();
    if (mPermissionDenied) {
        // Permission was not granted, display error dialog.
        showMissingPermissionError();
        mPermissionDenied = false;
    }
}

/**
 * Displays a dialog with error message explaining that the location permission is missing.
 */
private void showMissingPermissionError() {
    PermissionUtils.PermissionDeniedDialog
            .newInstance(true).show(getSupportFragmentManager(), "dialog");
}

}

【问题讨论】:

    标签: java android google-maps android-studio


    【解决方案1】:

    您也可以像这样使用 xml 属性设置缩放:

        <fragment xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:map="http://schemas.android.com/apk/res-auto"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            map:cameraZoom="13"
            map:mapType="normal"
            map:uiCompass="true"
            map:uiRotateGestures="true"
            map:uiScrollGestures="false"
            map:uiTiltGestures="true"
            map:uiZoomControls="false"
            map:uiZoomGestures="true"/>
    

    【讨论】:

    • 成功了。比起修改代码,我更喜欢使用 xml!!
    【解决方案2】:

    使用以下链接获取您当前的位置:

    http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

    现在,当您获得当前的纬度和经度时,使用以下线条缩放到您当前的位置:

     mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),16));
     mMap.getUiSettings().setZoomControlsEnabled(true); 
    

    之后使用地图的 setOnMyLocationChangeListener() 方法在用户移动时更改标记。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多