2016-03-07 36 views
0

您好我想获取位置(经度和纬度)从Gps和谷歌地图上设置标记,但它不工作。在此代码中,我试图获得纬度和来自GPS位置监听器方法onLocationChanged的经度,但此方法从不调用不显示任何吐司。获取位置形式的GPS和设置在谷歌地图上的标记android

public class MapsFragment extends Fragment implements OnMapReadyCallback, GoogleMap.OnMapLoadedCallback { 
    private static View view; 
    private SupportMapFragment mMap; 
    private static Double latitude = 28.6538100, longitude = 77.2289700; 
    GoogleMap gMap; 
    private static final int PERMISSION_REQUEST_CODE = 1; 
    private MinDisLocationListener locationListener; 
    private LocationManager lm; 

    public MapsFragment() { 
    } 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     FragmentManager fm = getActivity().getSupportFragmentManager(); 
     SupportMapFragment mMapFragment = (SupportMapFragment) getActivity() 
       .getSupportFragmentManager().findFragmentById(R.id.map); 
     locationListener = new MinDisLocationListener(); 
     lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); 
     if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 2, this.locationListener); 
     } else { 
      requestPermission(); 
     } 
     lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 2, this.locationListener); 
     if (mMapFragment == null) { 
      mMapFragment = SupportMapFragment.newInstance(); 
      fm.beginTransaction().replace(R.id.map, mMapFragment).commit(); 
      mMapFragment.getMapAsync(this); 
     } 
     view = inflater.inflate(R.layout.fragment_map, container, false); 

     return view; 
    } 

    @Override 
    public void onMapReady(GoogleMap map) { 
     gMap = map; 
     gMap.setOnMapLoadedCallback(this); 
//  drawMarker(latitude, longitude); 
     gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new 
       LatLng(49.39, -124.83), 20)); 
     gMap.addMarker(new MarkerOptions() 
       .position(new LatLng(37.7750, 122.4183)) 
       .title("San Francisco") 
       .snippet("Population: 776733")); 
     gMap.getUiSettings().setZoomGesturesEnabled(true); 
     if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      gMap.setMyLocationEnabled(true); 
      lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 2, this.locationListener); 
     } else { 
      requestPermission(); 
     } 
    } 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     FragmentManager fm = getChildFragmentManager(); 
     mMap = (SupportMapFragment) fm.findFragmentById(R.id.map); 
     if (mMap != null) { 
      mMap = SupportMapFragment.newInstance(); 
      fm.beginTransaction().replace(R.id.map, mMap).commit(); 
      mMap.getMapAsync(this); 
     } 
    } 


    private void requestPermission() { 
     if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) { 
      Toast.makeText(getActivity(), "GPS permission allows us to access location data. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show(); 
     } else { 
      ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE); 
     } 
    } 

    public void drawMarker(double lat, double lon) { 
     if (gMap != null) { 
      MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lon)).title(" Maps Tutorial").snippet("Android Ruler"); 
      marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); 
      CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(12).build(); 
      gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); 
      gMap.addMarker(marker); 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case PERMISSION_REQUEST_CODE: 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
         gMap.setMyLocationEnabled(true); 
         lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000, 2, this.locationListener); 
        } 
        gMap.setMyLocationEnabled(true); 
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 2, this.locationListener); 
       } else { 


       } 
       break; 
     } 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     FragmentManager fm = getChildFragmentManager(); 
     mMap = (SupportMapFragment) fm.findFragmentById(R.id.map); 
     if (mMap != null) { 
      mMap = SupportMapFragment.newInstance(); 
      fm.beginTransaction().replace(R.id.map, mMap).commit(); 
      mMap.getMapAsync(this); 

     } 
    } 

    @Override 
    public void onDestroyView() { 
     super.onDestroyView(); 
     if (mMap != null) { 
      mMap = null; 
     } 
    } 

    @Override 
    public void onMapLoaded() { 
    } 

    public class MinDisLocationListener implements LocationListener { 
     @Override 
     public void onLocationChanged(Location location) { 
      Log.d("location", "onLocationChanged"); 
      drawMarker(location.getLatitude(),location.getLongitude()); 
      Toast.makeText(getActivity(), "onLocationChanged", Toast.LENGTH_SHORT).show(); 
     } 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
      Log.d("location", "onStatusChanged"); 
      Toast.makeText(getActivity(), "onStatusChanged", Toast.LENGTH_SHORT).show(); 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
      Log.d("location", "onProviderEnabled"); 
      Toast.makeText(getActivity(), "onProviderEnabled", Toast.LENGTH_SHORT).show(); 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 
      Log.d("location", "onProviderEnabled"); 
      Toast.makeText(getActivity(), "onProviderEnabled", Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 

Msnifist文件这是

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.deltastar.catchme" > 

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.READ_CONTACTS" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <uses-permission android:name="android.permission.CALL_PHONE" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permisssion.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 
    - See more at: 
    http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample#sthash.PtrAvZrk.dpuf 
    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_logo" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme" > 
     <activity android:name=".LoginActivity" /> 
     <activity 
      android:name=".RegisterActivity" 
      android:label="@string/register" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <activity 
      android:name=".OtpVerifyActivity" 
      android:label="@string/otp_verify" /> 
     <activity android:name=".CreateProfileActivity" /> 
     <activity android:name=".ChatMemberActivity" /> 
     <activity android:name=".CreateGroup" /> 
     <activity android:name=".AddMemberGroup" /> 
     <activity android:name=".MeatPointName" /> 
     <activity android:name=".MyMeeting" /> 
     <activity android:name=".ChatActivity" /> 
     <activity android:name=".GroupInfo" /> 
     <activity 
      android:name=".MapChat" 
      android:label="@string/title_activity_map_chat" /> 
     <activity android:name=".MyMeatingReq" /> 
     <activity android:name=".UserProfile" /> 
     <activity android:name=".MyProfile" /> 
     <activity android:name=".SplashScreen" /> 
     <activity android:name=".Settings" /> 
     <activity 
      android:name=".DrawerDemo" 
      android:label="@string/title_activity_drawer_demo" 
      android:theme="@style/AppTheme" /> 

     <!-- 
      The API key for Google Maps-based APIs is defined as a string resource. 
      (See the file "res/values/google_maps_api.xml"). 
      Note that the API key is linked to the encryption key used to sign the APK. 
      You need a different API key for each encryption key, including the release key that is used to 
      sign the APK for publishing. 
      You can define the keys for the debug and release targets in src/debug/ and src/release/. 
     --> 
     <meta-data 
      android:name="com.google.android.geo.API_KEY" 
      android:value="@string/google_maps_key" /> 

     <activity 
      android:name=".MeetingPointLocation" 
      android:label="@string/title_activity_create_meating_point" /> 
     <!-- 
      ATTENTION: This was auto-generated to add Google Play services to your project for 
      App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. 
     --> 
     <meta-data 
      android:name="com.google.android.gms.version" 
      android:value="@integer/google_play_services_version" /> 

     <activity 
      android:name=".HomePage" 
      android:label="@string/title_activity_home_page" 
      android:theme="@style/AppTheme" /> 
     <activity android:name=".MyLocation" /> 

     <activity android:name="com.services.LocDemo" > 
     </activity> 
    </application> 

</manifest> 

fragment_map.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.fragment.MapsFragment"> 

    <fragment xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:id="@+id/map" 
     android:name="com.google.android.gms.maps.SupportMapFragment" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 
</FrameLayout> 
+0

请显示清单文件 –

+0

您可以发布fragment_map和您的活动xml吗? – Raghavendra

回答

0

从那里 http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial 检查项目,但我觉得有明显 问题,你有没有这个

<permission         android:name="tj.tajdev.mrking.whatisonindushanbe.permission.MAPS_RECEIVE"         android:protectionLevel="signature" />     <uses-feature         android:glEsVersion="0x00020000"         android:required="true" />     <uses-permission android:name="android.permission.VIBRATE" />     <uses-permission android:name="tj.tajdev.mrking.whatisonindushanbe.permission.MAPS_RECEIVE" />     <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" />     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />     <uses-permission android:name="android.permission.READ_PHONE_STATE" />     <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.RECORD_AUDIO" />     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

<meta-data             android:name="com.google.android.gms.version"             android:value="@integer/google_play_services_version" /> 
1

您的代码运行完美。您只需将设备移动到可用gps的地方,因为您测试应用的地方可能不会暴露于GPS卫星。 onLocationChanged()将在设备检测到GPS时调用

+0

你确定我的代码工作完美,如果GPS卫星没有在那个地方找到什么解决方案 –

+0

是我评论语句“drawMarker(location.getLatitude(),location.getLongitude());”和测试代码,它显示吐司“onLocationChanged” – Nikhil

+0

好的谢谢尼克希尔,但我测试了其他地方吐司显示只有一次位置不更新后5000秒或2米 –

相关问题