获取用户的当前位置

时间:2017-07-04 12:54:56

标签: android

我需要在代码中进行哪些更改才能获取用户的当前位置而不是预定义的纬度和经度?

这是我的代码:

package com.example.safwan.mypersonal;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
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;

    @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;
        // Add a marker in Sydney and move the camera
        LatLng cannaughtplace = new LatLng(28.6315,77.2167);
        mMap.addMarker(new MarkerOptions()
            .position(cannaughtplace)
            .title("Marker in Cannught place"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(cannaughtplace));
    }
}

1 个答案:

答案 0 :(得分:0)

  locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    try {
        location = locationManager.getLastKnownLocation(provider);
    }
    catch (Exception e)
    {

    }
    if(location==null) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    if (location != null) {
        double lat = location.getLatitude();
        double longg = location.getLongitude();
        mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(lat,longg) , 14.0f) );
        startService(new Intent(MainActivity.this, MyService.class));
        ismarkervisible = true;
    } else {
        Toast.makeText(MainActivity.this, "Device Failed To Fetch Lat Long", Toast.LENGTH_LONG).show();
    }