android– 在Google Map Fragment中显示当前位置

android– 在Google Map Fragment中显示当前位置,第1张

概述我目前正在制作一个带有谷歌地图的片段.一旦用户访问该片段,他的地图应该缩放并关注他的位置.但是,它显示的是世界地图而不是附近的位置(靠近用户):@SuppressWarnings("unused")publicclassDeferredMapFragmentextendsMapFragmentimplementsGoogleMap.OnCameraChangeListen

我目前正在制作一个带有谷歌地图的片段.一旦用户访问该片段,他的地图应该缩放并关注他的位置.但是,它显示的是世界地图而不是附近的位置(靠近用户):

@SuppressWarnings("unused")public class DeferredMapFragment extends MapFragment implements GoogleMap.OnCamerachangelistener, OnMapReadyCallback, Googleapiclient.ConnectionCallbacks, Googleapiclient.OnConnectionFailedListener,            LocationListener {        private static final String TAG = "DeferredMapFragment";    private Deque<Runnable> pendingActions;    private AbstractMap<Marker, Object> Tags;    private GoogleMap map;    private LocationRequest mLocationRequest;    private Googleapiclient mGoogleapiclient;    private Location mLastLocation;    private Marker marker;    private GoogleMap.OnCamerachangelistener camerachangelistener = null;    private boolean isMapReady = false;    /*     * INTERNALS     */    @OverrIDe    public voID onActivityCreated(Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        if (getMap() != null) {            map = getMap();            getMap().setonCamerachangelistener(this);        }    }    @OverrIDe    public voID onCameraChange(Cameraposition cameraposition) {        isMapReady = true;        if (pendingActions != null) {            int i = pendingActions.size();            while (i > 0) {                pendingActions.pop().run();                --i;            }        }        if (camerachangelistener != null) {            camerachangelistener.onCameraChange(cameraposition);        }        if (getMap() != null) {            getMap().setonCamerachangelistener(camerachangelistener);        }    }    private voID execute(Runnable action) {        if (action == null) {            return;        }        if (isMapReady) {            action.run();        } else {            if (pendingActions == null) {                pendingActions = new linkedList<>();            }            pendingActions.add(action);        }    }    /*     * TAGGING     */    private voID addTag(Marker key, Object value) {        if (Tags == null) {            Tags = new HashMap<>();        }        Tags.put(key, value);    }    public Object getTag(Marker key) {        return Tags != null ? Tags.get(key) : null;    }    /*     * ListENERS     */    public voID setonInfoWindowClickListener(final GoogleMap.OnInfoWindowClickListener Listener) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().setonInfoWindowClickListener(Listener);            }        });    }    public voID setonCamerachangelistener(final GoogleMap.OnCamerachangelistener Listener) {        camerachangelistener = Listener;    }    public voID setonMarkerClickListener(final GoogleMap.OnMarkerClickListener Listener) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().setonMarkerClickListener(Listener);            }        });    }    public voID setonMapClickListener(final GoogleMap.OnMapClickListener Listener) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().setonMapClickListener(Listener);            }        });    }    /*     * MAP OVERLAYS     */    public voID addpolyline(final polylineoptions options) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().addpolyline(options);            }        });    }    public voID addpolygon(final polygonoptions options) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().addpolygon(options);            }        });    }    public voID addCircle(final CircleOptions options) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().addCircle(options);            }        });    }    public voID addMarker(final MarkerOptions options) {        addMarker(options, null);    }    public voID addMarker(final MarkerOptions options, final Object tag) {        execute(new Runnable() {            @OverrIDe            public voID run() {                Marker marker = getMap().addMarker(options);                if (tag != null) {                    addTag(marker, tag);                }            }        });    }    public voID addGroundOverlay(final GroundOverlayOptions options) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().addGroundOverlay(options);            }        });    }    public voID addTileOverlay(final TileOverlayOptions options) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().addTileOverlay(options);            }        });    }    /*     *  UI SETTINGS     */    public voID setMapToolbarEnabled(final boolean enabled) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().getUiSettings().setMapToolbarEnabled(enabled);            }        });    }    public voID setpadding(final int left, final int top, final int right, final int bottom) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().setpadding(left, top, right, bottom);            }        });    }    public voID setZoomControlsEnabled(final boolean enabled) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().getUiSettings().setZoomControlsEnabled(enabled);            }        });    }    public voID setCompassEnabled(final boolean enabled) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().getUiSettings().setCompassEnabled(enabled);            }        });    }    public voID setMyLocationbuttonEnabled(final boolean enabled) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().getUiSettings().setMyLocationbuttonEnabled(enabled);            }        });    }    public voID setIndoorLevelPickerEnabled(final boolean enabled) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().getUiSettings().setIndoorLevelPickerEnabled(enabled);            }        });    }    public voID setScrollGesturesEnabled(final boolean enabled) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().getUiSettings().setScrollGesturesEnabled(enabled);            }        });    }    public voID setZoomGesturesEnabled(final boolean enabled) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().getUiSettings().setZoomGesturesEnabled(enabled);            }        });    }    public voID setTiltGesturesEnabled(final boolean enabled) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().getUiSettings().setTiltGesturesEnabled(enabled);            }        });    }    public voID setRotateGesturesEnabled(final boolean enabled) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().getUiSettings().setRotateGesturesEnabled(enabled);            }        });    }    public voID setAllGesturesEnabled(final boolean enabled) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().getUiSettings().setAllGesturesEnabled(enabled);            }        });    }    public voID setInfoWindowAdapter(final GoogleMap.InfoWindowAdapter adapter) {        execute(new Runnable() {            @OverrIDe            public voID run() {                getMap().setInfoWindowAdapter(adapter);            }        });    }    @OverrIDe    public voID onMapReady(GoogleMap GoogleMap) {        map = GoogleMap;        setUpMap();    }    public voID setUpMap() {        map.setMapType(GoogleMap.MAP_TYPE_HYBRID);        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {            // Todo: ConsIDer calling            //    ActivityCompat#requestPermissions            // here to request the missing permissions, and then overrIDing            //   public voID onRequestPermissionsResult(int requestCode, String[] permissions,            //                                          int[] grantResults)            // to handle the case where the user grants the permission. See the documentation            // for ActivityCompat#requestPermissions for more details.            return;        }        map.setMyLocationEnabled(true);    }    @OverrIDe    public voID onConnected(Bundle bundle) {        mLocationRequest = new LocationRequest();        mLocationRequest.setInterval(1000);        mLocationRequest.setFastestInterval(1000);        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);        //mLocationRequest.setSmallestdisplacement(0.1F);        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {            // Todo: ConsIDer calling            //    ActivityCompat#requestPermissions            // here to request the missing permissions, and then overrIDing            //   public voID onRequestPermissionsResult(int requestCode, String[] permissions,            //                                          int[] grantResults)            // to handle the case where the user grants the permission. See the documentation            // for ActivityCompat#requestPermissions for more details.            return;        }        LocationServices.FusedLocationAPI.requestLocationUpdates(mGoogleapiclient, mLocationRequest, this);    }    @OverrIDe    public voID onConnectionSuspended(int i) {    }    @OverrIDe    public voID onLocationChanged(Location location) {        mLastLocation = location;        //remove prevIoUs current location Marker        if (marker != null){            marker.remove();        }        double dLatitude = mLastLocation.getLatitude();        double dLongitude = mLastLocation.getLongitude();        marker = map.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude))                .Title("My Location").icon(BitmapDescriptorFactory                        .defaultMarker(BitmapDescriptorFactory.HUE_RED)));        map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));    }    @OverrIDe    public voID onPause() {        super.onPause();        if (mGoogleapiclient != null) {            LocationServices.FusedLocationAPI.removeLocationUpdates(mGoogleapiclient, this);        }    }    protected synchronized voID buildGoogleapiclient() {        mGoogleapiclient = new Googleapiclient.Builder(getContext())                .addConnectionCallbacks(this)                .addOnConnectionFailedListener(this)                .addAPI(LocationServices.API)                .build();    }    @OverrIDe    public voID onConnectionFailed(@NonNull ConnectionResult connectionResult) {    }}

有缩放功能吗?另外我的API允许我访问用户的邮政编码.我可以用它吗?我要求用户显示他附近的位置.

解决方法:

这与我的other answer here类似,但是,这是不同的,因为您正在扩展MapFragment并在Fragment中实现自定义行为.

下面是一个扩展SupportMapFragment的示例片段,在启动时它将获取用户的当前位置,放置标记并放大:

public class MapFragment extends SupportMapFragment        implements OnMapReadyCallback,        Googleapiclient.ConnectionCallbacks,        Googleapiclient.OnConnectionFailedListener,        LocationListener {    GoogleMap mGoogleMap;    SupportMapFragment mapFrag;    LocationRequest mLocationRequest;    Googleapiclient mGoogleapiclient;    Location mLastLocation;    Marker mCurrLocationMarker;    @OverrIDe    public voID onResume() {        super.onResume();        setUpMAPIfNeeded();    }    private voID setUpMAPIfNeeded() {        if (mGoogleMap == null) {            getMapAsync(this);        }    }    @OverrIDe    public voID onPause() {        super.onPause();        //stop location updates when Activity is no longer active        if (mGoogleapiclient != null) {            LocationServices.FusedLocationAPI.removeLocationUpdates(mGoogleapiclient, this);        }    }    @OverrIDe    public voID onMapReady(GoogleMap GoogleMap)    {        mGoogleMap=GoogleMap;        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);        //Initialize Google Play Services        if (androID.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {            if (ContextCompat.checkSelfPermission(getActivity(),                    Manifest.permission.ACCESS_FINE_LOCATION)                    == PackageManager.PERMISSION_GRANTED) {                //Location Permission already granted                buildGoogleapiclient();                mGoogleMap.setMyLocationEnabled(true);            } else {                //Request Location Permission                checkLocationPermission();            }        }        else {            buildGoogleapiclient();            mGoogleMap.setMyLocationEnabled(true);        }    }    protected synchronized voID buildGoogleapiclient() {        mGoogleapiclient = new Googleapiclient.Builder(getActivity())                .addConnectionCallbacks(this)                .addOnConnectionFailedListener(this)                .addAPI(LocationServices.API)                .build();        mGoogleapiclient.connect();    }    @OverrIDe    public voID onConnected(Bundle bundle) {        mLocationRequest = new LocationRequest();        mLocationRequest.setInterval(1000);        mLocationRequest.setFastestInterval(1000);        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);        if (ContextCompat.checkSelfPermission(getActivity(),                Manifest.permission.ACCESS_FINE_LOCATION)                == PackageManager.PERMISSION_GRANTED) {            LocationServices.FusedLocationAPI.requestLocationUpdates(mGoogleapiclient, mLocationRequest, this);        }    }    @OverrIDe    public voID onConnectionSuspended(int i) {}    @OverrIDe    public voID onConnectionFailed(ConnectionResult connectionResult) {}    @OverrIDe    public voID onLocationChanged(Location location)    {        mLastLocation = location;        if (mCurrLocationMarker != null) {            mCurrLocationMarker.remove();        }        //Place current location marker        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());        MarkerOptions markerOptions = new MarkerOptions();        markerOptions.position(latLng);        markerOptions.Title("Current position");        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_magenta));        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);        //move map camera        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));    }    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;    private voID checkLocationPermission() {        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)                != PackageManager.PERMISSION_GRANTED) {            // Should we show an explanation?            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),                    Manifest.permission.ACCESS_FINE_LOCATION)) {                // Show an explanation to the user *asynchronously* -- don't block                // this thread waiting for the user's response! After the user                // sees the explanation, try again to request the permission.                new AlertDialog.Builder(getActivity())                        .setTitle("Location Permission Needed")                        .setMessage("This app needs the Location permission, please accept to use location functionality")                        .setPositivebutton("OK", new DialogInterface.OnClickListener() {                            @OverrIDe                            public voID onClick(DialogInterface dialogInterface, int i) {                                //Prompt the user once explanation has been shown                                ActivityCompat.requestPermissions(getActivity(),                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},                                        MY_PERMISSIONS_REQUEST_LOCATION );                            }                        })                        .create()                        .show();            } else {                // No explanation needed, we can request the permission.                ActivityCompat.requestPermissions(getActivity(),                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},                        MY_PERMISSIONS_REQUEST_LOCATION );            }        }    }    @OverrIDe    public voID onRequestPermissionsResult(int requestCode,                                           String permissions[], int[] grantResults) {        switch (requestCode) {            case MY_PERMISSIONS_REQUEST_LOCATION: {                // If request is cancelled, the result arrays are empty.                if (grantResults.length > 0                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {                    // permission was granted, yay! Do the                    // location-related task you need to do.                    if (ContextCompat.checkSelfPermission(getActivity(),                            Manifest.permission.ACCESS_FINE_LOCATION)                            == PackageManager.PERMISSION_GRANTED) {                        if (mGoogleapiclient == null) {                            buildGoogleapiclient();                        }                        mGoogleMap.setMyLocationEnabled(true);                    }                } else {                    // permission denIEd, boo! disable the                    // functionality that depends on this permission.                    Toast.makeText(getActivity(), "permission denIEd", Toast.LENGTH_LONG).show();                }                return;            }            // other 'case' lines to check for other            // permissions this app might request        }    }}

由于Location权限请求需要通过Activity,因此您需要将Activity的结果路由到Fragment的onRequestPermissionsResult()方法:

public class MainActivity extends AppCompatActivity {    MapFragment mapFragment;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findVIEwByID(R.ID.toolbar);        setSupportActionbar(toolbar);        mapFragment = new MapFragment();        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();        transaction.add(R.ID.mapframe, mapFragment);        transaction.commit();    }    @OverrIDe    public voID onRequestPermissionsResult(int requestCode,                                           String permissions[], int[] grantResults) {        if (requestCode == MapFragment.MY_PERMISSIONS_REQUEST_LOCATION){            mapFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);        }        else {            super.onRequestPermissionsResult(requestCode, permissions, grantResults);        }    }}

布局只包含MapFragment所在的FrameLayout.

activity_main.xml中:

<?xml version="1.0" enCoding="utf-8"?><androID.support.design.Widget.CoordinatorLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    xmlns:app="http://schemas.androID.com/apk/res-auto"    xmlns:tools="http://schemas.androID.com/tools"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent"    androID:fitsSystemwindows="true"    tools:context="com.danIElnugent.mapapplication.MainActivity">    <androID.support.design.Widget.AppbarLayout        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:theme="@style/Apptheme.AppbarOverlay">        <androID.support.v7.Widget.Toolbar            androID:ID="@+ID/toolbar"            androID:layout_wIDth="match_parent"            androID:layout_height="?attr/actionbarSize"            androID:background="?attr/colorPrimary"            app:popuptheme="@style/Apptheme.PopupOverlay" />    </androID.support.design.Widget.AppbarLayout>    <FrameLayout        androID:ID="@+ID/mapframe"        androID:layout_margintop="?attr/actionbarSize"        androID:layout_height="match_parent"        androID:layout_wIDth="match_parent" /></androID.support.design.Widget.CoordinatorLayout>

结果

首先提示位置权限:

授予位置权限后,使用标记显示当前位置:

如果用户拒绝或撤消“位置”权限,则会在应用启动时显示:

一,解释:

然后,位置权限请求:

总结

以上是内存溢出为你收集整理的android – 在Google Map Fragment中显示当前位置全部内容,希望文章能够帮你解决android – 在Google Map Fragment中显示当前位置所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1116212.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-29
下一篇2022-05-29

发表评论

登录后才能评论

评论列表(0条)

    保存