2013-12-24 2 views
0

Я работал с прошлых часов, чтобы получить карту работы Google, но кажется, что я делаю некоторые вещи неправильно ..Android Google Map Версия 2

Позвольте мне поделиться с вами информацией ..

Вот моя работа ..

MainActivity.java класс

import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.Toast; 

import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.MapFragment; 
import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
import com.google.android.gms.maps.model.CameraPosition; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 

public class MainActivity extends Activity { 

    // Google Map 
    private GoogleMap googleMap; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     try { 
      // Loading map 
      initilizeMap(); 

      // Changing map type 
      googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
      // googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 
      // googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); 
      // googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); 
      // googleMap.setMapType(GoogleMap.MAP_TYPE_NONE); 

      // Showing/hiding your current location 
      googleMap.setMyLocationEnabled(true); 

      // Enable/Disable zooming controls 
      googleMap.getUiSettings().setZoomControlsEnabled(false); 

      // Enable/Disable my location button 
      googleMap.getUiSettings().setMyLocationButtonEnabled(true); 

      // Enable/Disable Compass icon 
      googleMap.getUiSettings().setCompassEnabled(true); 

      // Enable/Disable Rotate gesture 
      googleMap.getUiSettings().setRotateGesturesEnabled(true); 

      // Enable/Disable zooming functionality 
      googleMap.getUiSettings().setZoomGesturesEnabled(true); 

      double latitude = 17.385044; 
      double longitude = 78.486671; 

      // lets place some 10 random markers 
      for (int i = 0; i < 10; i++) { 
       // random latitude and logitude 
       double[] randomLocation = createRandLocation(latitude, 
         longitude); 

       // Adding a marker 
       MarkerOptions marker = new MarkerOptions().position(
         new LatLng(randomLocation[0], randomLocation[1])) 
         .title("Hello Maps " + i); 

       Log.e("Random", "> " + randomLocation[0] + ", " 
         + randomLocation[1]); 

       // changing marker color 
       if (i == 0) 
        marker.icon(BitmapDescriptorFactory 
          .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)); 
       if (i == 1) 
        marker.icon(BitmapDescriptorFactory 
          .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); 
       if (i == 2) 
        marker.icon(BitmapDescriptorFactory 
          .defaultMarker(BitmapDescriptorFactory.HUE_CYAN)); 
       if (i == 3) 
        marker.icon(BitmapDescriptorFactory 
          .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); 
       if (i == 4) 
        marker.icon(BitmapDescriptorFactory 
          .defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
       if (i == 5) 
        marker.icon(BitmapDescriptorFactory 
          .defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)); 
       if (i == 6) 
        marker.icon(BitmapDescriptorFactory 
          .defaultMarker(BitmapDescriptorFactory.HUE_RED)); 
       if (i == 7) 
        marker.icon(BitmapDescriptorFactory 
          .defaultMarker(BitmapDescriptorFactory.HUE_ROSE)); 
       if (i == 8) 
        marker.icon(BitmapDescriptorFactory 
          .defaultMarker(BitmapDescriptorFactory.HUE_VIOLET)); 
       if (i == 9) 
        marker.icon(BitmapDescriptorFactory 
          .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)); 

       googleMap.addMarker(marker); 

       // Move the camera to last position with a zoom level 
       if (i == 9) { 
        CameraPosition cameraPosition = new CameraPosition.Builder() 
          .target(new LatLng(randomLocation[0], 
            randomLocation[1])).zoom(15).build(); 

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

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 

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

    /** 
    * function to load map If map is not created it will create it for you 
    * */ 
    private void initilizeMap() { 
     if (googleMap == null) { 
      googleMap = ((MapFragment) getFragmentManager().findFragmentById(
        R.id.map)).getMap(); 

      // check if map is created successfully or not 
      if (googleMap == null) { 
       Toast.makeText(getApplicationContext(), 
         "Sorry! unable to create maps", Toast.LENGTH_SHORT) 
         .show(); 
      } 
     } 
    } 

    /* 
    * creating random postion around a location for testing purpose only 
    */ 
    private double[] createRandLocation(double latitude, double longitude) { 

     return new double[] { latitude + ((Math.random() - 0.5)/500), 
       longitude + ((Math.random() - 0.5)/500), 
       150 + ((Math.random() - 0.5) * 10) }; 
    } 
} 

Вот мой файл Xml ..

<?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.SupportMapFragment" /> 

</RelativeLayout> 

и вот мой файл манифеста ..

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

    <permission 
     android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE" 
     android:protectionLevel="signature" /> 

    <uses-permission android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE" /> 

    <uses-sdk 
     android:minSdkVersion="9" 
     android:targetSdkVersion="18" /> 

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

    <!-- Required to show current location --> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

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

    <!-- Requires OpenGL ES version 2 --> 
    <uses-feature 
     android:glEsVersion="0x00020000" 
     android:required="true" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name"> 
     <activity 
      android:name="info.androidhive.googlemapsv2.MainActivity" 
      android:label="@string/app_name" 
      android:theme="@style/AppBaseTheme"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

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

     <!-- Goolge API Key --> 
     <meta-data 
      android:name="com.google.android.maps.v2.API_KEY" 
      android:value="AIzaSyBZMlkOv4sj-M5JO9p6wksdax4TEjDVLgo" /> 
    </application> 

</manifest> 

Я парование AndroidHive учебник < http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/>

ошибка, что я получаю ..

Мой журнал ошибок ::

12-24 13:32:56.062: E/AndroidRuntime(7014): FATAL EXCEPTION: main 
12-24 13:32:56.062: E/AndroidRuntime(7014): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.googlemapsv2/info.androidhive.googlemapsv2.MainActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.app.ActivityThread.access$1500(ActivityThread.java:117) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.os.Handler.dispatchMessage(Handler.java:99) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.os.Looper.loop(Looper.java:130) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.app.ActivityThread.main(ActivityThread.java:3687) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at java.lang.reflect.Method.invokeNative(Native Method) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at java.lang.reflect.Method.invoke(Method.java:507) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at dalvik.system.NativeStart.main(Native Method) 
12-24 13:32:56.062: E/AndroidRuntime(7014): Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:581) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.view.LayoutInflater.rInflate(LayoutInflater.java:623) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.view.LayoutInflater.inflate(LayoutInflater.java:408) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:209) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.app.Activity.setContentView(Activity.java:1657) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at info.androidhive.googlemapsv2.MainActivity.onCreate(MainActivity.java:24) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  ... 11 more 
12-24 13:32:56.062: E/AndroidRuntime(7014): Caused by: java.lang.ClassNotFoundException: android.view.fragment in loader dalvik.system.PathClassLoader[/data/app/info.androidhive.googlemapsv2-2.apk] 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at java.lang.ClassLoader.loadClass(ClassLoader.java:551) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at java.lang.ClassLoader.loadClass(ClassLoader.java:511) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.view.LayoutInflater.createView(LayoutInflater.java:471) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.view.LayoutInflater.onCreateView(LayoutInflater.java:549) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:66) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568) 
12-24 13:32:56.062: E/AndroidRuntime(7014):  ... 20 more 

Я отнесся к каждой части в tutoria л. Также я консультировался с другими сайтами, включая Google.

Любая помощь по этому поводу будет высоко оценена. Дайте мне знать, если мне нужно что-то добавить больше.

Спасибо!

+0

укажите имя фрагменту. как android: name = "com.example.googlemap.MainActivity" – user1728071

+0

добавлена ​​библиотека google_play_services? – deniz

+0

Проверьте http://stackoverflow.com/questions/18235838/binary-xml-file-line-15-error-inflating-class-fragment/18307228#18307228 –

ответ

0

Убедитесь, что вы добавили библиотеку игровых сервисов google и библиотеку android-support-v4 для фрагментов карты поддержки.

enter image description here

enter image description here

Также в вашем методе InitializeMap() как вы используете SupportMapFragment так же, как вам нужно инициализировать карту с SupportMapFragment только не с MapFragment.Измените код, как показано ниже:

private void initilizeMap() { 
    if (googleMap == null) { 
     googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
       R.id.map)).getMap(); 

     // check if map is created successfully or not 
     if (googleMap == null) { 
      Toast.makeText(getApplicationContext(), 
        "Sorry! unable to create maps", Toast.LENGTH_SHORT) 
        .show(); 
     } 
    } 
} 

Редакцией:

В вашем MainActivity, кроме расширения Activity попытаться расширяет FragmentActivity ниже

public class MainActivity extends FragmentActivity { 
+0

Да, мне тоже понравилось .. Нет sucess – AndroidHacker

+0

Вы изменили инициализацию своей карты в методе 'initilizeMap()', как я показал? – GrIsHu

+0

Я считаю, что я делаю то же самое, что и u .. – AndroidHacker

0
<?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.**SupportMapFragment**" /> 

</RelativeLayout> 

В вашем XML вы ARER с помощью SupportMapFragment но в коде, который вы используете getFragmentManager(), вы должны использовать getSupportFragmentManager()

private void initilizeMap() { 
     if (googleMap == null) { 
      googleMap = ((MapFragment) `getSupportFragmentManager`().findFragmentById(
        R.id.map)).getMap(); 

      // check if map is created successfully or not 
      if (googleMap == null) { 
       Toast.makeText(getApplicationContext(), 
         "Sorry! unable to create maps", Toast.LENGTH_SHORT) 
         .show(); 
      } 
     } 
    } 
+0

Использование того же самого .. для получения поддержки, но без sucess – AndroidHacker

0

правой кнопкой мыши на проекте выберите Android Tools -> Add Support Library, чтобы добавить библиотеки поддержки для вашего проекта

и в вашей деятельности изменить Activity к android.support.v4.app.FragmentActivity

public class MainActivity extends android.support.v4.app.FragmentActivity{ 

и изменить инициализацию этой

if (googleMap == null) { 
    googleMap = ((SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map)).getMap(); 
} 

Добавить этот импорт также

import com.google.android.gms.maps.SupportMapFragment; 
+0

Я думаю, что в моем файле или файле манифеста есть проблема. . Я делаю то же самое, что и U, предлагая – AndroidHacker

+0

. Я также использую SupportMapFragment – AndroidHacker

+0

@AndroidHacker: код, который вы разместили здесь, отличается, ваша деятельность расширяет 'Activity', а не' FragmentActivity', XML кажется прекрасным –

0

У меня возникла такая же проблема, когда я это сделал. Но после этого это сработало для меня. Проверьте мой код для отображения Карты. Как только вы получите карту, вы можете перейти к следующему шагу.

activity_main.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" > 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Button"/> 

    <fragment 
     android:id="@+id/map" 
     android:name="com.example.googlemap.MainActivity" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     class="com.google.android.gms.maps.SupportMapFragment" /> 

</LinearLayout> 

MainActivity.java

package com.example.googlemap; 

import android.os.Bundle; 
import android.view.Menu; 

public class MainActivity extends android.support.v4.app.FragmentActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

} 

AndroidManifest.xml

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

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="17" /> 

    <permission 
     android:name="com.example.googlemap.permission.MAPS_RECEIVE" 
     android:protectionLevel="signature" /> 

    <uses-feature 
     android:glEsVersion="0x00020000" 
     android:required="true" /> 

    <uses-permission android:name="com.example.googlemap.permission.MAPS_RECEIVE" /> 
    <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_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" > 
     <uses-library android:name="com.google.android.maps" /> 
     <activity 
      android:name="com.example.googlemap.MainActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <meta-data 
      android:name="com.google.android.maps.v2.API_KEY" 
      android:value="AIzaSyAP8K9rStcxbXNO7jRD_FhzDiNbB8AWEwA"/> 
    </application> 

</manifest> 
0
  1. Изменение макета

класс = "com.google.android.maps.SupportMapFragment" к класса = "com.google.android.gms.maps.SupportMapFragment"

  1. Вы должны определить это в вашем MainFest файл под тег приложения

    <application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name"> 
    
    <uses-library android:name="com.google.android.maps" /> 
    
    <activity 
        android:name="com.example.androidhackergooglemap.MainActivity" 
        android:label="@string/app_name" 
        android:theme="@style/AppBaseTheme"> 
        <intent-filter> 
         <action android:name="android.intent.action.MAIN" /> 
    
         <category android:name="android.intent.category.LAUNCHER" /> 
        </intent-filter> 
    </activity> 
    
    <!-- Goolge API Key --> 
    <meta-data 
        android:name="com.google.android.maps.v2.API_KEY" 
        android:value="AIzaSyCv_j5f8gEkjjtU0BLPaLsz1iWzIOyUCBg" />