Android 获取用户的当前位置
我需要在我的代码中做哪些更改,使其获取用户的当前位置,而不是预定义的纬度和经度 这是我的密码:Android 获取用户的当前位置,android,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.ma
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));
}
}
您需要做的第一个更改是设置您在此处发布的代码的格式。没有人喜欢读这个。试试上面的东西
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();
}