【问题标题】:Get user location: Android获取用户位置:Android
【发布时间】:2016-04-05 17:58:10
【问题描述】:

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

请看下面的 .java 和 .xml 代码。

Java

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>

非常感谢

【问题讨论】:

  • 有很多潜在的问题。首先,您需要确保您在 Manifest 中有 ACCESS_COARSE_LOCATION 权限。其次,如果您在 Android API 23 上进行开发,则必须实现检查自我权限块,以便获得访问位置的权限。另请注意,如果 location 为空,则在声明“双纬度”和“双经度”时会出现异常。另外,GoogleMap.getMyLocation() 已弃用,参考developers.google.com/android/reference/com/google/android/gms/…

标签: java android xml android-layout location


【解决方案1】:

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

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



}

}

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2012-08-19
    • 1970-01-01
    • 2013-07-29
    • 2018-08-13
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多