地图片段不会加载相同的GPS位置和地图类型

时间:2015-09-21 05:44:10

标签: android google-maps android-fragments

我是Android编程的新手。我正在开发一个需要访问Google地图的Android项目。我的导航抽屉里有几个选项,包括谷歌地图位置。

因此,每当我第一次尝试加载地图时,它都能正常工作并加载具有当前GPS位置并定义了MAP TYPE的地图。

  

但每当我尝试切换到其他片段并返回Map时   片段,GPS功能和地图类型都不起作用。

需要帮助。提前致谢。我正在尝试修复它。 :)

我的代码如下。

  

我在这里尝试做的是每当用户触摸某个地方时,a   标记将放在该位置。

 public class AddCustomerLocationFragment extends Fragment implements
        LocationListener {

    private MapView mapView;
    private GoogleMap map;
    private Marker marker;
    private boolean markerAvailable;
    private Bundle bundle;
    Button btnReset, btnSetLocation;
    LocationManager locationManager;
    private View view;
    private double[] addCustomerLocation = new double[10];

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
     View v = inflater.inflate(R.layout.fragment_addcustomer_location,
     container, false);
     MapsInitializer.initialize(getActivity());
     mapView = (MapView) v.findViewById(R.id.map);
     btnReset = (Button) v.findViewById(R.id.btnReset);
     btnSetLocation = (Button) v.findViewById(R.id.btnSetLocation);
     mapView.onCreate(bundle);
     map.setMyLocationEnabled(true);
     locationManager = (LocationManager) getActivity()
     .getSystemService(
     Context.LOCATION_SERVICE);

     if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
     getGPS();
     } else {
     locationManager.requestLocationUpdates(
     LocationManager.NETWORK_PROVIDER, 1000, 10, this);
     }
     map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
     map.getUiSettings().setMyLocationButtonEnabled(true);
     map.getUiSettings().setCompassEnabled(true);

     map.setOnMapClickListener(new OnMapClickListener() {
     public void onMapClick(LatLng point) {
     Toast.makeText(
     getActivity(),
     "Latitude:" + point.latitude + ", Longitude:"
     + point.longitude, Toast.LENGTH_SHORT).show();
     addMarker(point);
     markerAvailable = true;
     }
     });
     btnSetLocation.setOnClickListener(new OnClickListener() {

     @Override
     public void onClick(View v) {
     // TODO Auto-generated method stub
     Toast.makeText(
     getActivity(),
     "Your current loaction is set to: Latitude:"
     + addCustomerLocation[0] + ", Longitude:"
     + addCustomerLocation[1], Toast.LENGTH_SHORT)
     .show();

     }
     });
     btnReset.setOnClickListener(new OnClickListener() {

     @Override
     public void onClick(View v) {
     // TODO Auto-generated method stub
     marker.remove();
     Toast.makeText(getActivity(), "Marker is Reset",
     Toast.LENGTH_SHORT).show();
     markerAvailable = false;
     }
     });

     // add a marker
     //
     return v;
     }
    private void getGPS() {
        // TODO Auto-generated method stub
        onLocationChanged(locationManager
                .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER));

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bundle = savedInstanceState;
        setRetainInstance(true);
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
        getGPS();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    private void outGPS() {
        // TODO Auto-generated method stub
        locationManager.removeUpdates(this);

    }

    @Override
    public void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    // @Override
    public void onLocationChanged(Location location) {
         // TODO Auto-generated method stub
        LatLng latLng = null;
        if (!markerAvailable) {
            latLng = new LatLng(location.getLatitude(), location.getLongitude());
            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
                    latLng, 18f);
            map.animateCamera(cameraUpdate);
            addMarker(latLng);
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(final String provider) {
        // TODO Auto-generated method stub
    }

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

    }

    private void addMarker(LatLng point) {
        map.clear();
        marker = map.addMarker(new MarkerOptions().position(
                new LatLng(point.latitude, point.longitude)).title(
                "Your Location!?"));
    }
}

1 个答案:

答案 0 :(得分:0)

以下是在片段中显示Google地图的代码。我已经使用LongClickListeners在地图上放置标记,您可以将其更改为onClick。

public class LocationFragment extends Fragment {

    MapView mMapView;
    private GoogleMap googleMap;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // inflat and return the layout
        View v = inflater.inflate(R.layout.fragment_location, container, false);
        mMapView = (MapView) v.findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume();// needed to get the map to display immediately

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        googleMap = mMapView.getMap();

        setUpMap();
        addingMarkers();
        addingCircles();
        setOnLongClickListenerForAddingNewMarkers();
        return v;
    }

    private void setUpMap() {

        // To show my location button on Google maps
        googleMap.setMyLocationEnabled(true);
        LocationManager locationManager = MainActivity.locationManager;
        Criteria criteria = new Criteria();

        final Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        if (location != null) {
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(), location.getLongitude()), 13));

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                    .zoom(17)                   // Sets the zoom
                    .bearing(90)                // Sets the orientation of the camera to east
                    .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                    .build();                   // Creates a CameraPosition from the builder
            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        }

    }

    private void addingMarkers() {
        // Adding marker to locations - This is a marker for Shipra Mall, which is close to my house. Zoom out to see the Marker
        double latitude = 28.6322269;
        double longitude = 77.3671697;

        // create marker
        MarkerOptions marker = new MarkerOptions().position(
                new LatLng(latitude, longitude)).title("Shipra Mall");

        // Changing marker icon
        marker.icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

        googleMap.addMarker(marker);
        // End - Adding marker to location


        // Another marker for District Center in Janakpuri
        double latitude2 = 28.6292303;
        double longitude2 = 77.0805496;

        MarkerOptions marker2 = new MarkerOptions().position(
                new LatLng(latitude2, longitude2)).title("District Center");
        marker2.icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        googleMap.addMarker(marker2);
        // End - Another marker for District Center in Janakpuri
    }

    private void addingCircles() {
        // Latitude and Longitude of Pacific Mall Subash Nagar
        double latitude = 28.6438947;
        double longitude = 77.1128296;

        // Adding a circle around Pacific Mall of 1000 meters radius.
        googleMap.addCircle(new CircleOptions()
                .center(new LatLng(latitude, longitude)) // Setting center point
                .radius(1000) // In meters
                .strokeColor(Color.RED) // Color of Border of Circle
                .fillColor(R.color.semi_blue) // Colour of fill, I've set the color to semi transparent blue which I've defined in colors.xml. For fill colour always use semi transparent colour.
                .strokeWidth(10)); // Width of red border.
    }

    private void setOnLongClickListenerForAddingNewMarkers() {
        googleMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

            @Override
            public void onMapLongClick(LatLng latLng) {
                // This method will add a new marker to wherever the user long clicks on the Map.
                // The title of the marker will be set based on what is located at that location.
                // The Geocoder.getFromLocation() method gets the address and details of the location.

                // Find Details of location
                Geocoder geocoder;
                List<Address> addresses = null;
                geocoder = new Geocoder(getActivity().getApplicationContext(), Locale.getDefault());

                try {
                    addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                assert addresses != null;
                String address = addresses.get(0).getAddressLine(0);
                String city = addresses.get(0).getLocality();
                String state = addresses.get(0).getAdminArea();
                String country = addresses.get(0).getCountryName();
                String postalCode = addresses.get(0).getPostalCode();
                String knownName = addresses.get(0).getFeatureName();
                // End - Find details of location

                // Add the new marker to the map
                MarkerOptions mo = new MarkerOptions();
                mo.position(latLng);
                mo.title(knownName + ", " + address + ", " + city + ", " + state + ", " + country);
                mo.icon(BitmapDescriptorFactory
                        .defaultMarker(new Random().nextFloat() * 360));
                googleMap.addMarker(mo);
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

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

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

然后我将此片段添加到我的MainActivity中。

您需要为清单添加一些权限,并指定您的Google Maps API密钥。清单文件是:

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

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <!--
 The ACCESS_COARSE/FINE_LOCATION 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"/>

    <permission
        android:name="com.arshad.map.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <!-- Permission to receive Google Maps -->
    <uses-permission android:name="com.arshad.map.permission.MAPS_RECEIVE"/>

    <!-- Maps API needs OpenGL ES 2.0. -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version"/>
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="@string/google_maps_key"/>

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

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

你很高兴。