簡體   English   中英

Android-縮放到用戶位置並顯示地圖

[英]Android - Zoom to the user location and display the map

我是android的初學者。 所以請幫忙! 現在只要單擊一個按鈕,相機就會縮放到用戶位置,但是一旦創建活動,我希望它縮放。 並在用戶移動時更改位置。

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");
}

}

您也可以使用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"/>

使用以下鏈接獲取您的當前位置:

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

現在,當您獲得當前的緯度和經度時,請使用以下幾行縮放至當前位置:

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

之后,使用map的setOnMyLocationChangeListener()方法在用戶移動時更改標記。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM