用gps android获取我当前的位置

时间:2023-02-05 21:08:06

Hi I'm trying to get my location and use it to draw a path between my place and a specific location , I use GMapV2Direction class to draw the directions and this is my code

嗨,我正在尝试获取我的位置并使用它来绘制我的位置和特定位置之间的路径,我使用GMapV2Direction类来绘制方向,这是我的代码

public class MapsActivity extends FragmentActivity implements LocationListener {
GoogleMap mMap;
Location location;
String provider;
LocationManager service;
GMapV2Direction md;
private Boolean flag = false;
LatLng fromPosition ;
LatLng toPosition = new LatLng(35.407838, 8.112893);

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    flag = displayGpsStatus();
    if (!flag) {
        alertbox("Gps Status!!", "Your GPS is: OFF");
    }

    setContentView(R.layout.activity_maps);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    md = new GMapV2Direction();
    mMap = ((SupportMapFragment)getSupportFragmentManager()
            .findFragmentById(R.id.map)).getMap();

    service = (LocationManager)this.getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    provider = service.getBestProvider(criteria, true);
    location = service.getLastKnownLocation(provider);
    if (location != null){
        fromPosition = new LatLng(location.getLatitude(), location.getLongitude());
        DrawRoute();
    }
    else{
       ProgressDialog mProgressDialog = new ProgressDialog(MapsActivity.this);

        mProgressDialog.setTitle("Waiting");

        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);

       mProgressDialog.show();

    }
}
/*----Method to Check GPS is enable or disable ----- */
private Boolean displayGpsStatus() {
    ContentResolver contentResolver = getBaseContext()
            .getContentResolver();
    boolean gpsStatus = Settings.Secure
            .isLocationProviderEnabled(contentResolver,
                    LocationManager.GPS_PROVIDER);
    if (gpsStatus) {
        return true;

    } else {
        return false;
    }
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your Device's GPS is Disable")
            .setCancelable(false)
            .setTitle("** Gps Status **")
            .setPositiveButton("Gps On",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // finish the current activity
                            // AlertBoxAdvance.this.finish();
                            Intent myIntent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(myIntent);
                            dialog.cancel();
                        }
                    })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // cancel the dialog box
                            dialog.cancel();
                        }
                    });
    AlertDialog alert = builder.create();
    alert.show();
}
@Override
public void onLocationChanged(Location location) {
    double lng=location.getLongitude();
    double lat=location.getLatitude();
    fromPosition = new LatLng(lat,lng);
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

public void DrawRoute(){
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(fromPosition, 16));
    mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
    mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));
    Document doc = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING);
   /* int duration = md.getDurationValue(doc);
    String distance = md.getDistanceText(doc);
    String start_address = md.getStartAddress(doc);
    String copy_right = md.getCopyRights(doc);*/

    ArrayList<LatLng> directionPoint = md.getDirection(doc);
    PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);

    for(int i = 0 ; i < directionPoint.size() ; i++) {
        rectLine.add(directionPoint.get(i));
    }
    mMap.addPolyline(rectLine);
}

@Override
protected void onResume() {
    super.onResume();
    service.requestLocationUpdates(provider, 5000, 10, this);
}

}

But when I check location I found it alwaus = null can anyone help me to get my location

但当我检查位置时,我发现alwaus = null可以帮助我找到我的位置

1 个解决方案

#1


0  

Make a simple single location update like this

像这样做一个简单的单一位置更新

   locationManager.requestSingleUpdate(provider,locationListener,null);

Official Doc: LocationManager check more similar methods And

Enable this settings Settings -> Location and security -> Use Wireless network (Location determined by wifi and/or mobile network)

官方文档:LocationManager检查更多类似的方法并启用此设置设置 - >位置和安全 - >使用无线网络(位置由wifi和/或移动网络确定)

#1


0  

Make a simple single location update like this

像这样做一个简单的单一位置更新

   locationManager.requestSingleUpdate(provider,locationListener,null);

Official Doc: LocationManager check more similar methods And

Enable this settings Settings -> Location and security -> Use Wireless network (Location determined by wifi and/or mobile network)

官方文档:LocationManager检查更多类似的方法并启用此设置设置 - >位置和安全 - >使用无线网络(位置由wifi和/或移动网络确定)