2013-02-10 111 views
4

我想在每次位置更改時在地圖中放置一個標記。我從Location中獲取緯度和長度,並在onLocationChanged()方法中創建標記。爲什麼標記不被創建?在android上抓取谷歌地圖v2的用戶位置?

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); 
} 
+0

你確保你能獲得位置更新? – iagreen 2013-02-10 02:07:19

+0

是的,我已經在外面測試過它,並且驅動它並更新。 – 2013-02-11 00:29:32

+0

我會放大檢索的位置來檢查。因此,在你的'onLocationChanged'中,放大位置以確保不添加標記。 – 2013-02-15 14:16:09

回答

2

LatLng current = new LatLng(location.getLatitude(), location.getLatitude());應該 LatLng current = new LatLng(location.getLatitude(), location.getLongitude());

此外,作爲一項改善的LocationManager的配置,我建議設置這樣說:

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

我真的很愛你。 – 2013-02-17 18:58:36