一些CameraUpdateFactory问题

时间:2016-11-06 09:53:37

标签: android google-maps camera

我对CameraUpdateFactory有一些疑问。

  

Q1:

     

我正在尝试执行一个功能,当我单击按钮时,它执行函数“mapList()”

     

我的“mapList()”只是改变我的相机位置。 //运行成功但不能正常工作!!!!

     

所以我使用Google Map API的功能。

     

我的代码如下 - > MAPLIST()

    public void mapList(View view) {
    Intent intentMap = new Intent(this, MapsActivity.class);
    // start map component

    LatLng tagCYCU = new LatLng(24.956867, 121.242846);
    CameraPosition cameraPosition =
            new CameraPosition.Builder()
                    .target(tagCYCU)
                    .zoom(17)   
                    .build();

    CameraUpdateFactory.newLatLng(tagCYCU) ;
    CameraUpdateFactory.newCameraPosition(cameraPosition) ;
    startActivityForResult(intentMap, 0);
    }
  

Q2:

     

在我的地图活动中,我想尝试从其他片段中读取信息。因为我需要它来做某事。 (也改变相机位置)

     

所以我做这个代码,但总是“ERROR”// null object

     

我的代码如下 - > MapsActivity()

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

TextView getTextAddress ;
Spinner getName ;
String addrRestaurant = "", nameRestaurant = "" ;

private GoogleMap mMap;

private GoogleApiClient googleApiClient;

// Location
private LocationRequest locationRequest;

private Location currentLocation;

private Marker currentMarker, itemMarker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(map);
    mapFragment.getMapAsync(this);
}


/**
 * 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. In this case,
 * we just add a marker near Sydney, Australia.
 * 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;

    // ------------------------------- Get current location ---------------------------------
    LocationManager locationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
    }

    Location location = locationManager.getLastKnownLocation(locationManager
            .getBestProvider(criteria, false));
    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();
    LatLng currentHere = new LatLng(currentLatitude,currentLongitude) ;

    mMap.addMarker(new MarkerOptions().position(currentHere).title("Current Here"));

    // --------------------------------------------------------------------------------------

    // ---------------------------- Tag all restaurants from SQLite--------------------------


    String addrRestaurant = "" ;

    getTextAddress = (TextView)findViewById(R.id.textViewAddress);   
    // what i get , camera change to that position   
    // bur textViewAddress is in other fragments !!

    addrRestaurant = getTextAddress.getText().toString();

    DBHelper dbHelper = new DBHelper(this);
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    String selectQuery =  "SELECT  " +
            Restaurant.KEY_ID    + "," +
            Restaurant.KEY_name  + "," +
            Restaurant.KEY_type  + "," +
            Restaurant.KEY_price + "," +
            Restaurant.KEY_phone + "," +
            Restaurant.KEY_addr  + "," +
            Restaurant.KEY_score +
            " FROM " + Restaurant.TABLE;

    Cursor cursor = db.rawQuery(selectQuery, null);

    int sizeDB = (int) DatabaseUtils.queryNumEntries(db, "Restaurant");
    String infoAddress = "", infoName = "" ;

    for( int indexDB = 0 ; indexDB < sizeDB ; indexDB ++ ) {
        cursor.moveToPosition(indexDB);

        infoName = cursor.getString(cursor.getColumnIndex(Restaurant.KEY_name));
        infoAddress = cursor.getString(cursor.getColumnIndex(Restaurant.KEY_addr)) ;

        Geocoder geoCoder = new Geocoder(this);
        List<Address> addressLocation ;

        try {
            addressLocation = geoCoder.getFromLocationName(infoAddress, 1);
            double latitude = addressLocation.get(0).getLatitude();
            double longitude = addressLocation.get(0).getLongitude();
            LatLng tag = new LatLng(latitude, longitude);
            addMarker(tag, "Foody Restaurants",infoName ); // get mark !
            if(addrRestaurant.equals(infoAddress) == true){     

                // change camera position according to what i get fom other activity

                mMap.moveCamera(CameraUpdateFactory.newLatLng(tag));
                moveMap(tag);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    // --------------------------------------------------------------------------------------
}

private void moveMap(LatLng place) {
    CameraPosition cameraPosition =
            new CameraPosition.Builder()
                    .target(place)
                    .zoom(17)
                    .build();

    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}

private void addMarker(LatLng place, String title, String snippet) {
    BitmapDescriptor icon =
            BitmapDescriptorFactory.fromResource(R.mipmap.ic_tag);

    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(place)
            .title(title)
            .snippet(snippet)
            .icon(icon);

    mMap.addMarker(markerOptions);
}
  

Locat

     

处理:com.example.user.foody,PID:2896                                                                         java.lang.NullPointerException:

     

尝试在空对象引用上调用虚方法'java.lang.CharSequence android.widget.TextView.getText()'

     

at com.example.user.foody.MapsActivity.onMapReady(MapsActivity.java:121)

     

MapsActivity.java:121 - &gt; (addrRestaurant = getTextAddress.getText()。toString();)

     

在com.google.android.gms.maps.SupportMapFragment $ zza $ 1.zza(未知来源)

我真的需要帮助!!请:(谢谢..

1 个答案:

答案 0 :(得分:1)

您可以查看此sample on GitHub,了解如何更改地图的相机位置。单击 Animate To Sydney 按钮时,此代码段将运行。

public void onGoToSydney(View view) {
    if (!checkReady()) {
        return;
    }

    changeCamera(CameraUpdateFactory.newCameraPosition(SYDNEY), new CancelableCallback() {
        @Override
        public void onFinish() {
            Toast.makeText(getBaseContext(), "Animation to Sydney complete", Toast.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(getBaseContext(), "Animation to Sydney canceled", Toast.LENGTH_SHORT)
                    .show();
        }
    });
}

关于Fragments,请查看有关将Fragment对象添加到将处理地图的Activity的文档。

请检查此SO post,了解如何解决问题以及导致NullPointerException的可能原因。

  

&#34;避免此类异常的最佳方法是在自己不创建对象时始终检查null。&#34; 如果调用者传递null,但为null对于该方法来说,这不是一个有效的参数,那么将异常抛回调用者是正确的,因为它是调用者的错误。