我正在尝试使用Geofire来存储和显示登录地图的用户

时间:2017-07-11 20:33:04

标签: android google-maps firebase firebase-realtime-database geofire

我正在尝试使用Geofire来存储和显示在地图上登录的用户我是android studio中的新用户 我收到这个错误  java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.parthtiwari.trace / com.example.parthtiwari.trace.tracking}:java.lang.NullPointerException:尝试调用虚拟方法'com.google.android.gms空对象引用上的.maps.model.Circle com.google.android.gms.maps.GoogleMap.addCircle(com.google.android.gms.maps.model.CircleOptions)'

     import android.app.AlertDialog;
     import android.graphics.Color;
     import android.os.Bundle;
     import android.os.Handler;
     import android.os.SystemClock;
     import android.support.v4.app.FragmentActivity;
     import android.view.animation.AccelerateDecelerateInterpolator;
     import android.view.animation.Interpolator;
     import com.firebase.geofire.GeoFire;
     import com.firebase.geofire.GeoLocation;
     import com.firebase.geofire.GeoQuery;
     import com.firebase.geofire.GeoQueryEventListener;
     import com.google.android.gms.maps.CameraUpdateFactory;         
     import com.google.android.gms.maps.GoogleMap;
     import com.google.android.gms.maps.OnMapReadyCallback;
     import com.google.android.gms.maps.SupportMapFragment;
     import com.google.android.gms.maps.model.*;
     import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    import com.google.firebase.database.DatabaseError;
    import com.google.firebase.database.FirebaseDatabase;

     import java.util.HashMap;
     import java.util.Map;

   public class tracking extends FragmentActivity implements 
  GeoQueryEventListener,OnMapReadyCallback, 
GoogleMap.OnCameraChangeListener{
private static final GeoLocation INITIAL_CENTER = new GeoLocation(22.7789, 
-78.4017);
private static final int INITIAL_ZOOM_LEVEL = 14;
private static final String GEO_FIRE_DB = "https://trace-
5fa8c.firebaseio.com";
private static final String GEO_FIRE_REF = GEO_FIRE_DB + "/_geofire";
private GoogleMap mMap;


private GoogleMap map;
private Circle searchCircle;
private GeoFire geoFire;
private GeoQuery geoQuery;
private Map<String,Marker> markers;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tracking);
    // Obtain the SupportMapFragment and get notified when the map is ready 
     to be used.
      SupportMapFragment mapFragment = (SupportMapFragment) 
      getSupportFragmentManager()
            .findFragmentById(R.id.map);
      mapFragment.getMapAsync((OnMapReadyCallback) this);
      LatLng latLngCenter = new LatLng(INITIAL_CENTER.latitude, 
    INITIAL_CENTER.longitude);
    this.searchCircle = this.map.addCircle(new 
     CircleOptions().center(latLngCenter).radius(1000));
    this.searchCircle.setFillColor(Color.argb(66, 255, 0, 255));
    this.searchCircle.setStrokeColor(Color.argb(66, 0, 0, 0));
    this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter, 
    INITIAL_ZOOM_LEVEL));
    this.map.setOnCameraChangeListener(this);

    FirebaseOptions options = new  FirebaseOptions.Builder().setApplicationId("geofire").setDatabaseUrl(GEO_FIRE_DB).build();
    FirebaseApp app = FirebaseApp.initializeApp(this, options);

    // setup GeoFire
    this.geoFire = new GeoFire(FirebaseDatabase.getInstance(app).getReferenceFromUrl(GEO_FIRE_REF));
    // radius in km
     this.geoQuery = this.geoFire.queryAtLocation(INITIAL_CENTER, 1);

    // setup markers
    this.markers = new HashMap<String, Marker>();
}


@Override
protected void onStop() {
    super.onStop();
    // remove all event listeners to stop updating in the background
    this.geoQuery.removeAllListeners();
    for (Marker marker: this.markers.values()) {
        marker.remove();
    }
    this.markers.clear();
}

@Override
protected void onStart() {
    super.onStart();
    // add an event listener to start updating locations again
    this.geoQuery.addGeoQueryEventListener(this);
}

@Override
public void onKeyEntered(String key, GeoLocation location) {
    // Add a new marker to the map
    Marker marker = this.map.addMarker(new MarkerOptions().position(new 
 LatLng(location.latitude, location.longitude)));
     this.markers.put(key, marker);
 }

 @Override
 public void onKeyExited(String key) {
    // Remove any old marker
    Marker marker = this.markers.get(key);
    if (marker != null) {
        marker.remove();
        this.markers.remove(key);
    }
}

 @Override
 public void onKeyMoved(String key, GeoLocation location) {
    // Move the marker
    Marker marker = this.markers.get(key);
    if (marker != null) {
        this.animateMarkerTo(marker, location.latitude, location.longitude);
    }
 }

 @Override
 public void onGeoQueryReady() {
 }

 @Override
 public void onGeoQueryError(DatabaseError error) {
    new AlertDialog.Builder(this)
            .setTitle("Error")
            .setMessage("There was an unexpected error querying GeoFire: " + 
   error.getMessage())
            .setPositiveButton(android.R.string.ok, null)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
   }

  // Animation handler for old APIs without animation support
  private void animateMarkerTo(final Marker marker, final double lat, final 
  double lng) {
    final Handler handler = new Handler();
     final long start = SystemClock.uptimeMillis();
    final long DURATION_MS = 3000;
    final Interpolator interpolator = new 
    AccelerateDecelerateInterpolator();
    final LatLng startPosition = marker.getPosition();
    handler.post(new Runnable() {
        @Override
        public void run() {
            float elapsed = SystemClock.uptimeMillis() - start;
            float t = elapsed/DURATION_MS;
            float v = interpolator.getInterpolation(t);

            double currentLat = (lat - startPosition.latitude) * v + 
       startPosition.latitude;
            double currentLng = (lng - startPosition.longitude) * v + 
   startPosition.longitude;
            marker.setPosition(new LatLng(currentLat, currentLng));

            // if animation is not finished yet, repeat
            if (t < 1) {
                handler.postDelayed(this, 16);
            }
        }
    });
  }

  private double zoomLevelToRadius(double zoomLevel) {
    // Approximation to fit circle into view
    return 16384000/Math.pow(2, zoomLevel);
}



 @Override
 public void onCameraChange(CameraPosition cameraPosition) {
    LatLng center = cameraPosition.target;
    double radius = zoomLevelToRadius(cameraPosition.zoom);
    this.searchCircle.setCenter(center);
     this.searchCircle.setRadius(radius);
    this.geoQuery.setCenter(new GeoLocation(center.latitude, 
  center.longitude));
    // radius in km
    this.geoQuery.setRadius(radius/1000);
}

@Override
public void onMapReady(GoogleMap googleMap) {

}
}

1 个答案:

答案 0 :(得分:0)

您正在使用此声明异步请求GoogleMap实例:

ng-options

当地图可供使用时,将在此回调中向您报告:

mapFragment.getMapAsync((OnMapReadyCallback) this);

您需要从活动的@Override public void onMapReady(GoogleMap googleMap) { } 方法中获取使用地图的所有初始化代码,并将其移至onCreate()或从onMapReady()调用的方法。例如:

onMapReady()

不清楚为什么要创建另一个应用实例。我不认为Geofire需要它。尝试使用默认值:

@Override
public void onMapReady(GoogleMap googleMap) {
    map = googleMap;
    //mMap = googleMap;  // not used?

    // all the map init stuff
    LatLng latLngCenter = new LatLng(INITIAL_CENTER.latitude,
            INITIAL_CENTER.longitude);
    this.searchCircle = this.map.addCircle(new
            CircleOptions().center(latLngCenter).radius(1000));
    this.searchCircle.setFillColor(Color.argb(66, 255, 0, 255));
    this.searchCircle.setStrokeColor(Color.argb(66, 0, 0, 0));
    this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter,
            INITIAL_ZOOM_LEVEL));
    this.map.setOnCameraChangeListener(this);
}
相关问题