Фрагмент карты Google не работает в Android

Я сделал очень простую демонстрационную программу для просмотра карты Android (api v2), сославшись на следующую ссылку, но моя программа не показывает карту. Она не работает. Пожалуйста, помогите мне, мой код выглядит следующим образом:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"/>

main.java

    package com.example.mymap;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.support.v4.app.FragmentActivity; 

public class MainActivity extends FragmentActivity {


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

    }



}

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mymap"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>


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

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

    <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="com.example.mymap.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mymap.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="AIzaSyCuS-daQYgOZsmbIBYUTCl0P5tV0GTnjrI" />
    </application>

</manifest>

person jigar    schedule 04.07.2013    source источник
comment
Измените свою активность на fragmentActivity   -  person Shani Goriwal    schedule 04.07.2013
comment
@ShaniGoriwal-В каком месте? Я не могу понять...!   -  person jigar    schedule 04.07.2013
comment
в котором вы делаете кодирование для карты Google   -  person Shani Goriwal    schedule 04.07.2013
comment
не работает .. пожалуйста, посмотрите мой обновленный код ..!   -  person jigar    schedule 04.07.2013


Ответы (6)


Пожалуйста, попробуйте использовать мой рабочий код.

Сначала импортируйте проект библиотеки сервисов Google Play из /Android/android-sdk-linux/extras/google/google_play_services, а затем создайте новый проект и напишите этот код.

//Main Activity
package in.wptrafficanalyzer.multipleproximitymapv2;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {

GoogleMap googleMap;
LocationManager locationManager;
PendingIntent pendingIntent;
SharedPreferences sharedPreferences;
int locationCount = 0;

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

    // 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

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

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

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

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

        // Opening the sharedPreferences object
        sharedPreferences = getSharedPreferences("location", 0);

        // Getting number of locations already stored
        locationCount = sharedPreferences.getInt("locationCount", 0);

        // Getting stored zoom level if exists else return 0
        String zoom = sharedPreferences.getString("zoom", "0");

        // If locations are already saved
        if (locationCount != 0) {

            String lat = "";
            String lng = "";

            // Iterating through all the locations stored
            for (int i = 0; i < locationCount; i++) {

                // Getting the latitude of the i-th location
                lat = sharedPreferences.getString("lat" + i, "0");

                // Getting the longitude of the i-th location
                lng = sharedPreferences.getString("lng" + i, "0");

                // Drawing marker on the map
                drawMarker(new LatLng(Double.parseDouble(lat),
                        Double.parseDouble(lng)));

                // Drawing circle on the map
                drawCircle(new LatLng(Double.parseDouble(lat),
                        Double.parseDouble(lng)));
            }

            // Moving CameraPosition to last clicked position
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(
                    Double.parseDouble(lat), Double.parseDouble(lng))));

            // Setting the zoom level in the map on last position is clicked
            googleMap.animateCamera(CameraUpdateFactory.zoomTo(Float
                    .parseFloat(zoom)));
        }

        googleMap.setOnMapClickListener(new OnMapClickListener() {

            public void onMapClick(LatLng point) {

                // Incrementing location count
                locationCount++;

                // Drawing marker on the map
                drawMarker(point);

                // Drawing circle on the map
                drawCircle(point);

                // This intent will call the activity ProximityActivity
                Intent proximityIntent = new Intent(
                        "in.wptrafficanalyzer.activity.proximity");

                // Passing latitude to the PendingActivity
                proximityIntent.putExtra("lat", point.latitude);

                // Passing longitude to the PendingActivity
                proximityIntent.putExtra("lng", point.longitude);

                // Creating a pending intent which will be invoked by
                // LocationManager when the specified region is
                // entered or exited
                pendingIntent = PendingIntent.getActivity(getBaseContext(),
                        0, proximityIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

                // Setting proximity alert
                // The pending intent will be invoked when the device enters
                // or exits the region 20 meters
                // away from the marked point
                // The -1 indicates that, the monitor will not be expired
                locationManager.addProximityAlert(point.latitude,
                        point.longitude, 20, -1, pendingIntent);

                /**
                 * Opening the editor object to write data to
                 * sharedPreferences
                 */
                SharedPreferences.Editor editor = sharedPreferences.edit();

                // Storing the latitude for the i-th location
                editor.putString(
                        "lat" + Integer.toString((locationCount - 1)),
                        Double.toString(point.latitude));

                // Storing the longitude for the i-th location
                editor.putString(
                        "lng" + Integer.toString((locationCount - 1)),
                        Double.toString(point.longitude));

                // Storing the count of locations or marker count
                editor.putInt("locationCount", locationCount);

                /** Storing the zoom level to the shared preferences */
                editor.putString("zoom",
                        Float.toString(googleMap.getCameraPosition().zoom));

                /** Saving the values stored in the shared preferences */
                editor.commit();

                Toast.makeText(getBaseContext(),
                        "Proximity Alert is added", Toast.LENGTH_SHORT)
                        .show();

            }
        });

        googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {

            public void onMapLongClick(LatLng point) {
                Intent proximityIntent = new Intent(
                        "in.wptrafficanalyzer.activity.proximity");

                pendingIntent = PendingIntent.getActivity(getBaseContext(),
                        0, proximityIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

                // Removing the proximity alert
                locationManager.removeProximityAlert(pendingIntent);

                // Removing the marker and circle from the Google Map
                googleMap.clear();

                // Opening the editor object to delete data from
                // sharedPreferences
                SharedPreferences.Editor editor = sharedPreferences.edit();

                // Clearing the editor
                editor.clear();

                // Committing the changes
                editor.commit();

                Toast.makeText(getBaseContext(),
                        "Proximity Alert is removed", Toast.LENGTH_LONG)
                        .show();
            }
        });
    }
}

private void drawCircle(LatLng point) {

    // Instantiating CircleOptions to draw a circle around the marker
    CircleOptions circleOptions = new CircleOptions();

    // Specifying the center of the circle
    circleOptions.center(point);

    // Radius of the circle
    circleOptions.radius(20);

    // Border color of the circle
    circleOptions.strokeColor(Color.BLACK);

    // Fill color of the circle
    circleOptions.fillColor(0x30ff0000);

    // Border width of the circle
    circleOptions.strokeWidth(2);

    // Adding the circle to the GoogleMap
    googleMap.addCircle(circleOptions);

}

private void drawMarker(LatLng point) {
    // Creating an instance of MarkerOptions
    MarkerOptions markerOptions = new MarkerOptions();

    // Setting latitude and longitude for the marker
    markerOptions.position(point);

    // Adding InfoWindow title
    markerOptions.title("Location Coordinates");

    // Adding InfoWindow contents
    markerOptions.snippet(Double.toString(point.latitude) + ","
            + Double.toString(point.longitude));

    // Adding marker on the Google Map
    googleMap.addMarker(markerOptions);
}
}

// Activity_main

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


//Manifiest

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

<permission
    android:name="in.wptrafficanalyzer.multipleproximitymapv2.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="in.wptrafficanalyzer.multipleproximitymapv2.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" />

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

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="in.wptrafficanalyzer.multipleproximitymapv2.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>
    <activity
        android:name=".ProximityActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="in.wptrafficanalyzer.activity.proximity" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:name=".NotificationView"
        android:label="@string/app_name" >
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyD2fSGTakDlROXxr2IJeDH6f31b7BSc0F8" />
</application>

person nilesh patel    schedule 04.07.2013
comment
вы разместили код своего приложения вместо того, чтобы указать на ошибки в коде операции и ключ карты вашего приложения. - person Raghunandan; 04.07.2013
comment
developers.google.com/maps/documentation/android/start... Я использовал приведенную выше ссылку... возможно ли это так? Я выполнил указанные шаги, но не работает...! - person jigar; 04.07.2013

Добавьте библиотеку в файл AndroidManifest:

  <uses-library
        android:name="com.google.android.maps"
        android:required="true" />
person Shani Goriwal    schedule 04.07.2013
comment
@ Шани-все то же самое произошло ...! - person jigar; 04.07.2013
comment
Итак, вы добавили проект библиотеки для этого? А вы установили библиотеку Google Play из Android SDK ?? - person Shani Goriwal; 04.07.2013
comment
но ссылка developers.google.com/maps/documentation/android/start не работает ах какой шаг...! - person jigar; 04.07.2013
comment
@jigar, вы проверили ссылки в моем комментарии, они указывают вам на упомянутые шаги. Посмотрите на документы внимательно. Проверьте мой комментарий, где первая ссылка показывает, как загрузить и настроить. вторая ссылка указывает вам шаги. Проверьте первый шаг в обзоре. Он просит вас настроить сервисы Google Play. Загрузите и настройте SDK сервисов Google Play - person Raghunandan; 04.07.2013
comment
Вы должны сначала установить проект библиотеки Google из Android SDK, а затем импортировать его в eclipse и добавить в качестве проекта библиотеки в свой проект. - person Shani Goriwal; 04.07.2013
comment
@ShaniGoriwal Я действительно не знаю, но понимаете ли вы, что моды удалили некоторые из ваших ответов, потому что вы даете двойные ответы? Еще раз: пожалуйста, прекратите создавать более одного ответа на вопрос! ТАК работает иначе! Обновите свой первый ответ, чтобы отразить изменения или улучшения, но НЕ создавайте второй или третий ответ на тот же вопрос! - person WarrenFaith; 04.07.2013

Просто проверьте это:

package com.example.mymap;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.support.v4.app.FragmentActivity; 

public class MainActivity extends FragmentActivity {


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


    FragmentManager myFM = .getSupportFragmentManager();

    SupportMapFragment myMAPF = (SupportMapFragment) myFM
            .findFragmentById(R.id.fragment1);
    MAP = myMAPF.getMap();
    MAP.setMyLocationEnabled(true);
    MAP.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    MAP.setOnMapClickListener(new OnMapClickListener() {
        @Override
        public void onMapClick(LatLng point) {
            // TODO Auto-generated method stub
            MAP.addMarker(new MarkerOptions().position(point).title(
                    point.toString()));
            Log.e("lat", "" + point);
        }
    });

}

}

Ваш xml-файл будет:

              <fragment
                android:id="@+id/fragment1"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:layout_below="@+id/fragment1"
                android:layout_centerHorizontal="true"
                class="com.google.android.gms.maps.SupportMapFragment" />    

И, наконец, добавьте libray в файл манифеста:

 <uses-library
    android:name="com.google.android.maps"
    android:required="true" />
person Shani Goriwal    schedule 04.07.2013
comment
developers.google.com/maps/documentation/android/start. Нет необходимости в used-library. - person Raghunandan; 04.07.2013
comment
@jigar Вы ссылались на проект библиотеки в своем проекте карты? Вы не упомянули то же самое. Я думаю, у вас нет. см. мое редактирование в ответе. Также убедитесь, что у вас включены карты для Android в консоли Google API. - person Raghunandan; 04.07.2013
comment
Я прошел по той же ссылке... и выполнил те же действия по той же ссылке... данные не работают... даты и я разместил этот вопрос....! - person jigar; 04.07.2013

Вы должны использовать SupportFragment Ваш минимальный SDK равен 8.

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

Ваша активность должна распространяться FragmentActivity

импорт

import android.support.v4.app.FragmentActivity;  
import com.google.android.gms.maps.SupportMapFragment; 

Редактировать:

Из ваших комментариев вы говорите, что есть ошибка @

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

Итак, я предполагаю, что вы неправильно ссылались на проект библиотеки сервисов Google Play.

Загрузите сервисы Google Play. Перейти к Windows. Перейдите в Android SDK Manager. Выберите сервисы Google Play в разделе «Дополнительно».

Скопируйте проект библиотеки google-play services_lib в свою рабочую область. Проект библиотеки можно найти по следующему пути.

     <android-sdk-folder>/extras/google/google_play_services/libproject/google-play-services_lib library project .

Импортируйте проект библиотеки в ваше затмение

Нажмите «Файл» > «Импорт», выберите «Android» > «Существующий код Android в рабочую область» и просмотрите рабочую область, импортируйте проект библиотеки. Вы можете проверить, является ли это проектом библиотеки. Щелкните правой кнопкой мыши проект библиотеки. Перейти к свойствам. Нажмите Android на левой панели. Вы увидите флажок Is Library.

person Raghunandan    schedule 04.07.2013
comment
@jigar, что ты имеешь в виду, говоря, что это не работает? Вы получаете исключения или ошибки? - person Raghunandan; 04.07.2013
comment
@jigar вы все еще используете MapFragment в своем xml - person Raghunandan; 04.07.2013
comment
импортировать com.google.android.gms.maps.SupportMapFragment; выводит строку ошибки...! и мой эмулятор показывает, что ваше приложение, к сожалению, не работает - person jigar; 04.07.2013
comment
@jigar вы ссылались на проект библиотеки в своем проекте Android. Я думаю, вы этого не сделали - person Raghunandan; 04.07.2013
comment
Библиотечный проект? для апи v2? - person jigar; 04.07.2013
comment
Я следовал инструкциям, но не работал ... Да, вы разместили вопрос ..! :о - person jigar; 04.07.2013
comment
@jigar проверьте эту ссылку developer.android.com/google/play-services/setup .html. вы не выполнили все шаги, указанные в ссылке. Первый шаг в обзоре @ developers.google.com/maps/documentation/android/start говорит: Загрузите и настройте SDK сервисов Google Play. Google Maps Android API распространяется как часть этого SDK. - person Raghunandan; 04.07.2013
comment
@jigar, вам также следует протестировать свое приложение на реальном устройстве. Хотя вы можете протестировать его на эмуляторе, рекомендуем вам протестировать его на устройстве. - person Raghunandan; 04.07.2013

Попробуй это.

В вашем xml-файле

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

В java-файле

public class MapExampleActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map_example);

    //setUpMap
}
person android developer    schedule 04.07.2013
comment
Вы тестируете его на эмуляторе или устройстве? - person android developer; 04.07.2013

Я столкнулся со многими ошибками при работе с google map API V2. Вы можете проверить эти настройки, которые решили мою проблему.

person Tai Dao    schedule 04.07.2013