简体   繁体   English

在Android上使用Google Maps v2抢占用户位置?

[英]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. 我要从Location抓取纬度和经度,并在onLocationChanged()方法内创建一个标记。 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()); 应该是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的配置的改进,我建议以这种方式进行设置:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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