2017-10-07 1 views
-4

Ich möchte meinen aktuellen Standort mit Google Maps v2 aus einer fragment zeigen, aber die Google Maps wird beim Start nicht initialisiert. Wenn ich die Anwendung starte, stürzt sie nicht ab, aber die Karte zeigt weder meine aktuelle Position noch zeigt sie irgendetwas an. Ich habe diesen Code für meine Aktivität verwendet und er ist voll funktionsfähig.Google Maps v2 nicht initialisiert in Fragment

Unten ist mein java Code:

public class MapFragment extends Fragment implements LocationListener,GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener,OnMapReadyCallback { 
    SupportMapFragment mSupportMapFragment; 
    MapView mMapView; 
    Location mLastLocation; 
    Marker mCurrLocationMarker; 
    private MarkerOptions markerOptions; 
    protected GoogleApiClient mGoogleApiClient; 
    private LatLng latLng; 
    public GoogleMap mMap; 
    private Marker marker; 
    LocationRequest mLocationRequest; 
    private GoogleMap googleMap; 
    private TextView lastTrip, lastDeliveryText, lastDelivery, lastAmountText, lastAmount, kes, 
      todayTotal, totalDeliveryText, totalDelivery, totalAmount, totalAmountText; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     buildGoogleApiClient(); 
     // inflat and return the layout 
     View v = inflater.inflate(R.layout.map_fragment, container, 
       false); 

     mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapwhere); 
     if (mSupportMapFragment == null) { 
      FragmentManager fragmentManager = getFragmentManager(); 
      FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
      mSupportMapFragment = SupportMapFragment.newInstance(); 
      fragmentTransaction.replace(R.id.mapwhere, mSupportMapFragment).commit(); 
     } 

     if (mSupportMapFragment != null) { 
      mSupportMapFragment.getMapAsync(this); 
     } 


     return v; 
    } 
    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     Log.d("one","one"); 

     mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
     //mMap.getUiSettings().setZoomControlsEnabled(true); 
     if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (ContextCompat.checkSelfPermission(getActivity(), 
        Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 
       Log.d("two","two"); 
       buildGoogleApiClient(); 
       mMap.setMyLocationEnabled(true); 

      } 
     } else { 
      Log.d("three","three"); 
      buildGoogleApiClient(); 
      mMap.setMyLocationEnabled(true); 

     } 
    } 
    protected synchronized void buildGoogleApiClient() { 
     Log.d("four","four"); 
     mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .addApi(Places.GEO_DATA_API) 
       .build(); 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     Log.d("five","five"); 
     mLastLocation = location; 

     if (mCurrLocationMarker != null) { 
      mCurrLocationMarker.remove(); 
     } 
     //mMap.getUiSettings().setZoomControlsEnabled(true); 

     final Double lat = location.getLatitude(); 
     final Double lng = location.getLongitude(); 
     Log.d("LATLANGz", lat + "|" + lng); 
     latLng = new LatLng(lat, lng); 
     markerOptions = new MarkerOptions(); 
     markerOptions.position(latLng); 
     markerOptions.title("Current Positionn"); 
     if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
      return; 
     } 
     mMap.setMyLocationEnabled(false); 

     markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.user_location)); 

     marker = mMap.addMarker(markerOptions); 

     //move map camera_main 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     mMap.animateCamera(CameraUpdateFactory.zoomTo(12)); 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     Log.d("hey2","hey2"); 
//  mMapView.onResume(); 
     mSupportMapFragment.onResume(); 
    } 

    @Override 
    public void onPause() { 

     super.onPause(); 
     Log.d("hey1","hey1"); 
     // mMapView.onPause(); 
     mSupportMapFragment.onPause(); 
    } 

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

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

    @Override 
    public void onDetach() { 
     Log.d("detach", "detach"); 
     super.onDetach(); 
     mSupportMapFragment.onDetach(); 

    } 


    @Override 
    public void onConnected(@Nullable Bundle bundle) { 
     Log.d("six","six"); 
     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(1000); 
     mLocationRequest.setFastestInterval(1000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 

     if (mGoogleApiClient.isConnected()){ 
      Log.d("seven","six"); 
      if (ContextCompat.checkSelfPermission(getActivity(), 
        Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 
       LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
      } 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

    } 
+2

@Anshul Ich habe Internet und access_fine_location –

+0

haben Sie Projekt auf Google erstellt? –

+0

ja, wenn ich statische LatLng onMapReady innere Funktion in onCreate es funktioniert –

Antwort

0

zuerst Ihre Berechtigungen überprüfen und Ihre api Schlüssel Google in Ihrem Manifest

Ihr xml Layout muss auch ohne irgend etwas so etwas wie dieses:

. <fragment xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:map="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/map" 
    android:name="com.google.android.gms.maps.SupportMapFragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.isg_biz.isg_tracking.MainActivity" /> 

Sie müssen OnMapReadyCallback implementieren, dann Ihr Code sollte so etwas sein in onCreate():

 SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
     .findFragmentById(R.id.map); 
mapFragment.getMapAsync(this); 

Sie nicht und vorbei an dem gleichen XML-Code zu kopieren buchstäblich müssen Sie (Werkzeuge: .....) ändern zu gleichen, die

für die Dokumentation in Ihrem xml existiert, Java-Code & mehr Bitte lesen:

https://developers.google.com/maps/documentation/android-api/map-with-marker

0

allererst Chaeck Erlaubnis in manifest

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 

dann Methode zur aktuellen Standort überprüfen

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() { 
    @Override 
    public void onMyLocationChange(Location location) { 
     LatLng loc = new LatLng(location.getLatitude(), location.getLongitude()); 
     marker = map.addMarker(new MarkerOptions().position(loc)); 
     if(map != null){ 
      map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f)); 
     } 
    } 
}; 

dann

mMap.setOnMyLocationChangeListener(myLocationChangeListener); 

verwenden und Geduld Karte nehmen zeitAufladungsTyp hängt von Ihnen Netzwerkgeschwindigkeit

Kommentar, wenn eine Abfrage