获取用户位置:Android

时间:2016-04-05 17:58:10

标签: java android xml android-layout location

所以我在互联网上搜索了许多不同的解决方案,让我的Android手机通过Google Maps API使用播放服务显示当前位置。我相信我有正确的设置,但有些事情是不对的。

请参阅下面的.java和.xml代码。

爪哇

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    private UiSettings mUiSettings;

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

        android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
        SupportMapFragment mySupportMapFragment
                = (SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
    }

    private void centerMapOnMyLocation() {
        mMap.setMyLocationEnabled(true);

        // Get LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Create a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Get the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        Location location = mMap.getMyLocation();

        // Getting latitude
        double latitude = location.getLatitude();

        // Getting longitude
        double longitude = location.getLongitude();

        LatLng latlng;

        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    public void requestPermissions(@NonNull String[] permissions, int requestCode)
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return;
        }
        Location myLocation = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            //Create a LatLng object for the current location
            latlng = new LatLng(latitude, longitude);
        } else {
            locationManager.requestLocationUpdates(provider, 20000, 0, (LocationListener) this);
        }

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                .zoom(17)                   // Sets the zoom
                .bearing(90)                // Sets the orientation of the camera to east
                .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                .build();                   // Creates a CameraPosition from the builder
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }
}

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/map"
    tools:context="example.navigationapplication_10.MapsActivity"
    android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

非常感谢

1 个答案:

答案 0 :(得分:2)

尝试使用此课程获取纬度和经度..

import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;

public class GPSTracker extends Service implements LocationListener {


private Context context;

boolean isGPSEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;

Location location;

double latitude;
double longitude;

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10;
private static final long MIN_TIME_BW_UPDATES=1000*60*1;

protected LocationManager locationManager;

public GPSTracker(Context context)
{
    this.context=context;
getLocation();
}

public Location getLocation()
{
    try{
    locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
    isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);




    if(!isGPSEnabled && !isNetworkEnabled)
    {
        showSettingsAlert();
    }
    else{
        this.canGetLocation=true;
        if(isNetworkEnabled)
        {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);


        if(locationManager !=null)
        {
            location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        if(location !=null)
        {
            latitude=location.getLatitude();
            longitude=location.getLongitude();
        }
        }
        }

        if(isGPSEnabled){
            if(location==null)
            {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                if(locationManager !=null)
                {
                    location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                    if(location !=null)
                    {
                        latitude=location.getLatitude();
                        longitude=location.getLongitude();
                    }   

                }

            }
        }


    }


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

public void stopUsingGPS()
{
    if(locationManager !=null)
    {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

public double getLatitude()
{
    if(location!=null)
    {
        latitude=location.getLatitude();
    }
    return latitude;

}


public double getLongitude()
{
    if(location!=null)
    {
        longitude=location.getLongitude();
    }
    return longitude;

}

public boolean canGetLocation(){

return this.canGetLocation;

}

public void showSettingsAlert(){
    Builder alertDialog=new Builder(context);
    alertDialog.setTitle("GPS Settings");
    alertDialog.setMessage("GPS is not enabled.Do you want to go to the settings menu?");
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            context.startActivity(intent);
        }
    }); 

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();

        }
    });
    alertDialog.show();
}


@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}


}

用于在地图中标记您的位置

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
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.MarkerOptions;

 public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // 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);
}



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



    try {

        gps = new GPSTracker(MapsActivity.this);

        if (gps.canGetLocation) {
            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();
            LatLng sydney = new LatLng(latitude, longitude);
            mMap.addMarker(new MarkerOptions().position(sydney).title("I am here"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);

            for(int i=0;i<MainActivity.nameArray.length;i++)
            {
                latitude=Double.parseDouble(MainActivity.latArray[i]);
                longitude=Double.parseDouble(MainActivity.lonArray[i]);
                LatLng shops = new LatLng(latitude, longitude);
                mMap.addMarker(new MarkerOptions().position(shops).title(MainActivity.nameArray[i]));

            }





        } else {
            gps.showSettingsAlert();
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



}

}

希望这有助于