如何使地图视图从当前位置获取?

时间:2018-11-05 10:53:45

标签: java android android-studio android-mapview gmsmapview

作为标题,如何使地图视图缩放到当前位置?顺便说一句,我可以在getLocation()中获取当前的Log和Lon。只是不知道如何在地图中实现。在此先感谢可以帮助我的人。我是android studio的新手。这个问题已经让我感到困惑了。

package com.example.edward.neweventmanagementsystem;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Locale;

public class StaffAttendanceCheckIn extends AppCompatActivity  {

    private TextView mtxtTime, mtxtDate, txtDisplayName;
    private Spinner eventSpinner;

    private static final int REQUEST_LOCATION = 1;
    TextView textLocation;
    LocationManager locationManager;
    String latitude,longitude;
    MapView mapview;
    private GoogleMap map;



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

        mtxtDate = (TextView) findViewById(R.id.txtCurrentDate);
        mtxtTime = (TextView) findViewById(R.id.txtCurrentTime);
        txtDisplayName = (TextView) findViewById(R.id.txtDisplayName);
        eventSpinner = (Spinner) findViewById(R.id.eventSpinner);
        mapview = (MapView) findViewById(R.id.mapview);

        mapview.onCreate(savedInstanceState);

        SimpleDateFormat date = new SimpleDateFormat("EEEE dd MMM yyyy", Locale.ENGLISH);
        String currentDate = date.format(new Date());

        SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
        String currentTime = time.format(new Date());

        mtxtDate.setText(currentDate);
        mtxtTime.setText(currentTime);

        FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ;
        txtDisplayName.setText(currentFirebaseUser.getDisplayName());

        /**
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("EventName");

        System.out.println("Test Script: " + myRef); */

        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        textLocation = (TextView)findViewById(R.id.location);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            buildAlertMessageNoGps();

        } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            getLocation();
        }

    }

//    @Override
//    public void onClick(View view) {
//
//    }

    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                (com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        } else {
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);

            if (location != null) {
                double latti = location.getLatitude();
                double longi = location.getLongitude();

                latitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                textLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);

                float ZOOM_MAP = 17.0f;
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(latLng, ZOOM_MAP);
                map.animateCamera(myLocation);


//                CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(latLng, ZOOM_MAP);
//                System.out.println("Test Script" + myLocation);
//                map.animateCamera(myLocation);


            } else  if (location1 != null) {
                double latti = location1.getLatitude();
                double longi = location1.getLongitude();
                latitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                textLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);

            } else  if (location2 != null) {
                double latti = location2.getLatitude();
                double longi = location2.getLongitude();
                latitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                textLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);

            }else{

                Toast.makeText(this,"Unble to Trace your location",Toast.LENGTH_SHORT).show();

            }
        }
    }

    protected void buildAlertMessageNoGps() {

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Please Turn ON your GPS Connection")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        mapview.onDestroy();
    }

    @Override
    public void onLowMemory(){
        super.onLowMemory();
        mapview.onLowMemory();
    }

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

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapview.onSaveInstanceState(outState);
    }
}

1 个答案:

答案 0 :(得分:0)

您只需执行以下操作即可很容易:

CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(yourLatLng, ZOOM_MAP);
mMap.animateCamera(myLocation);

ZOOM_MAP其浮动

更新----

    mapview.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(yourLatLng, ZOOM_MAP);
                    googleMap.animateCamera(myLocation);
                }
            });
相关问题