【问题标题】:Get Location form GPS and set marker on google maps in android从 GPS 获取位置并在 android 的谷歌地图上设置标记
【发布时间】:2016-06-20 15:20:45
【问题描述】:

您好,我正在尝试从 Gps 获取位置(纬度和经度)并在谷歌地图上设置标记,但它不起作用。在此代码中,我试图从 gps 位置侦听器方法 onLocationChanged 获取纬度和经度,但此方法从不调用没有显示任何吐司。

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>

【问题讨论】:

  • 请显示清单文件
  • 你可以发布 fragment_map 和你的活动 xml 吗?

标签: android google-maps


【解决方案1】:

您的代码运行良好。您只需将您的设备移动到 GPS 可用的地方,因为您正在测试应用程序的地方可能没有接触到 GPS 卫星。 一旦设备检测到 GPS,就会调用 onLocationChanged()

【讨论】:

  • 你确定我的代码工作正常吗?如果在那个地方找不到 GPS 卫星有什么解决方案
  • 是的,我评论了语句“drawMarker(location.getLatitude(),location.getLongitude());”并测试代码,它显示 Toast "onLocationChanged"
  • 好的,谢谢 nikhil,但我在其他地方测试它只显示一次位置在 5000 秒或 2 米后不更新
【解决方案2】:

从那里检查您的项目 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" /> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多