2016-11-30 2 views
0

Ich habe einige Online-Tutorials zum Hinzufügen von Markierungen zu den Google Maps API in Android gefolgt. Der Code ist anders aufgebaut als meiner, aber im Allgemeinen habe ich gesehen, dass es in der onCreate-Methode gemacht wird. Unten habe ich einen wirklich grundlegenden Code, um zu versuchen, einen Marker in der Mitte der Karte zu bekommen, jedoch erhalte ich eine Null-Zeiger-Ausnahme. Kennt jemand eine einfache Lösung dafür?Hinzufügen von Markierungen zu Google API

Hier ist der Fehler im Detail und unten ist meine Methode. Ich habe map als globale Variable deklariert.

java.lang.NullPointerException: Der Versuch, virtuelle Methode ‚com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker aufzurufen (com.google.android .gms.maps.model.MarkerOptions)‘auf einer null-Objekt Referenz

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    serviceManager = ServiceManager.getInstance(getActivity()); 
    userID = getString(R.string.mobile_health_client_user_id); 
    client = MobileIOClient.getInstance(getContext(), userID); 
    //client = MobileIOClient.getInstance(userID); 
    map.addMarker(new MarkerOptions() 
      .position(new LatLng(0, 0)) 
      .title("Hello world")); 
} 

ich habe lief auch über das google Tutorial, das onMapReady überschreibt(), aber diese Methode für mich funktioniert nicht. Ich bin mir nicht sicher, wie ich es in meinem Code zum Laufen bringen kann und kann keine adäquate Ressource online finden, die mir hilft. Jede Hilfe wäre willkommen. Hier

Dank

+0

Die Antwort zeigt Ihnen, wie Sie die Karte innerhalb OnMapReadyCallback zu bekommen. Dann können Sie die Markierungen zur Karte hinzufügen – ganlaw

Antwort

1

Sie sollten nicht mit dem Kartenobjekt in Ihrer Aktivität oder ein Fragment des onCreate() -Methode interagieren. Die einfache Überlegung ist, dass die Karte wahrscheinlich noch nicht fertig ist. Der richtige Weg, um dies zu handhaben ist die Implementierung der OnMapReadyCallback Schnittstelle und Hinzufügen von Marker in Ihrer Implementierung der onMapReady(GoogleMap googleMap) Funktion.

Ihre Lösung muss etwas anders sein, wenn Sie eine MapFragment vs MapView verwenden, aber die allgemeine Idee bleibt die gleiche.

Beispiel:

public class MyActivity extends Activity implements OnMapReadyCallback { 
    . 
    . 
    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     map = googleMap; // Set your local instance of GoogleMap for future use 
     map.addMarker(new MarkerOptions() 
      .position(new LatLng(0, 0)) 
      .title("Hello world")); 
    } 
    . 
    . 
} 

Wenn Sie eine MapView verwenden, benötigen Sie einen Griff zu Ihrer Ansicht in Ihrem Layout zu erhalten und ausdrücklich map.getMapAsync(this) aufrufen, um den onMapReady() Hörer zu befestigen.

Ich hoffe, das hilft!

1

ist der Code, den ich verwenden:

public class Map extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener { 

private GoogleMap mMap; 
public GoogleApiClient mGoogleApiClient; 
public static final String TAG = Map.class.getSimpleName(); 
public LocationRequest mLocationRequest; 
double latitude; 
double longitude; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_map); 

    // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 

    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 

    // Create the LocationRequest object 
    mLocationRequest = LocationRequest.create() 
      .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) 
      .setInterval(10 * 1000)  // 10 seconds, in milliseconds 
      .setFastestInterval(1 * 1000); // 1 second, in milliseconds 

} 


/** 
* Manipulates the map once available. 
* This callback is triggered when the map is ready to be used. 
* This is where we can add markers or lines, add listeners or move the camera. 
* If Google Play services is not installed on the device, the user will be prompted to install 
* it inside the SupportMapFragment. This method will only be triggered once the user has 
* installed Google Play services and returned to the app. 
*/ 
@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 


    LatLng here = new LatLng(latitude,longitude); 
    mMap.addMarker(new MarkerOptions().position(here).title("Here!")); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(here)); 
} 

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    Log.i(TAG, "Location services connected."); 
    Location location = null; 
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
      == PackageManager.PERMISSION_GRANTED) { 
     location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    } 

    if (location == null) { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
    } 
    else { 
     handleNewLocation(location); 
    }; 
} 

@Override 
public void onConnectionSuspended(int i) { 
    Log.i(TAG, "Location services suspended. Please reconnect."); 
} 

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

} 

@Override 
protected void onResume(){ 
    super.onResume(); 
    //setUpMapIfNeeded(); 
    mGoogleApiClient.connect(); 
} 

@Override 
protected void onPause() { 
    super.onPause(); 
    if (mGoogleApiClient.isConnected()) { 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
     mGoogleApiClient.disconnect(); 
    } 
} 

private void handleNewLocation(Location location) { 
    Log.d(TAG, location.toString()); 
    latitude = location.getLatitude(); 
    longitude = location.getLongitude(); 
    LatLng latLng = new LatLng(latitude,longitude); 

    MarkerOptions options = new MarkerOptions() 
      .position(latLng) 
      .title("I am here!"); 
    mMap.addMarker(options); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
} 

@Override 
public void onLocationChanged(Location location) { 
    handleNewLocation(location); 
    }  
} 
1

schreiben einfach in onMapReady
googleMap.addMarker(new MarkerOptions().position(new LatLng(0, 0));

Verwandte Themen