2014-09-12 80 views
0

我正在嘗試獲取座標,但沒有成功。結果是0。但是當我寫:GoogleMaps API無法獲取當前的緯度和經度

googleMap.setMyLocationEnabled(true); 

我可以看到藍點。我想使用此代碼來獲得這些值:

lat = googleMap.getMyLocation().getLatitude(); 
lng = googleMap.getMyLocation().getLongitude(); 

之後,latlng爲0

我的整個代碼:

public class GPS_maps extends Activity { 
    // Google Map 
    private GoogleMap googleMap; 
    static Location currentLocation; 
    static double lat , lng; 
    TextView coordinates; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.map); 
     coordinates = (TextView) findViewById(R.id.txt_coordinates); 
     try { 
      // Loading map 
      initilizeMap(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    private void initilizeMap() { 
     if (googleMap == null) {    
      googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); 
      // googleMap.setMyLocationEnabled(true); 
      lat = googleMap.getMyLocation().getLatitude(); 
      lng = googleMap.getMyLocation().getLongitude(); 
      coordinates.setText(String.valueOf(lat) +" , " +String.valueOf(lng)); 
      LatLng coordinate = new LatLng(lat, lng); 
      CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 5); 
      googleMap.animateCamera(yourLocation); 
      if (googleMap == null) { 
       Toast.makeText(getApplicationContext(), 
        "Unable to create maps", Toast.LENGTH_SHORT) 
        .show(); 
      } 
     } 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     initilizeMap(); 
    }} 
} 

我沒有得到任何錯誤。我的錯誤在哪裏?

+0

該地圖可能在當時沒有您的位置。嘗試添加一個'onMyLocationChangeListener'到您的地圖並在第一次通話中設置您的位置。 – dharms 2014-09-12 16:28:13

回答

0

請嘗試以下操作:

從lat,lan的聲明中刪除靜態修飾符。 確保您使用正確的語法發送setCoordiante。 爲確保經緯度正確,請在獲取它們後立即打印出來。

+0

刪除了靜態但仍然沒有任何差異0 – user3339279 2014-09-12 16:38:59

+0

獲取它們後立即打印出變量。它說什麼? – 2014-09-12 16:58:31

+0

同時打印出googleMap對象以確保它存在,就像你想要的一樣 – 2014-09-12 16:58:58