0

Здравствуйте! Пытаюсь запустить приложение google maps на своем устройстве, которое через usb подключено к компьютеру, и на него я вывожу результат. Дело в том, что, когда я запускаю приложение google maps, то выводится лишь бежевый прямоугольник и логотип google слева снизу. Я создал Google Maps Activity, получил API-ключ, вставил его в манифест. Не понимаю в чем причина. Писали, что проблема может быть в том, что ключ API неверный. Тогда как сделать правильно?

AndroidManifest.xml:

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

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->

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

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

    <application
        android:name="android.support.multidex.MultiDexApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

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

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

</manifest>

Gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "22.0.1"
    defaultConfig {
        applicationId "com.example.nikiz.myapplicationmaps"
        minSdkVersion 19
        targetSdkVersion 24
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.google.android.gms:play-services:9.8.0'
    compile 'com.android.support:multidex:1.0.1'
    testCompile 'junit:junit:4.12'
}

MapsActivity.java:

package com.example.nikiz.myapplicationmaps;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}
3
  • Должны быть логи при заходе на активити с мапой и там что то должно прояснить ситуацию
    – JVic
    4 янв 2017 в 20:57
  • По фильтру Error нашлась такая: /com.example.nikiz.myapplicationmaps E/b: Authentication failed. Timeout while trying to contact the server.
    – NikiZ
    4 янв 2017 в 21:11
  • В консоли разработчика ключ активен?
    – JVic
    4 янв 2017 в 21:53

2 ответа 2

1

В манифесте, похоже, забыты пермишены для доступа к сети. Это же облачный сервис, ему надо в облако за самой картой обращаться.

<uses-permission android:name="android.permission.INTERNET"/>
3
  • К сожалению ,не помогло. К тому же, в документации читал, что данный permission автоматически добавляется, его необязательно указывать явно.
    – NikiZ
    4 янв 2017 в 21:19
  • про автоматически я почитаю, спасибо, интересно даже. я на днях его забыл и потом добавлял. ищите тогда в логах, там должна быть подсказка. проверьте, что ключ свежий, что id приложения совпадает.
    – tse
    4 янв 2017 в 21:26
  • Вы были правы, кажется, нужно было добавить именно этот permission. У меня очень мало опыта, поэтому я не знал, что нужно удалять приложение с устройства, прежде чем снова выводить на него результат, поэтому вчера у меня ничего не выводилось. Спасибо!
    – NikiZ
    5 янв 2017 в 8:23
0

Попробуйте всё таки установить следующие permissions:

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

Также как возможно приятное замечание, не стоит импортировать всю библиотеку

    compile 'com.google.android.gms:play-services:9.8.0'

Так как именно поэтому мне кажется вам пришлось допиливать multidex.

Ну и ради пробы попробуйте добавить маркер следующим образом:

public void onMapReady(GoogleMap map) {
    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    Marker marker = map.addMarker(new MarkerOptions()
            .position(new LatLng(47.045029, 28.861427))
            .title("Marker"));
    builder.include(marker.getPosition());
    LatLngBounds bounds = builder.build();

    int padding = 150;
    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
    map.moveCamera(cu);
}

Надеюсь ответ будет полезным.

UPD

Чтобы обойти импорта mulitdex, желательно импортировать карты примерно следующим образом(если вы конечно собираетесь использовать только карты):

compile 'com.google.android.gms:play-services-maps:9.8.0'
compile 'com.google.android.gms:play-services-location:9.8.0'

Вместо

    compile 'com.google.android.gms:play-services:9.8.0'
3
  • Спасибо за ответ! Скажите, пожалуйста, каким образом я могу импортировать не всю библиотеку, так как именно из-за нее мне пришлось делать multidex?
    – NikiZ
    5 янв 2017 в 8:27
  • Обновил ответ. Можете ознакомиться.
    – Morozov
    5 янв 2017 в 8:54
  • Спасибо большое, Вы очень помогли!
    – NikiZ
    5 янв 2017 в 12:24

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.