我正在使用谷歌地图开发一个Android应用程序。目前,我可以在我的应用内查看地图,但我不知道如何查看应用中的当前位置。
这是我的代码:
public class MapsFragment extends Fragment{
MapView m;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.map_near_me, container, false);
m = (MapView) v.findViewById(R.id.map);
m.onCreate(savedInstanceState);
return v;
}
}
编辑: 和xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.google.android.gms.maps.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map" />
</LinearLayout>
这段代码工作正常,我知道'setmylocationenabled'可以帮助在FragmentActivity中启用,但不幸的是我必须将类型用作'Fragment'。我正在使用谷歌api v2。请有人帮忙解决这个问题。
答案 0 :(得分:9)
如何使用新推出的融合位置提供商 引自:http://developer.android.com/training/location/retrieve-current.html
public static class XYZ extends Fragment
implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
GoogleMap map;
LatLng latlng;
private LocationRequest lr;
private LocationClient lc;
MapFragment mapFragment;
ImageView iv;
private static View view;
public XYZ() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.XYZ, container,
false);
mapFragment = ((MapFragment) this.getActivity()
.getFragmentManager().findFragmentById(R.id.map));
iv = (ImageView) view.findViewById(R.id.iv);
map = mapFragment.getMap();
map.getUiSettings().setAllGesturesEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(false);
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
Toast.makeText(getActivity(), "Google Play Services missing !",
Toast.LENGTH_LONG).show();
} catch (InflateException e) {
Toast.makeText(getActivity(), "Problems inflating the view !",
Toast.LENGTH_LONG).show();
} catch (NullPointerException e) {
Toast.makeText(getActivity(), "Google Play Services missing !",
Toast.LENGTH_LONG).show();
}
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lr = LocationRequest.create();
lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
lc = new LocationClient(this.getActivity().getApplicationContext(),
this, this);
lc.connect();
}
@Override
public void onLocationChanged(Location l2) {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
new LatLng(l2.getLatitude(), l2.getLongitude()), 15);
map.animateCamera(cameraUpdate);
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
}
@Override
public void onConnected(Bundle connectionHint) {
lc.requestLocationUpdates(lr, this);
}
@Override
public void onDisconnected() {
}
}
使用XML作为:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="4dp"
android:layout_weight="1" >
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent" />
</RelativeLayout>
如果您没有所有要求,可能会出现空白地图 https://developers.google.com/maps/documentation/android/start
按照这篇文章获取项目的Play服务 https://blog-emildesign.rhcloud.com/?p=435
向您的清单添加权限
<uses-permission android:name="your.application.package.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
要测试地图应用程序,您需要拥有真实设备,如果没有,请通过adb将播放服务推送到模拟器,阅读此文章以了解如何通过adb https://stackoverflow.com/a/13869332/826657安装播放服务
完成上述所有步骤后,清理项目,从模拟器中卸载以前的.apk,然后运行项目。
答案 1 :(得分:7)
您可以启用您的位置,只需在您的课程中添加此代码
GoogleMap.setMyLocationEnabled(true);
答案 2 :(得分:3)
以下链接解释了您需要的所有内容
https://developers.google.com/maps/documentation/android/map
要在地图上设置位置,您需要使用以下类
LatLong objLatLng=new LatLong(lat,longi);
yourMapObject.moveCamera(CameraUpdateFactory.newLatLngZoom(objLatLng, 20));
yourMapObject.animateCamera(CameraUpdateFactory.zoomTo(18), 2000, null);
希望这会对你有所帮助。
答案 3 :(得分:2)
你应该像这样初始化你的Map v2:
m = (MapView) v.findViewById(R.id.map);
GoogleMap mMap = m.getMap();
现在您可以使用mMap.setMyLocationEnabled(true);
答案 4 :(得分:0)
Use LocationListener:
GPSTracker objGPSTracker = new GPSTracker(mContext);
objGPSTracker.stopUsingGPS();
objGPSTracker.getLocation();
这是GPSTracker的课程
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
//
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 50; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
//getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Constant.mLocation = location;
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Constant.mLocation = location;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public void onLocationChanged(Location location) {
Constant.mLocation = location;
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}