【问题标题】:How to retrieve current device location & show it on map fragment in a fragment如何检索当前设备位置并将其显示在片段中的地图片段上
【发布时间】:2013-08-30 12:09:21
【问题描述】:

我正在使用谷歌地图开发一个安卓应用程序。目前我可以在我的应用程序中查看地图,但我不知道如何在应用程序上查看当前位置。

这是我的代码:

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。请有人帮忙。

【问题讨论】:

  • 我们需要你的谷歌地图代码!!你从哪里得到地图来管理它?你应该使用 SupportMapFragment,使用 support lib v4 !!
  • @Yume117:检查我的xml代码出错了
  • 使用 SupportMapFragment 或 Fragment Map 代替 MapView :)
  • 所以你使用 Google map api v1 吗?因为不再推荐这种显示地图的方法:/
  • 那么我如何在类类型片段中实现它?

标签: android google-maps android-layout android-mapview google-maps-android-api-2


【解决方案1】:

如何使用新推出的融合位置提供程序 引用自: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

  1. 通过关注这篇文章,在您的项目中获取 Play 服务 https://blog-emildesign.rhcloud.com/?p=435

  2. 然后获取一个api密钥:https://blog-emildesign.rhcloud.com/?p=403

  3. 将权限添加到您的清单中,

       <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" />
    
  4. 要测试地图应用,你需要有一个真实的设备,如果没有,则通过 adb 将播放服务推送到模拟器,阅读这篇文章以了解如何通过 adb 安装播放服务https://stackoverflow.com/a/13869332/826657

  5. 完成上述所有步骤后,清理您的项目,从模拟器中卸载之前的 .apk,然后运行该项目。

【讨论】:

  • 能否请您也提供您的xml。
  • 在 getSupportFragmentManager() 获得红旗'方法 getSupportFragmentManager() 未定义类型 Activity'
  • 我编辑了代码,尝试使用getFragmentManager(),更改所有SupportMapFragment to MapFragment,在你的xml中也将它从SupportMapFragment更改为MapFragment
  • 抱歉回复晚了。但是当我运行它并在我的 LogCat 中出现空白屏幕时:09-01 13:01:02.760: E/GooglePlayServicesUtil(12622): 找不到 Google Play 服务资源。检查您的项目配置以确保包含资源。但我在清单中添加了所有必需的权限。
  • 感谢您的回答,我按照您所说的所有步骤在真实设备上进行了测试。但仍然是相同的结果,上面的代码(由我发布)正确显示了地图。我认为应该还有一些其他的问题。需要更多帮助。
【解决方案2】:

您可以启用您的位置,只需在您的课程中添加此代码

 GoogleMap.setMyLocationEnabled(true);

【讨论】:

    【解决方案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);
    

    希望这会对你有所帮助。

    【讨论】:

      【解决方案4】:

      你应该像这样初始化你的 Map v2:

      m = (MapView) v.findViewById(R.id.map);
      GoogleMap mMap = m.getMap();
      

      现在你可以使用mMap.setMyLocationEnabled(true);

      【讨论】:

      • 试过但强制关闭。 CatLog: 08-30 13:26:48.635: D/AndroidRuntime(11455): 关闭 VM 08-30 13:26:48.635: W/dalvikvm(11455): threadid=1: 线程退出未捕获异常 (group=0x4164a2a0 ) 08-30 13:26:48.635: E/AndroidRuntime(11455): 致命异常: main 08-30 13:26:48.635: E/AndroidRuntime(11455): java.lang.ClassCastException: android.widget.FrameLayout 不能转换为 com.google.android.gms.maps.MapView
      【解决方案5】:
      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;
          }
      
      }
      

      【讨论】:

      • 这些是常量变量,您可以根据自己的要求采用。
      • mapView.moveCamera(CameraUpdateFactory.newLatLngZoom(new tLng(latitude, longitude), 0));
      猜你喜欢
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多