简体   繁体   中英

Android: Setting user location on Google Map activity

i have just made an activity within my app that shows a map to the user. how can i put the location of the user onto this map? little bit confused about doing this so any help would be appreciated!

ALSO: when i set up the map, I had to include: MapView mapView = (MapView) findViewById(R.id.mapview); Why do you have to include this because don't you already have: setContentView(R.layout.main);? -- sounds like an idiot question but its just something i wondered!

I'd suggest using the MyLocationOverlay. This will get the user's current location and display it on the map via the blue dot. You can accomplish this with something like:

List<Overlay> overlays = mMaps.getOverlays();
overlays.clear();

MyLocationOverlay myLocOverlay = new MyLocationOverlay(this, mMaps);
myLocOverlay.enableMyLocation();
overlays.add(myLocOverlay);
myLocOverlay.runOnFirstFix(new Runnable() { public void run() {
    mMaps.getController().animateTo(myLocOverlay.getMyLocation());
}});

Here is a sample code that do the job. Short description, you are first getting locationService to learn location then with Criteria api you lets the system choose best provider according to your settings in Criteria then you got provider, request location updates from provider and implement LocationListener interface, too get cached last location you can call getLastKnownLocation but I wouldnt count on that may lead to outdated or null results

        String contenxt = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getSystemService(contenxt);

        /*
         * trying to get the best provider
         * with given conditions
         */
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setCostAllowed(true);
        criteria.setSpeedRequired(false);
        criteria.setBearingRequired(false);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        String provider = locationManager.getBestProvider(criteria, true);
        Log.d(GAL, provider);

        locationManager.requestLocationUpdates(provider, 3000, 30, locationListener);
        location = locationManager.getLastKnownLocation(provider);

Note: Dont forget to implement Location Listener

Answer to note: You are not including mapView with findViewById(R.id.mapView) its already included in your xml so in your layout. You are just getting reference to mapView to use builtin methods like setZoom, animateTo etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM