meu mapa so está mostrando a minha posição atual e o meu ponto de inicio. Mas não está mostrando os endereços dos alunos cadastrados no banco de dados.
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.com.cadastroDeAluno">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--
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-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_students"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".splashScreen.TelaDeApresentacaoActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Black.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainListaAlunosActivity"
android:label="@string/app_name">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".FormularioActivity"
android:label="@string/tela_cadastro" />
<activity
android:name=".ProvasActivity"
android:label="@string/tela_provas" />
<activity
android:name=".DetalhesProvaActivity"
android:label="@string/tela_detalhe_prova" />
<activity
android:name=".ProvasTabletActivity"
android:label="@string/tela_detalhe_prova" />
<!--
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" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
<activity
android:name=".MapaActivity"
android:label="@string/tela_mapa" />
</application>
</manifest>
gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.3"
defaultConfig {
applicationId "br.com.cadastroDeAluno"
minSdkVersion 15
targetSdkVersion 24
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(include: ['*.jar'], dir: 'libs')
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.android.support:cardview-v7:24.2.1'
compile 'com.android.support:support-v4:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.google.android.gms:play-services:9.2.1'
compile 'com.google.android.gms:play-services-location:8.4.0'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'tyrantgit:explosionfield:1.0.1'
testCompile 'junit:junit:4.12'
}
Localizador
package br.com.cadastroDeAluno.mapa;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
/**
* Created by Leandro on 18/10/2016.
*/
//classe responsável por gerenciar a parte do GPS
//classe Localizador que centraliza o mapa de acordo com a posição do dispositivo utilizando o GPS.
public class Localizador implements GoogleApiClient.ConnectionCallbacks, com.google.android.gms.location.LocationListener { //LocationListener
private final GoogleApiClient client; //a classe GoogleApiClient serve para fazer a conexão dentro do celular
private final MapaFragment mapaFragment;
public Localizador (Context context, MapaFragment mapaFragment){
client = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API) //acessar o LocationsService
.addConnectionCallbacks(this)
.build();
client.connect();
this.mapaFragment = mapaFragment;
}
// metodo em que especificamos o que fazer ao conectar
@Override
public void onConnected(@Nullable Bundle bundle) {
LocationRequest request = new LocationRequest();
request.setSmallestDisplacement(50); //define o deslocamento minimo
request.setInterval(1000); //intervalo de envio da posição
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); //com isso teremos uma precisão muito alta
LocationServices.FusedLocationApi.requestLocationUpdates(client, request, this);
}
//metodo em que especificamos o que fazer quando a conexao for suspensa
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
LatLng coordenada = new LatLng(location.getLatitude(), location.getLongitude());
mapaFragment.centralizarEm(coordenada);
}
}
Mapafragment:
package br.com.cadastroDeAluno.mapa;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdate;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import br.com.cadastroDeAluno.dao.AlunoDAO;
import br.com.cadastroDeAluno.modelo.Aluno;
/**
* Created by Leandro on 18/10/2016.
*/
public class MapaFragment extends SupportMapFragment implements OnMapReadyCallback {
private GoogleMap mapa;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
getMapAsync(this);
}
//esse metodo serve para poder mexer no mapa
@Override
public void onMapReady(GoogleMap googleMap) {
this.mapa = googleMap;
LatLng minhaPosicao = new LatLng(-7.91820779, -34.82892931);
//LatLng minhaPosicao = pegaCoordenadaDoEndereco("Rua Honorato Fernandes da Paz, Pau Amarelo, Paulista - PE");
//LatLng minhaPosicao = new LatLng(-7.91820779, -34.82892931);
if(minhaPosicao != null) {
centralizarEm(minhaPosicao);
MarkerOptions marcador = new MarkerOptions();
marcador.title("Minha Posição");
marcador.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
marcador.position(minhaPosicao);
mapa.addMarker(marcador);
}
//adiciona o local do aluno
AlunoDAO alunoDAO = new AlunoDAO(getContext());
for (Aluno aluno : alunoDAO.buscaAlunos()){
LatLng coordenada = pegaCoordenadaDoEndereco(aluno.getEndereco());
if(coordenada != null){
MarkerOptions marcador = new MarkerOptions();
marcador.position(coordenada);
marcador.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
marcador.title(aluno.getNome());
marcador.snippet(String.valueOf(aluno.getNota()));
mapa.addMarker(marcador);
}
}
alunoDAO.close();
new Localizador(getContext(), MapaFragment.this);
}
private LatLng pegaCoordenadaDoEndereco(String endereco){
// esse try catch serve para verificar a conexao
try {
Geocoder geocoder = new Geocoder(getContext()); //transforma uma string em latitude e longitude //getContext()
List<Address> resultados = geocoder.getFromLocationName(endereco, 1); //https://developer.android.com/reference/android/location/Geocoder.html
if (!resultados.isEmpty()){
LatLng posicao = new LatLng(resultados.get(0).getLatitude(), resultados.get(0).getLongitude());
return posicao;
}
}catch (IOException e){
e.printStackTrace();
}
return null; //caso nao tenha nenhum retorno
}
public void centralizarEm(LatLng coordenada) {
if(mapa != null){
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(coordenada, 17);
mapa.moveCamera(update);
}
}
}
mapaActivity
package br.com.cadastroDeAluno;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import br.com.cadastroDeAluno.mapa.Localizador;
import br.com.cadastroDeAluno.mapa.MapaFragment;
public class MapaActivity extends FragmentActivity { //Fragment
private static final int REQUEST_PERMISSOES = 1;
MapaFragment mapaFragment;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction tx = manager.beginTransaction();
mapaFragment = new MapaFragment();
tx.replace(R.id.frame_mapa, mapaFragment); //new SupportMapFragment();
tx.commit();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] permissoes = {android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION};
requestPermissions(permissoes, REQUEST_PERMISSOES);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_PERMISSOES) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
grantResults[1] == PackageManager.PERMISSION_GRANTED) {
new Localizador(this, mapaFragment);
}
}
}
}
layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frame_mapa"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Como mostrar o marcador do endereço de cada aluno cadastrado???