2015-09-21 102 views
-1

我是Android編程新手。我正在開發一個需要訪問Google地圖的Android項目。我有一個包含谷歌地圖位置的選項的導航抽屜。Map Fragment不加載相同的GPS位置和地圖類型

因此,無論何時我第一次嘗試加載地圖時,它都能正常工作,並使用當前GPS位置和定義的MAP TYPE加載地圖。

但是,每當我嘗試切換到其他片段並回到地圖 片段時,GPS功能和地圖類型不起作用。

需要幫助。提前致謝。我正在嘗試修復它。 :)

我的代碼如下。

我想在這裏做的是,每當用戶觸摸的地方,一個 標記將被放置在該位置。

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!?")); 
    } 
} 
+0

有什麼問題? –

+0

當我從地圖片段切換到另一個片段並返回到地圖片段時,地圖不會以HYBRID類型加載,也不會有我定義的默認GPS位置。 –

回答

0

這裏是代碼片段中顯示谷歌地圖。我已經讓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地圖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> 

而且你很好走。

+0

MainActivity.locationManager在這裏做什麼? –

+0

它獲得定位服務。 'locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);' – Rachit

+0

此代碼不適用於我。我的代碼第一次給我地圖,但在恢復地圖片段後,它不起作用。那就是問題所在。 –

相關問題