I'm designing an app with a MapsActivity that will update my location, but when I run it I only get the world map without telling me my position. I do not see the fault, I have tried many things .
package com.example.dani.etakemongo.ProductionFrontends;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.dani.etakemongo.DevelopFrontends.Menu;
import com.example.dani.etakemongo.Modelo.Usuario;
import com.example.dani.etakemongo.R;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.Serializable;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
String tag = "MapsActivity";
private GoogleMap mMap;
private Marker marcador;
double lat = 0.0;
double ing = 0.0;
String email2, emailaMenu;
int idusuario, idusuarioaMenu;
FloatingActionButton menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Log.d(tag, "Event onCreate()");
email2 = getIntent().getExtras().getString("email");
emailaMenu = email2;
//BOTON MENU
menu = (FloatingActionButton) findViewById(R.id.fab_menu);
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
goToMenu(v);
} catch (Exception ex) {
String error = ex.getMessage();
Toast.makeText(MapsActivity.this, error, Toast.LENGTH_SHORT).show();
}
}
});
// 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);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
}
/**
* 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;
miUbicacion();
}
//Metodo para incluir un marker, CameraUpdate para centrar la camara a la posicion del marker
private void agregarMarcador(double lat, double ing) {
LatLng coordenadas = new LatLng(lat, ing);
CameraUpdate miUbicacion = CameraUpdateFactory.newLatLngZoom(coordenadas, 16);
if (marcador != null)
marcador.remove(); //Si el marcador diferente de null le añadimos propiedades, titulo, imagen
marcador = mMap.addMarker(new MarkerOptions()
.position(coordenadas)
.title("Mi posicion")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher)));
mMap.animateCamera(miUbicacion);
}
//Metodo para obtener latitud y longitud de nuestra posicion actual
private void actualizarUbicacion(Location location) {
if (location != null) { //Comrpobamos la localizacion recibida es diferente de null antes de asignar valores a las valariables
lat = location.getLatitude();
ing = location.getLongitude();
agregarMarcador(lat, ing);
}
}
//Implementamos un objeto del tipo LocationListener, su funcion es estar atento a cambio de localidad recividio por el GPS
LocationListener locListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
actualizarUbicacion(location);//Llamamos anuestro metodo para actualizar la ubicacion
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//Metodo para obtener servicio de posicionamiento, nos da la ultima posicion obtenida y se actualiza cada 15 segundos
private void miUbicacion() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
actualizarUbicacion(location);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,10000,0,locListener);
}
#Override
protected void onStart() {
super.onStart();
Log.d(tag, "Event onStart()");
}
#Override
protected void onResume() {
super.onResume();
Log.d(tag, "Event onResume()");
}
#Override
protected void onPause() {
super.onPause();
Log.d(tag, "Event onPause()");
}
#Override
protected void onStop() {
super.onStop();
Log.d(tag, "Event onStop()");
}
#Override
protected void onRestart() {
super.onRestart();
Log.d(tag, "Event onRestart()");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(tag, "Event onDestroy()");
}
public void goToMenu(View view){
Intent intent = new Intent(MapsActivity.this, Menu.class);
intent.putExtra("email2",emailaMenu);
startActivityForResult(intent, 800);
}
}
Add this line of code in onMapReady
mGoogleMap.setMyLocationEnabled(true);
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
miUbicacion();
if (PermissionUtils.checkPermission(HomeActivity_.this,
PermissionConstant.LOCATION_PERMISSION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
}
Related
I'm using Open Street Map, and I need to save my added points inside a GeoJson so that I can then visualize these points according to the saved coordinates, time, and open within an analyzer of that type of file.
At the first moment, I do not have much data. I only have code using Open Street Map, which still needs some changes.
package br.com.josileudorodrigues.myapplication;
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.cocoahero.android.geojson.GeoJSON;
import org.osmdroid.bonuspack.kml.KmlDocument;
import org.osmdroid.bonuspack.location.NominatimPOIProvider;
import org.osmdroid.bonuspack.location.POI;
import org.osmdroid.config.Configuration;
import org.osmdroid.events.MapEventsReceiver;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;
import org.osmdroid.views.overlay.FolderOverlay;
import org.osmdroid.views.overlay.MapEventsOverlay;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.MinimapOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.PathOverlay;
import org.osmdroid.views.overlay.ScaleBarOverlay;
import org.osmdroid.views.overlay.compass.CompassOverlay;
import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider;
import org.osmdroid.views.overlay.infowindow.InfoWindow;
import org.osmdroid.views.overlay.infowindow.MarkerInfoWindow;
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.ArrayList;
import static android.os.Build.VERSION_CODES.M;
import static java.security.AccessController.getContext;
public class MainActivity extends AppCompatActivity implements MapEventsReceiver, LocationListener {
private static final int PERMISSAO_REQUERIDA =1 ;
private MapView osm;
private MapController mc;
private CompassOverlay mCompassOverlay;
private MyLocationNewOverlay mLocationOverlay;
private LocationManager locationManager;
private PathOverlay po;
private KmlDocument kmlDocument;
ArrayList<OverlayItem> overlayItemArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//onde mostra a imagem do mapa
Context ctx = getApplicationContext();
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
setContentView(R.layout.activity_main);
//Essa é para poder utilizar as permissões
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
osm = (MapView) findViewById(R.id.mapaId);
osm.setTileSource(TileSourceFactory.MAPNIK);
osm.setUseDataConnection(true);
osm.setMultiTouchControls(true);
osm.setClickable(true);
osm.setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] permissoes = {Manifest.permission.INTERNET, Manifest.permission.ACCESS_FINE_LOCATION};
requestPermissions(permissoes, PERMISSAO_REQUERIDA);
}
}
if (Build.VERSION.SDK_INT >= M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
String[] permissoes = {Manifest.permission.INTERNET, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissoes, PERMISSAO_REQUERIDA);
}
}
osm.setMapListener(new MapListener() {
#Override
public boolean onScroll(ScrollEvent event) {
Log.i("Script()", "onScroll ()");
return true;
}
#Override
public boolean onZoom(ZoomEvent event) {
Log.i("Script()", "onZoom ()");
return false;
}
});
mc = (MapController) osm.getController();
GeoPoint center = new GeoPoint(-5.1251, -38.3640);
mc.setZoom(14);
mc.animateTo(center);
addMarker(center);
/* locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//TODO: Consider calling
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);*/
MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(this, this);
osm.getOverlays().add(0, mapEventsOverlay);
// Aqui adiciona a escala do mapa
ScaleBarOverlay scaleBarOverlay = new ScaleBarOverlay(osm);
osm.getOverlays().add(scaleBarOverlay);
kmlDocument = new KmlDocument();
// kmlDocument.parseGeoJSON(geoJsonString);
/*this.mLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(ctx),osm);
this.mLocationOverlay.enableMyLocation();
osm.getOverlays().add(this.mLocationOverlay);*/
this.mCompassOverlay = new CompassOverlay(this, new InternalCompassOrientationProvider(this), osm);
this.mCompassOverlay.enableCompass();
osm.getOverlays().add(this.mCompassOverlay);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSAO_REQUERIDA: {
// Se a solicitação de permissão foi cancelada o array vem vazio.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permissão cedida, recria a activity para carregar o mapa, só será executado uma vez
this.recreate();
}
}
}
}
public void addMarker(final GeoPoint center) {
final Marker marker = new Marker(osm);
marker.setPosition(center);
marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
marker.setIcon(getResources().getDrawable(R.drawable.ic_mapa));
marker.setDraggable(true);
marker.setTitle("DADOS");
marker.setSnippet(center.getLatitude()+ "," + center.getLongitude());
marker.setSubDescription("subDescription Marker");
marker.setInfoWindow(new CustomMarkerInfoWindow(osm));
marker.setInfoWindowAnchor(marker.ANCHOR_CENTER, marker.ANCHOR_TOP);
marker.setOnMarkerClickListener(new Marker.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker m, MapView mapView) {
Log.i("Script","onMarkerClick");
m.showInfoWindow();
InfoWindow.getOpenedInfoWindowsOn(osm);
return true;
}
});
marker.setOnMarkerDragListener(new Marker.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
Log.i("Script", "onMarkerDragStart()");
}
#Override
public void onMarkerDragEnd(Marker marker) {
Log.i("Script", "onMarkerDragEnd()");
}
#Override
public void onMarkerDrag(Marker marker) {
Log.i("Script", "onMarkerDrag()");
}
});
// osm.getOverlays().clear();
osm.getOverlays().add(new MapOverlay(this));
osm.getOverlays().add(marker);
osm.invalidate();
}
public void onResume(){
super.onResume();
//this will refresh the osmdroid configuration on resuming.
//if you make changes to the configuration, use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
osm.onResume(); //needed for compass, my location overlays, v6.0.0 and up
}
public void onPause(){
super.onPause();
//this will refresh the osmdroid configuration on resuming.
//if you make changes to the configuration, use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Configuration.getInstance().save(this, prefs);
osm.onPause(); //needed for compass, my location overlays, v6.0.0 and up
}
#Override
public void onLocationChanged(Location location) {
GeoPoint center = new GeoPoint(location.getLatitude(), location.getLongitude());
mc.animateTo(center);
addMarker(center);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onDestroy() {
super.onDestroy();
if (locationManager != null) {
locationManager.removeUpdates((LocationListener) this);
}
}
class MapOverlay extends Overlay {
public MapOverlay(Context ctx) {
super(ctx);
}
#Override
public void draw(Canvas c, MapView osmv, boolean shadow) {
}
// aqui é onde movimenta o cursor do mapa
#Override
public boolean onSingleTapConfirmed(MotionEvent me, MapView mv) {
Projection p = osm.getProjection();
GeoPoint gp = (GeoPoint) p.fromPixels((int) me.getX(), (int) me.getY());
addMarker(gp);
return (true); // se false ---> vai travar o mapa
}
}
// Aqui quando eu pressionar em uma determinada parte do mapa ele
// irá mostrar as minhas cordenadas
#Override
public boolean singleTapConfirmedHelper(GeoPoint p) {
Toast.makeText(this, "Coordenadas:\nLatitude: ("+p.getLatitude() +"\nLongitude: " +
""+p.getLongitude()+")" , Toast.LENGTH_SHORT).show();
// InfoWindow.closeAllInfoWindowsOn(osm); //Clicando em qualquer canto da tela, fecha o infowindow
return (true);
}
//Aqui eu adiciono uma marcação se eu pressionar a tela
#Override
public boolean longPressHelper(GeoPoint p) {
// addMarker(p);
return true;
}
// InfoWindow
public class CustomMarkerInfoWindow extends MarkerInfoWindow {
public CustomMarkerInfoWindow(MapView mapView) {
super(R.layout.bonuspack_bubble,mapView);
}
#Override
public void onOpen(Object item){
Marker m = (Marker) item;
ImageView iv = (ImageView) mView.findViewById(R.id.bubble_image);
iv.setImageResource(R.drawable.btn_moreinfo);
TextView snippet = (TextView) mView.findViewById(R.id.bubble_title);
snippet.setText(m.getTitle());
TextView coordenada = (TextView) mView.findViewById(R.id. coordenadas);
coordenada.setText(m.getSnippet());
Button bt = (Button) mView.findViewById(R.id.bubble_buttom);
bt.setVisibility(View.VISIBLE);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"Salvo",Toast.LENGTH_SHORT ).show();
}
});
}
}
}
The results I got trying to implement geojson were not satisfactory. I saw several tutorials, but none explained whether or not I had to implement a public void method, if I would have to put it inside the onCreate method, or if I would have to create one Java file.
How can I do this?
You should find most of what you need in OSMBonusPack GeoJSON features.
But this is assuming you have the right level of skills about Java and Android development.
I have a MapsActivity Class, where it starts at a fixed point set on the map. I'm calling a Thread, where Map is only fully loaded, when the return is true. (I'll do a search on a DB through the Web Service where it will return me Lat and Long values to play on the map, and that value will be changed every 15 seconds).
I needed to know, how do I change the position of a Marker out of the class onMapReady.
Follows the MapsActivity class
package com.example.patrickcamargo.myapplication.Maps;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
public class MapsActivity extends SupportMapFragment implements GoogleMap.OnMyLocationButtonClickListener, OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback, GoogleMap.OnMapClickListener {
private GoogleMap mMap;
Marker marker;
LatLng latLng = new LatLng(-23.497444, -47.440722);
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private FusedLocationProviderClient mFusedLocationClient;
public Double latitude, longitude;
public ProgressDialog getProgress() {
return progress;
}
public void setProgress(ProgressDialog progress) {
this.progress = progress;
}
private ProgressDialog progress;
boolean teste = true;
boolean teste2 = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getMapAsync(this);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
mFusedLocationClient.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast toast = Toast.makeText(getContext(),"LAT: " + location.getLatitude() + "LONG: " + location.getLongitude(),Toast.LENGTH_LONG);
toast.show();
}
}
});
//TESTE DE EVENTO
progress = new ProgressDialog(getContext());
progress.setMessage("AGUARDE ENQUANTO IDENTIFICAMOS O SERVIÇO...");
progress.show();
progress.setCanceledOnTouchOutside(false);
ThreadCarregarChamado threadCarregarChamado = new ThreadCarregarChamado();
threadCarregarChamado.setMapsActivity(this);
threadCarregarChamado.start();
//CRIADO UM LOOP INFINITO, PARA QUE SÓ SEJA CARREGADO O MAPA TOTALMENTE, QUANDO O RETORNO DO CHAMADO JÁ TIVER UM FUNCIONARIO DISPONIVEL
//E TAMBEM VINCULADO COM ESSE CHAMADO QUE FOI ABERTO
//ENQUANTO NÃO FOR VINCULADO UM FUNCIONARIO, NÃO IRA SER EXECUTADO DAQUI PRA FRENTE
while (teste);
//onMapReady(mMap);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
enableMyLocation();
mMap = googleMap;
mMap.setOnMapClickListener(this);
// Add a marker in Sydney and move the camera
marker = mMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Testando")
.snippet("Population: 776733"));
}
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
PermitirLocalizacao.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
android.Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap != null) {
mMap.setMyLocationEnabled(true);//BOTÃO PARA MUDAR CAMERA PARA POSIÇÃO ATUAL}
LatLng latLng = new LatLng(latitude, longitude);
//mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); JOGA O ZOOM DIRETO NA POSIÇÃO ATUAL DO CLIENTE
//mMap.animateCamera(CameraUpdateFactory.zoomTo(80));
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermitirLocalizacao.isPermissionGranted(permissions, grantResults,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
enableMyLocation();
} else {
//resume.mPermissionDenied = true;
}
}
#Override
public boolean onMyLocationButtonClick() {
return false;
}
#Override
public void onMapClick(LatLng latLng) {
Toast toast = Toast.makeText(getContext(),"Coordenadas: " + latLng.toString(),Toast.LENGTH_LONG);
toast.show();
}
public void MarcarGuincho()
{
teste=false;
marker.setPosition(new LatLng(-25.63356, -47.440722));
//latLng = (-23.497444, -47.440722);
}
}
Now my Thread
package com.example.patrickcamargo.myapplication.Maps;
import android.app.ProgressDialog;
import android.content.Context;
import com.example.patrickcamargo.myapplication.Conexao;
import com.example.patrickcamargo.myapplication.ConexaoInterface;
import org.json.JSONException;
public class ThreadCarregarChamado extends Thread implements ConexaoInterface{
private ProgressDialog progress;
private Context context;
Conexao conexao;
public MapsActivity getMapsActivity() {
return mapsActivity;
}
public void setMapsActivity(MapsActivity mapsActivity) {
this.mapsActivity = mapsActivity;
}
private MapsActivity mapsActivity;
#Override
public void run() {
//conexao = new Conexao(context, this, "ThreadCarregarChamado.java");
//conexao.execute("teste.php?","");
try {
depoisDownload("OK");
Thread.sleep(5000);
} catch (JSONException e) {
} catch (InterruptedException e) {
}
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
#Override
public void depoisDownload(String result) throws JSONException {
if(result.equals("FALSE\r"))
{
run();
}
else {
mapsActivity.MarcarGuincho();
ProgressDialog progress;
progress = mapsActivity.getProgress();
progress.dismiss();
mapsActivity.setProgress(progress);
}
}
}
In the MarcarGuincho class, this is where I need to change the position of the marker set above, but it is giving me as null for me, so this is giving error ...
Error in this line
marker.setPosition(new LatLng(-25.63356, -47.440722));
Logcat
10-02 13:29:43.628 29584-30901/com.example.patrickcamargo.myapplication E/AndroidRuntime: FATAL EXCEPTION: Thread-240709
Process: com.example.patrickcamargo.myapplication, PID: 29584
com.google.maps.api.android.lib6.common.apiexception.c: Not on the main thread
at com.google.maps.api.android.lib6.common.k.b(:com.google.android.gms.DynamiteModulesB#11517436:11)
at com.google.maps.api.android.lib6.common.p.a(:com.google.android.gms.DynamiteModulesB#11517436:5)
at com.google.maps.api.android.lib6.impl.cz.c(:com.google.android.gms.DynamiteModulesB#11517436:176)
at com.google.android.gms.maps.model.internal.q.onTransact(:com.google.android.gms.DynamiteModulesB#11517436:18)
at android.os.Binder.transact(Binder.java:387)
at com.google.android.gms.internal.zzed.zza(Unknown Source)
at com.google.android.gms.maps.model.internal.zzr.getPosition(Unknown Source)
at com.google.android.gms.maps.model.Marker.getPosition(Unknown Source)
at com.example.patrickcamargo.myapplication.Maps.MapsActivity.MarcarGuincho(MapsActivity.java:148)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.depoisDownload(ThreadCarregarChamado.java:55)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.run(ThreadCarregarChamado.java:30)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.depoisDownload(ThreadCarregarChamado.java:60)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.run(ThreadCarregarChamado.java:30)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.depoisDownload(ThreadCarregarChamado.java:60)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.run(ThreadCarregarChamado.java:30)
Line 148 = marker.remove();
Try using
teste = false;
LatLng latLng1 = new LatLng(-25.63356, -47.440722);
if(marker != null)
{
marker.remove();
marker = mMap.addMarker(new MarkerOptions()
.position(latLng1)
.title("Testando")
.snippet("Population: 776733"));
}
I am new to android and try to implement an activity with two tab one show co-ordinates which i got from GPS-Service and i want to mark that current location (co-ordinates value using marker) in map using coordinates value which i got from GPS services. And kindly help me for implementing Geo Fencing in map also.
GPS Service
package com.app.servicegps;
/**
* Created by Android on 29-Dec-16.
*/
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
public class GPS_Service extends Service {
private LocationListener listener;
private LocationManager locationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("coordinatesLongt",location.getLongitude());
i.putExtra("coordinatesLangt",location.getLatitude());
sendBroadcast(i);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);
}
#Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
//noinspection MissingPermission
locationManager.removeUpdates(listener);
}
}
}
Map Activity
package com.app.servicegps;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
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 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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements LocationListener,OnMapReadyCallback,
SensorEventListener, DialogInterface.OnClickListener {
private GoogleMap mMap;
private BroadcastReceiver broadcastReceiver;
Marker now;
String langt = null;
String longt= null;
#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);
}
#Override
public void onLocationChanged(Location location) {
if(now != null){
now.remove();
}
//TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
//double latitude = location.getLatitude();
// Getting longitude of the current location
// double longitude = location.getLongitude();
double latitude= Double.parseDouble(langt);
double longitude= Double.parseDouble(longt);
// Creating a LatLng object for the current location
// LatLng latLng = new LatLng(latitude, longitude);
LatLng latLng = new LatLng(latitude, longitude);
now = mMap.addMarker(new MarkerOptions().position(latLng));
// Showing the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//get value
if(intent.getAction().equals("location_update"))
{
langt=intent.getStringExtra("coordinatesLangt");
longt=intent.getStringExtra("coordinatesLongt");
}
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
/**
* 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));*/
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
#Override
public void onSensorChanged(SensorEvent event) {
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
Main Activity
package com.app.servicegps;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button btn_start, btn_stop;
private TextView textView;
private BroadcastReceiver broadcastReceiver;
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
textView.append("\n" +intent.getExtras().get("coordinates"));
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
#Override
protected void onDestroy() {
super.onDestroy();
if(broadcastReceiver != null){
unregisterReceiver(broadcastReceiver);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.button);
btn_stop = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView);
if(!runtime_permissions())
enable_buttons();
}
private void enable_buttons() {
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i =new Intent(getApplicationContext(),GPS_Service.class);
startService(i);
}
});
btn_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),GPS_Service.class);
stopService(i);
}
});
}
private boolean runtime_permissions() {
if(Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},100);
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 100){
if( grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
enable_buttons();
}else {
runtime_permissions();
}
}
}
}
Kindly help me for Geo fencing how i implement it it map activity.
The basic this i want is a main activity with tabs fragments.
Fragment 1st - Show Coordinates
Fragment 2nd Show Map
And A Geo Fencing To Show Notification when i enter in a tag place.
Interface class
public interface LocationInter {
void onUpdateLocation(Location location);
}
Implement the interface in main activity.
Add below lines in GPS service class.
private static LocationInter locationListener = null;
public void LocationInstance(LocationGuideInter locationListeners) {
if (locationListener == null) {
locationListener = locationListeners;
}
}
In Location change add this line
if (locationListener != null) {
locationListener.onUpdateLocation(location);
}
This is taken from android documentation so you can look at more details here
Set up for Geofence Monitoring
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Create geofence objects
Use Geofence.Builder to create a geofence, setting the desired radius, duration, and transition types for the geofence. For example, to populate a list object named mGeofenceList:
mGeofenceList.add(new Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId(entry.getKey())
.setCircularRegion(
entry.getValue().latitude,
entry.getValue().longitude,
Constants.GEOFENCE_RADIUS_IN_METERS
)
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.build());
Specify geofences and initial triggers
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
Define an Intent for geofence transitions
public class MainActivity extends FragmentActivity {
...
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
// calling addGeofences() and removeGeofences().
return PendingIntent.getService(this, 0, intent, PendingIntent.
FLAG_UPDATE_CURRENT);
}
Add geofences
public class MainActivity extends FragmentActivity {
...
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(this);
}
Handle Geofence Transitions
public class GeofenceTransitionsIntentService extends IntentService {
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errorMessage = GeofenceErrorMessages.getErrorString(this,
geofencingEvent.getErrorCode());
Log.e(TAG, errorMessage);
return;
}
// Get the transition type.
int geofenceTransition = geofencingEvent.getGeofenceTransition();
// Test that the reported transition was of interest.
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
// Get the geofences that were triggered. A single event can trigger
// multiple geofences.
List triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// Get the transition details as a String.
String geofenceTransitionDetails = getGeofenceTransitionDetails(
this,
geofenceTransition,
triggeringGeofences
);
// Send notification and log the transition details.
sendNotification(geofenceTransitionDetails);
Log.i(TAG, geofenceTransitionDetails);
} else {
// Log the error.
Log.e(TAG, getString(R.string.geofence_transition_invalid_type,
geofenceTransition));
}
}
Geofences tutorial from Raywendrlich here
hi im going through this tutorial and i faced a annoying problem that latitude and longitude always return 0.0 .im using api 16 on nexus 4.
GPSTracker.java
package ir.ketabe_zard.www.maps;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
/**
* Created by Pedram Hassas on 11/24/2016.
*/
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
}
Criteria locationCritera = new Criteria();
String providerName = locationManager.getBestProvider(locationCritera,
true);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(providerName);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check if best network provider
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.delete);
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public void stopUsingGPS() {
if (locationManager != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.removeUpdates(GPSTracker.this);
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location loc) {
if(location!=null){
location=loc;
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}<br>
MapsActivity.java
package ir.ketabe_zard.www.maps;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
View.OnClickListener {
Location location;
TextView txtLatLng;
protected LocationManager locationManager;
Double Lat, Lng;
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
#Override
public void onMapLongClick(LatLng latLng) {
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
#Override
protected void onStart() {
txtLatLng = (TextView) findViewById(R.id.txtLatLng);
super.onStart();
}
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);
}
public void btnLocation_clicked(View view) {
GPSTracker gps = new GPSTracker(this);
if(gps.canGetLocation()){
Lat=gps.getLatitude();
Lng=gps.getLongitude();
txtLatLng.setText(String.valueOf(Lat)+","+String.valueOf(Lng));
}else {
gps.showSettingsAlert();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
final TextView LatLng;
// Add a marker in Sydney and move the camera
LatLng Tehran = new LatLng(35.689197, 51.388974);
mMap.addMarker(new MarkerOptions().position(Tehran).title("Marker in Tehran").draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Tehran, 12));
}
#Override
public void onClick(View v) {
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}<br>
i have a button when user taped it . show lat and lng in a textview in x.x,x.x format.
Basically I am working on Google Map in which I have Google Map Activity and user click on any place of Google Map I was adding marker on this click and I have one button on this button click I take this marker position and put it to my Firebase Database.My complete code was working, but the problem is that when I click on the button which takes marker latlang to Firebase, my latlang value successfully update and my map Activity is re-transited (e.g./i.e. like Intent from current Activity to self Activity) that for my map was reloaded and I lose marker on screen.
Here is my Java code:
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class PickUpActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, View.OnClickListener, GoogleMap.OnMapClickListener {
private static final int PERMISSION_REQUEST_CODE = 1;
public double marker_latitude;
public double marker_longitude;
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private Marker marker;
private double latitude;
private double longitude;
private Button btn;
private Bus bus;
private Firebase ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_up);
Firebase.setAndroidContext(this);
btn = (Button) findViewById(R.id.btn_pick);
ref = new Firebase(Config.FIREBASE_URL);
bus = new Bus();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mMap = mapFragment.getMap();
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
btn.setOnClickListener(this);
mMap.setOnMapClickListener(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
getCurrentLocation();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
private void getCurrentLocation() {
if (!checkPermission()) {
requestPermission();
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
longitude = location.getLongitude();
latitude = location.getLatitude();
moveMap();
}
}
private void moveMap() {
LatLng latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(PickUpActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(PickUpActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
Toast.makeText(PickUpActivity.this, "GPS permission allows us to access location data. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(PickUpActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getCurrentLocation();
} else {
}
break;
}
}
#Override
public void onClick(View v) {
if (v == btn) {
if (marker == null) {
Toast.makeText(PickUpActivity.this, "Please Select Any Place", Toast.LENGTH_SHORT).show();
} else {
bus.setlatitude(marker_latitude);
bus.setlongitude(marker_longitude);
ref.child("school1").child("bus1").child("parents").child("parent01").child("pickuppoint").setValue(bus);
Toast.makeText(PickUpActivity.this, "Pick Up Point Set", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onMapClick(LatLng latLng) {
mMap.clear();
marker = mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title("" + latLng));
marker_latitude = latLng.latitude;
marker_longitude = latLng.longitude;
}
}
During analysis I found problem in below code:
bus.setlatitude(marker_latitude);
bus.setlongitude(marker_longitude);
ref.child("school1").child("bus1").child("parents").child("parent01").child("pickuppoint").setValue(bus);
If I put some static value on bus.setlatitude() and bus.setlongitude no re-transition occur. I don't know what I am doing wrong and what is solution for this problem.
if your user click on your Map the map will be cleared: mMap.clear();
#Override
public void onMapClick(LatLng latLng) {
mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title(""+latLng));
marker_latitude = latLng.latitude;
marker_longitude= latLng.longitude;
}