0

我不确定出了什么问题,但我试图让我的谷歌地图片段在开始时放大到特定位置。由于某种原因,它无法正常工作,并且默认情况下仍会放大到非洲。这是我的代码。

public class OutbreakMap extends Activity implements LocationListener {
    double lat=50;
    double longi=50;
    private LocationManager locationManager;
    private String provider;
    private MapFragment mMapFragment;
    private GoogleMap googleMap;


    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.location);

        // Get the location manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);

         // Check if enabled and if not send user to the GSP settings
         // Better solution would be to display a dialog and suggesting to
        // go to the settings
        if (!enabled) {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

            // set title
            alertDialogBuilder.setTitle("Turn On Your GPS");

            // set dialog message
            alertDialogBuilder
                    .setMessage("Please turn on your GPS to track sickness in your area!")
                    .setCancelable(false)
                    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            // current activity
                            OutbreakMap.this.finish();
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton("No",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();

        }
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            onLocationChanged(location);
        } else {
            Toast.makeText(getApplicationContext(),"Location not found",Toast.LENGTH_SHORT);
        }

        mMapFragment = MapFragment.newInstance();
        FragmentTransaction fragmentTransaction =
                getFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.map, mMapFragment);
        fragmentTransaction.commit();
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();
        setUpMapIfNeeded();
        googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        if(location != null)  {
            lat=location.getLatitude();
            longi=location.getLongitude();
        }

        CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(lat,longi))      // Sets the center of the map to Mountain View
                    .zoom(17)                   // Sets the zoom
                  // Sets the tilt of the camera to 30 degrees
                    .build();                   // Creates a CameraPosition from the builder
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        UiSettings uiSettings=googleMap.getUiSettings();
        uiSettings.setAllGesturesEnabled(false);
        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            onLocationChanged(location);
        } else {
        Toast.makeText(getApplicationContext(),"Couldn't Find Location",Toast.LENGTH_SHORT);
        }



        ParseGeoPoint userLoc= new ParseGeoPoint(lat,longi);
        ParseQuery query= new ParseQuery("Outbreak");
        query.whereWithinMiles("location",userLoc,1);
        query.findInBackground(new FindCallback() {
            public void done(List<ParseObject> objects, ParseException e) {
                if (e == null) {
                GetOutbreaks.getOutBreaksNearMe(googleMap,lat,longi,objects);
                Toast.makeText(getApplicationContext(),"Recieved Outbreak Data",Toast.LENGTH_SHORT);
                } else {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"Could Not Download    Data",Toast.LENGTH_SHORT);
                }
            }

        });


//        moveToPrescription();
//        moveToPrescription();
    }

    /* Request updates at startup */
    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        int lat = (int) (location.getLatitude());
        int lng = (int) (location.getLongitude());
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    }

    public void moveToPrescription(){
        Intent intent = new Intent(this,Prescription.class);
        startActivity(intent);

    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (googleMap != null) {
                // The Map is verified. It is now safe to manipulate the map.

            }
        }
    }

}

另外,这是我的地图片段活动的 xml 布局

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:orientation="vertical" >

        <fragment xmlns:android="http://schemas.android.com/apk/res/android"
                  android:id="@+id/map"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:name="com.google.android.gms.maps.MapFragment"/>

    </LinearLayout>

还有我的 Android 清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.parse.starter"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15"/>
    <permission
            android:name="com.example.mapdemo.permission.MAPS_RECEIVE"
            android:protectionLevel="signature"/>
    <uses-permission android:name="com.example.mapdemo.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <!-- The following two permissions are not required to use
         Google Maps Android API v2, but are recommended. -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <application
        android:name="ParseApplication"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ParseStarterProjectActivity"

            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Register"/>
        <activity android:name=".Login"/>
        <activity android:name=".Home"/>
        <activity android:name=".OutbreakMap"/>
        <activity android:name=".Prescription"/>
        <activity android:name=".MyPrescriptions"/>
        <receiver android:name=".AlarmManagerBroadcastReceiver"></receiver>

        <uses-library android:name="com.google.android.maps"/>
        <meta-data
                android:name="com.google.android.maps.v2.API_KEY"
                android:value="My Maps API Key is Here"/>
    </application>
    <uses-feature android:glEsVersion="0x00020000" android:required="true" />

</manifest>

LogCat 没有显示任何错误。谢谢您的帮助!

4

3 回答 3

0

您将在代码中添加第二个 SupportMapFragment 在与 GoogleMap 交互的 Fragment 之上。只需删除不必要的代码。

于 2013-04-04T20:02:20.417 回答
0

使用 SupportMapFragment

      <fragment  
      android:id="@+id/map"
      android:name="com.google.android.gms.maps.SupportMapFragment"
      />

谷歌地图通用;

gm = ((SupportMapFragment(getSupportFragmentManager().findFragmentById(R.id.map))).getMap();

于 2013-04-18T09:31:09.480 回答
0

注释掉以下代码行

mMapFragment = MapFragment.newInstance();
    FragmentTransaction fragmentTransaction =
            getFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.map, mMapFragment);
    fragmentTransaction.commit();

它会像魅力一样发挥作用。

于 2015-07-09T06:53:23.497 回答