Re: Урок 139. Google maps. Создание и настройка проекта. Кар
Добавлено: 21 апр 2015, 10:14
Господа, делаю все, как сказано в уроке, но программа останавливается на этапе включения.
Помогите.
Помогите.
Добро пожаловать на форум сайта
http://forum.startandroid.ru/
pka,спасибо, Вы очень помогли!pka писал(а):Для запуска и настройки урока #139 на Android Studio нужно:FastRus1804 писал(а):А как настроить Google Play services в Android Studio?
=> Зайти в браузере на свой акаунт на сайте Google APIs Console https://code.google.com/apis/console/?noredirect, на вкладке Services включить тумблер Google Maps Android API v2
=> Создаем пустой проект с нужными нам именем, blank/HelloWorld activity.
=> В Android Studio на открытой вкладке проекта (область слева) щёлкнуть ПКМ по структуре проекта и выбрать
"New" -> "Google" -> "Google Map Activity"
=> Система сгенерирует некоторые файлы и зависимости а вам откроется файл res/values/google_maps_api.xml
=> Внимательно его изучаем. В нем есть значение ключа SHA1, а также ссылка для перехода на сайт google для получения google_maps_key.
=> Копируем ссылку перехода и вставляем в адресную строку браузера для перехода на страницу генерирования ключа средствами google
=>Разбираемся с интерфейсом, нажимаем "generate" или как-то так
=> Сгенерированный на сайте гугла ключ вставляем сюда же (res/values/google_maps_api.xml) в значение строковой переменной google_maps_key:
<string name="google_maps_key" templateMergeStrategy="preserve">*************-********-****************</string>
=> Рекомендуют создать googleplay классы (хотя карта и без них работает): В Android Studio на открытой вкладке проекта щёлкнуть ПКМ по структуре проекта и выбрать
"New" -> "Google" -> "Google Play Services Activity"
(полагаю, в SDK менеджере уже должны быть скачаны Google Play services)
=> Редактировать файл манифеста не нужно, строки googleplayservices и права доступа добавятся сами. (Чудеса!)
=>далее - по тексту урока: копируем текст layout-а, вставляем в layout; текст main-activity.java - в main-activity.java...
Код: Выделить всё
package ru.startandroid.develop.p1391googlemaps;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
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 MainActivity extends FragmentActivity implements OnMapReadyCallback {
SupportMapFragment mapFragment;
private GoogleMap mMap;
final String TAG = "myLogs";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
init();
}
private void init() {
Log.d(TAG,"Init");
}
public void onClickTest(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
@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));
}
}
Код: Выделить всё
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical">
<Button
android:id="@+id/btnTest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickTest"
android:text="@string/test">
</Button>
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
</LinearLayout>
Код: Выделить всё
<?xml version="1.0" encoding="utf-8"?>
<manifest package="ru.startandroid.develop.p1391googlemaps"
xmlns:android="http://schemas.android.com/apk/res/android">
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="@string/google_maps_key">
</meta-data>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version">
</meta-data>
<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"/>
<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-feature>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!--
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"/>
</application>
</manifest>