2015-05-07 3 views
0

Это мой код:Почему google map API v2 показывает пустую карту?

public class Map extends ActionBarActivity{ 

    GoogleMap map; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_map); 
     getSupportActionBar().setDisplayShowHomeEnabled(true); 
     getSupportActionBar().setLogo(R.drawable.ic_launcher); 
     getSupportActionBar().setDisplayUseLogoEnabled(true); 
     // Initializing 
     int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); 
     markerPoints = new ArrayList<LatLng>(); 
     // Showing status 
     if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available 

      int requestCode = 10; 
      Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode); 
      dialog.show(); 

     }else { // Google Play Services are available 

      // Getting reference to the SupportMapFragment of activity_main.xml 
      SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
      // Getting GoogleMap object from the fragment 
      map = fm.getMap(); 

      if (map == null) { 
       Toast.makeText(getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show(); 
      } 

      // Enabling MyLocation Layer of Google Map 
      map.setMyLocationEnabled(true); 

     } 
    } 
} 

Я уверен, что мой ключ API и разрешение прав. Потому что я использовал его для этого проекта в прошлом, и он сработал. Но я не знаю, почему он сейчас не работает. Может кто-нибудь показать мне, почему, пожалуйста? Я изменил свой ключ API, но он все еще не работает.

+0

Какая ошибка вы видите? код статуса? –

+0

Я использую реальный прибор. Поэтому я не вижу код состояния. @Sunil B N. – Hades10

+0

Но это сработало в прошлом. @Sunil B N – Hades10

ответ

0

Это полный код GoogleMaps API v2 и работа для меня:

MapsActivity.java

public class MapsActivity extends FragmentActivity implements LocationListener { 

private GoogleMap mMap; // Might be null if Google Play services APK is not available. 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps); 
    setUpMapIfNeeded(); 
    // Getting Google Play availability status 
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext()); 

    // Showing status 
    if(status!= ConnectionResult.SUCCESS){ // Google Play Services are not available 

     int requestCode = 10; 
     Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode); 
     dialog.show(); 

    }else { // Google Play Services are available 

     // Enabling MyLocation Layer of Google Map 
     mMap.setMyLocationEnabled(true); 

     // My location button 
     mMap.getUiSettings().setMyLocationButtonEnabled(true); 

     mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

     mMap.getUiSettings().setCompassEnabled(true); 

     mMap.getUiSettings().setZoomControlsEnabled(true); 

     // Getting LocationManager object from System Service LOCATION_SERVICE 
     LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 

     // Creating a criteria object to retrieve provider 
     Criteria criteria = new Criteria(); 

     // Getting the name of the best provider 
     String provider = locationManager.getBestProvider(criteria, true); 

     // Getting Current Location 
     Location location = locationManager.getLastKnownLocation(provider); 

     // latitude and longitude 
     double latitude = latitude; 
     double longitude = longitude; 

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

     // Changing marker icon 
     marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_maps)); 

     // adding marker 
     mMap.addMarker(marker); 

     // changing camera map 
     CameraPosition cameraPosition = new CameraPosition.Builder().target(
       new LatLng(latitude, longitude)).zoom(11).build(); 

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

     if (location != null) { 
      onLocationChanged(location); 
     } 
     locationManager.requestLocationUpdates(provider, 20000, 10, this); 

    } 
} 

@Override 
public void onLocationChanged(Location location) { 
    // Getting latitude of the current location 
    double latitude = location.getLatitude(); 

    // Getting longitude of the current location 
    double longitude = location.getLongitude(); 

    // Creating a LatLng object for the current location 
    LatLng latLng = new LatLng(latitude, longitude); 

    // Showing the current location in Google Map 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 

    // Zoom in the Google Map 
    mMap.animateCamera(CameraUpdateFactory.zoomTo(12)); 
} 

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

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

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

@Override 
protected void onResume() { 
    super.onResume(); 
    setUpMapIfNeeded(); 
} 

/** 
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly 
* installed) and the map has not already been instantiated.. This will ensure that we only ever 
* call {@link #setUpMap()} once when {@link #mMap} is not null. 
* <p/> 
* If it isn't installed {@link SupportMapFragment} (and 
* {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to 
* install/update the Google Play services APK on their device. 
* <p/> 
* A user can return to this FragmentActivity after following the prompt and correctly 
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not 
* have been completely destroyed during this process (it is likely that it would only be 
* stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this 
* method in {@link #onResume()} to guarantee that it will be called. 
*/ 
private void setUpMapIfNeeded() { 
    // Do a null check to confirm that we have not already instantiated the map. 
    if (mMap == null) { 
     // Try to obtain the map from the SupportMapFragment. 
     mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
       .getMap(); 
     // Check if we were successful in obtaining the map. 
     if (mMap != null) { 
      setUpMap(); 
     } 
    } 
} 

/** 
* This is where we can add markers or lines, add listeners or move the camera. In this case, we 
* just add a marker near Africa. 
* <p/> 
* This should only be called once and when we are sure that {@link #mMap} is not null. 
*/ 

и этого activity_maps.xml:

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

мая может помочь

+0

Что такое '// широта и долгота double latitude = широта; double longitude = longitude; 'и' setUpMap(); '? @Agung Harrys – Hades10

+0

@ Hades10 вы можете удалить его –

0

У меня был этот выпуск ...

  1. Правильно ли настроен ключ API? Удостоверьтесь, что у вас есть правильный sha1 или у вас нет определенных, чтобы сделать его общедоступным.
  2. Убедитесь, что API Карт включен. Вы должны войти в нее и включить ее.

Затем проверить его с помощью этого простого кода:

общественный конечный класс MainActivity расширяет FragmentActivity {

static final LatLng HAMBURG = new LatLng(53.558, 9.927); 
    static final LatLng KIEL = new LatLng(53.551, 9.993); 
    private GoogleMap map; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)) 
     .getMap(); 
    map.getUiSettings().setMyLocationButtonEnabled(true); 
    map.addMarker(new MarkerOptions().position(HAMBURG) 
     .title("Hamburg")); 
    map.addMarker(new MarkerOptions() 
     .position(KIEL) 
     .title("Kiel") 
     .snippet("Kiel is cool") 
     .icon(BitmapDescriptorFactory 
      .fromResource(R.drawable.ic_launcher))); 

    // Move the camera instantly to hamburg with a zoom of 15. 
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15)); 

    // Zoom in, animating the camera. 
    map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); 
    } 

манифеста:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/> 
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 

    <activity 
     android:name=".SplashActivity" 
     android:label="@string/app_name" 
     android:theme="@android:style/Theme.NoTitleBar.Fullscreen" 
     android:screenOrientation="portrait" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

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

    <activity 
      android:name=".MainActivity" 
      android:label="@string/app_name" 
      android:theme="@android:style/Theme.NoTitleBar.Fullscreen" 
      android:configChanges="keyboardHidden|orientation|screenSize" 
      android:screenOrientation="portrait" 
      android:windowSoftInputMode="stateHidden" /> 

    <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="API_KEY_HERE" /> 

Планировка:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity" > 

    <fragment 
     android:id="@+id/map" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     class="com.google.android.gms.maps.MapFragment" /> 

</RelativeLayout> 
Смежные вопросы