简体   繁体   中英

Grabbing user location with google maps v2 on android?

I want to place a marker in the map each time the location changes. I am grabbing the Lat and Long from the Location and creating a marker within the onLocationChanged() method. Why doesn't the marker get created?

 public class MainActivity extends FragmentActivity implements LocationListener
{
Context context = this;
GoogleMap googlemap;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initMap();
    addTwittertoMap();

    LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0,
            this);
    String provider = lm.getBestProvider(new Criteria(), true);

}

public void onLocationChanged(Location location) {
    LatLng current = new LatLng(location.getLatitude(), location.getLatitude());
    Date date = new Date();

    googlemap.addMarker(new MarkerOptions()
            .title("Current Pos")
            .snippet(new Timestamp(date.getTime()).toString())
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
            .position(current)
            );
}

public void onStatusChanged(String provider, int status, Bundle extras) {
}

public void onProviderEnabled(String provider) {
}

public void onProviderDisabled(String provider) {

}
private void initMap(){
    SupportMapFragment mf = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    googlemap = mf.getMap();

    googlemap.setMyLocationEnabled(true);
    googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}

LatLng current = new LatLng(location.getLatitude(), location.getLatitude()); should be LatLng current = new LatLng(location.getLatitude(), location.getLongitude());

Also, as an improvement to the configuration of the LocationManager, I'd suggest to setup it this way:

    LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    String provider = lm.getBestProvider(new Criteria(), true);
    lm.requestLocationUpdates(provider, 10000, 0, this);

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