2015-04-06 133 views
1

我試圖在地圖片段中獲取當前位置,但在線路中出現錯誤時崩潰googleMap.setMyLocationEnabled(true); 我用Location和Latlang檢測當前位置。無法在Google地圖片段中獲取當前位置

mapFragment.java

public class mapFragment extends Fragment { 

    MapView mMapView; 
    private GoogleMap googleMap; 
    Location location; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // inflat and return the layout 
     View v = inflater.inflate(R.layout.fragment_map, container, 
       false); 
     mMapView = (MapView) v.findViewById(R.id.mapView); 
     mMapView.onCreate(savedInstanceState); 

     mMapView.onResume();// needed to get the map to display immediately 

     try { 
      MapsInitializer.initialize(getActivity().getApplicationContext()); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     googleMap.setMyLocationEnabled(true); 
     googleMap = mMapView.getMap(); 
     // latitude and longitude 
     LatLng lat = new LatLng(location.getLatitude(), location.getLongitude()); 
     /*double latitude = 17.385044; 
     double longitude = 78.486671;*/ 

     // create marker 
     MarkerOptions marker = new MarkerOptions().position(
       lat).title("Hello Maps"); 

     // Changing marker icon 
     marker.icon(BitmapDescriptorFactory 
       .defaultMarker(BitmapDescriptorFactory.HUE_ROSE)); 

     // adding marker 
     googleMap.addMarker(marker); 
     CameraPosition cameraPosition = new CameraPosition.Builder() 
       .target(lat).zoom(12).build(); 
     googleMap.animateCamera(CameraUpdateFactory 
       .newCameraPosition(cameraPosition)); 

     // Perform any camera updates here 
     return v; 
    } 


    @Override 
    public void onResume() { 
     super.onResume(); 
     mMapView.onResume(); 
    } 

    @Override 
    public void onPause() { 
     super.onPause(); 
     mMapView.onPause(); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     mMapView.onDestroy(); 
    } 

    @Override 
    public void onLowMemory() { 
     super.onLowMemory(); 
     mMapView.onLowMemory(); 
    } 
} 

fragment_map.xml

<?xml version="1.0" encoding="utf-8"?> 
<com.google.android.gms.maps.MapView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/mapView" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 
+0

你的精確位置在清單中添加的權限? –

回答

0

看起來你有一些問題,但飛機墜毀發生,因爲你需要調用getMap()你打電話之前setMyLocationEnabled()

更改此:

googleMap.setMyLocationEnabled(true); 
googleMap = mMapView.getMap(); 

...這樣的:

googleMap = mMapView.getMap(); 
googleMap.setMyLocationEnabled(true); 

更新:我能得到這個代碼的工作。

獲取當前位置應該使用Fused Location Provider API完成,但這超出了此問題的範圍。

本示例代碼中的方法可能適用於較舊的設備,但在4.4.4版本中,由於getMyLocation()被刪除而返回空位置。

但是,使用空檢查地圖顯示正確,並且您可以單擊位置按鈕以使地圖移動到您當前的位置。

 MapView mMapView; 
     private GoogleMap googleMap; 
     Location location; 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
           Bundle savedInstanceState) { 
      // inflat and return the layout 
      View v = inflater.inflate(R.layout.fragment_main, container, 
        false); 
      mMapView = (MapView) v.findViewById(R.id.mapView); 
      mMapView.onCreate(savedInstanceState); 

      mMapView.onResume();// needed to get the map to display immediately 

      try { 
       MapsInitializer.initialize(getActivity().getApplicationContext()); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      googleMap = mMapView.getMap(); 
      googleMap.setMyLocationEnabled(true); 

      location = googleMap.getMyLocation(); 

      if (location != null) { 

       // latitude and longitude 
       LatLng lat = new LatLng(location.getLatitude(), location.getLongitude()); 

       //double latitude = 17.385044; 
       //double longitude = 78.486671; 
       //LatLng lat = new LatLng(latitude,longitude); 

       // create marker 

       MarkerOptions marker = new MarkerOptions().position(
         lat).title("Hello Maps"); 

       // Changing marker icon 
       marker.icon(BitmapDescriptorFactory 
         .defaultMarker(BitmapDescriptorFactory.HUE_ROSE)); 

       // adding marker 
       googleMap.addMarker(marker); 

       CameraPosition cameraPosition = new CameraPosition.Builder() 
         .target(lat).zoom(12).build(); 


       googleMap.animateCamera(CameraUpdateFactory 
         .newCameraPosition(cameraPosition)); 

      } 

      // Perform any camera updates here 
      return v; 
     } 
0

您可以使用setOnMyLocationChangeListener方法獲取當前位置。下載源在這裏(Show Google Map In Android

MainActivity.Java

package deepshikha.googlemap; 

import android.Manifest; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.location.Location; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.Toast; 

import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.MapFragment; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 

public class MainActivity extends AppCompatActivity { 
public GoogleMap googleMap; 
private static final int REQUEST_PERMISSIONS = 100; 
Button btn; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    btn = (Button)findViewById(R.id.btn); 


    fn_permission(); 
    fn_currentlocation(); 
} 

public void fn_currentlocation(){ 

    if (googleMap == null) { 
     googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); 

     try { 

      googleMap.setMyLocationEnabled(true); 
     } catch (Exception e) { 

     } 

     if (googleMap != null) { 

      googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() { 

       @Override 
       public void onMyLocationChange(Location arg0) { 
        // TODO Auto-generated method stub 
        double current_latitude = arg0.getLatitude(); 
        double currrent_longitude = arg0.getLongitude(); 
        LatLng current_latLng = new LatLng(current_latitude, currrent_longitude); 
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(current_latLng)); 

        Log.e("CURRENT LONGITUDE", currrent_longitude + ""); 
        Log.e("CURRENT LATITUDE", current_latitude + ""); 

        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); 
        googleMap.addMarker(new MarkerOptions().position(current_latLng).title("Marker")); 
       } 
      }); 

     } 


    } 
} 

private void fn_permission(){ 
    if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) || 
      (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) { 
     if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) && 
       (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION))) { 
     } else { 
      ActivityCompat.requestPermissions(MainActivity.this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION}, 
        REQUEST_PERMISSIONS); 
     } 
    } 

} 


@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults); 

    switch (requestCode) { 
     case REQUEST_PERMISSIONS: { 
      for (int i = 0; i < grantResults.length; i++) { 
       if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) { 

       } else { 
        Toast.makeText(MainActivity.this, "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show(); 
       } 
      } 
     } 
    } 
} 
} 
相關問題