I'm trying to create my map so that it opens to the user's current location zoomed in. However I'm having trouble doing this. I've seen several people using getLastKnownLocation() however this always returns null for me and I always get NullPointerException. The code I have is
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
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.widget.Toast;
public class WeatherMapActivity extends Activity implements LocationListener {
private GoogleMap map;
private Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_maps_main);
initializeMap();
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng);
map.moveCamera(CameraUpdateFactory.newLatLng(coordinate));
}
private void initializeMap() {
// check if map is created
if(map == null) {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); // creates the map
map.setMyLocationEnabled(true); // enables gps to track my location
map.getUiSettings().setMyLocationButtonEnabled(true); // enables the "return to my location" button on map
map.getUiSettings().setCompassEnabled(true); // enables the compass button on map
// check if map is created successfully or not
if (map == null) {
Toast.makeText(getApplicationContext(),
"Map could not be created", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initializeMap();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onLocationChanged(Location location) {
map.clear();
MarkerOptions marker = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude()));
marker.title("Current location");
map.addMarker(marker);
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
I've tried putting map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 16)); in onLocationChanged(Location location) but this zooms in to my current location every so often when I'm trying to look at the other parts of the map.
So how do I set it so that when I open the app, it opens to the current location zoomed in and doesn't zoom in any other time?
You can use CameraPosition to do this.
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
//here where the camera animate and zoom to particular location.
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 14));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(18) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
Related
I'm trying to build an app and on the landing page google maps zooms in on your current location. This has been working on an emulator then suddenly stopped with the error messages. I then switched to an android phone and initially worked fine but now I'm getting a GnssLocationProvider: 'Wakelock acquired by send message' followed by 'Wakelock released by handle message' error, and can't find where to fix it, or if the code is the problem. This is the code:
package com.example.mappractise;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
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;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
LocationManager locationManager;
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);
locationManager = (LocationManager) getSystemService(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
// 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;
}else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
System.out.println("Getting to line 53");
//check if network provide is enabled
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onLocationChanged(Location location) {
//get latitude
double latitude = location.getLatitude();
//get longitude
double longitude = location.getLongitude();
//instantiate the class LatLng
LatLng latLng = new LatLng(latitude, longitude);
//instantiate the class, geocoder
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getLocality();
str += addressList.get(0).getCountryName()+",";
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.2f));
int num = 0;
do {
System.out.println("Count : "+num);
System.out.println("Latitude : " + latitude);
System.out.println("Longitude : " + longitude);
System.out.println("Time : "+java.time.LocalTime.now());
Thread.sleep(1000);
num++;
if(num==11){
break;
}
} while (num<=10);
System.out.println("Loop Finished");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get latitude
double latitude = location.getLatitude();
//get longitude
double longitude = location.getLongitude();
//instantiate the class LatLng
LatLng latLng = new LatLng(latitude, longitude);
//instantiate the class, geocoder
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getLocality();
str += addressList.get(0).getCountryName()+",";
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10.2f));
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error above line 129");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
/**
* 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));
}
}
and the logcat message:
2020-05-16 17:06:56.771 1926-1943/system_process I/GnssLocationProvider: WakeLock released by handleMessage(REPORT_SV_STATUS, 0, com.android.server.location.GnssLocationProvider$SvStatusInfo#771350b)
2020-05-16 17:06:57.771 1926-2998/system_process I/GnssLocationProvider: WakeLock acquired by sendMessage(REPORT_SV_STATUS, 0, com.android.server.location.GnssLocationProvider$SvStatusInfo#adf1fe8)
2020-05-16 17:06:57.772 1926-1943/system_process I/GnssLocationProvider: WakeLock released by handleMessage(REPORT_SV_STATUS, 0, com.android.server.location.GnssLocationProvider$SvStatusInfo#adf1fe8)
The loop inside the retrofitResponse method does not loops which it was suppose to do. It was suppose to fetch json data from google map url.
package com.webstarts.byteglory.shomadhan;
import android.*;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.location.Location;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationRequest;
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.MapFragment;
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.webstarts.byteglory.shomadhan.POJO.Example;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class StartActivity extends FragmentActivity implements ConnectionCallbacks, OnConnectionFailedListener, com.google.android.gms.location.LocationListener, OnMapReadyCallback {
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
protected static final String TAG = "Location Services Test";
private Button search_location_button;
private Button search_area_button;
private Button toilet_status_button;
protected LatLng latlng;
protected LocationRequest mLocationRequest;
private GoogleMap mMap;
private int PROXIMITY_RADIUS = 10000;
Marker mCurrLocationMarker;
boolean mapReady = false;
private Marker mPerth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
search_location_button = (Button) findViewById(R.id.search_location_button);
search_area_button = (Button) findViewById(R.id.search_area_button);
toilet_status_button = (Button) findViewById(R.id.toilet_status_button);
locationApiClient();
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
search_location_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Log.i(TAG, String.valueOf(latlng.latitude));
// Uri gmmIntentUri = Uri.parse("geo:"+String.valueOf(latlng.latitude)+","+String.valueOf(latlng.longitude)+"?z=15&q=public toilets");
// Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
// mapIntent.setPackage("com.google.android.apps.maps");
// startActivity(mapIntent);
retrofitResponse();
// Marker loc = mMap.addMarker(new MarkerOptions().position(latlng)
// .title("You are here now 23"));
// mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15));
//
// // Zoom in, animating the camera.
// mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
// Log.i(TAG, String.valueOf(latlng.latitude));
}
});
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
protected synchronized void locationApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
#Override
public void onConnected(Bundle connectionHint) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null) {
latlng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
}
else {
Toast toast = Toast.makeText(this, "Turn on your location service", Toast.LENGTH_LONG);
toast.show();
finish();
}
}
public void onLocationChanged(Location location) {
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
/*
* Called by Google Play services if the connection to GoogleApiClient drops because of an
* error.
*/
public void onDisconnected() {
Log.i(TAG, "Disconnected");
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
private void retrofitResponse() {
String url = "https://maps.googleapis.com/maps/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitMaps service = retrofit.create(RetrofitMaps.class);
Call<Example> call = service.getNearbyPlaces("restaurents", latlng.latitude + "," + latlng.longitude, PROXIMITY_RADIUS);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Response<Example> response, Retrofit retrofit) {
try {
mMap.clear();
// This loop will go through all the results and add marker on each location.
Log.i("ishan", String.valueOf(response.body().getResults().size()));
for (int i = 0; i < response.body().getResults().size(); i++) {
Double lat = response.body().getResults().get(i).getGeometry().getLocation().getLat();
Double lng = response.body().getResults().get(i).getGeometry().getLocation().getLng();
String placeName = response.body().getResults().get(i).getName();
String vicinity = response.body().getResults().get(i).getVicinity();
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, lng);
// Position of Marker on Map
markerOptions.position(latLng);
// Adding Title to the Marker
markerOptions.title(placeName + " : " + vicinity);
// Adding Marker to the Camera.
Marker m = mMap.addMarker(markerOptions);
// Adding colour to the marker
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Log.i("ishan", String.valueOf(i));
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
#Override
public void onMapReady(GoogleMap map) {
mapReady=true;
mMap = map;
// //Initialize Google Play Services
// if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (ContextCompat.checkSelfPermission(this,
// android.Manifest.permission.ACCESS_FINE_LOCATION)
// == PackageManager.PERMISSION_GRANTED) {
// }
// }
}
}
This is the interface of the retrofit. It has just the GET as it just reads data from map url.
package com.webstarts.byteglory.shomadhan;
import com.webstarts.byteglory.shomadhan.POJO.Example;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Query;
public interface RetrofitMaps {
/*
* Retrofit get annotation with our URL
* And our method that will return us details of student.
*/
#GET("api/place/nearbysearch/json?sensor=true&key=AIzaSyABCGHHSFDGSDsdfGADFnM")
Call<Example> getNearbyPlaces(#Query("type") String type, #Query("location") String location, #Query("radius") int radius);
}
I have just looped inside the onResponse retrofit function like this:
public void onResponse(Call call, Response response) {
/* implement the toast */
/* =new ArrayList<User>(); */
ArrayList<User> test;
test=response.body().getUsers();
String jax= test.get(0).getFarm_name();
//Toast.makeText(MarkerDemoActivity.this, "farm name is "+jax, Toast.LENGTH_LONG).show();
//LatLng m_cord,String farm_name,String desc
int i = 0;
while ( test.size()>i) {
String farm_name = test.get(i).getFarm_name();
String desc1 = test.get(i).getOwner_tel();
String desc2 = test.get(i).getFarm_type();
String cords = test.get(i).getM_cord();
//split the co-ords
String[] latlong = cords.split(",");
double latitude = Double.parseDouble(latlong[0]);
double longitude = Double.parseDouble(latlong[1]);
LatLng location = new LatLng(latitude, longitude);
//do the loop here
// Add lots of markers to the map. LatLng m_cord,String farm_name,String desc
addMarkersToMapJax(location, farm_name, desc1 + desc2);
i++;
}
}
I created a marker function to load the co-ordinates:
private void addMarkersToMapJax(LatLng m_cord,String farm_name,String desc) {
// Uses a colored icon.
mArc = mMap.addMarker(new MarkerOptions()
.position(m_cord)
.title(farm_name)
.snippet(desc)
I'm working on an app getting user's current location and showing it on map, as well as Latitude and Longitude on the screen, so far everything is going fine, the map's showing my current location as well as displaying latitude and longitude on the screen using this code
#Override
public void onLocationChanged(Location location) {
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();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
Problem occurs when I want to send this latitude and longitude on server , it throws NUll pointer exception
01-04 23:27:38.759 29286-29286/io.xgear.geotag E/AndroidRuntime: FATAL
EXCEPTION: main
Process: io.xgear.geotag, PID: 29286
java.lang.NullPointerException
at io.xgear.geotag.MainActivity$GeoTagTask.<init>(MainActivity.java:234)
at io.xgear.geotag.MainActivity$1.onClick(MainActivity.java:181)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19270)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
this is the piece of code for getting latitude and longitude to send
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private final String shopCode;
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
private boolean isConnect;
GeoTagTask(String shopId) {
shopCode = shopId;
isConnect = false;
}
#Override
protected Boolean doInBackground(Void... params) {
boolean res = false;
try {
ContentValues nameValuePairs = new ContentValues();
nameValuePairs.put("Id", shopCode);
nameValuePairs.put("lat", lat);
nameValuePairs.put("lng", lng);
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
Log.i("Latitude", lat+"");
Post post = new Post(getApplicationContext());
String result = "";
// isConnect = post.isConnected();
// if(isConnect) {
result = post.doPost(nameValuePairs);
jsonObj = new JSONObject(result);
Log.i("Result", result+"");
if(jsonObj.getInt("success") == 1)
res = true;
// }
} catch (JSONException e) {
e.printStackTrace();
}
return res;
}
and this is the full code
package io.xgear.geotag;
import android.Manifest;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import android.support.v4.app.Fragment;
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.GoogleMapOptions;
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;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import io.xgear.geotag.helper.Post;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
private GeoTagTask mAuthTask = null;
GPSTracker gps;
private JSONObject jsonObj;
// UI references.
private EditText txtShopCode;
private EditText lblAddress;
private View mProgressView;
private View mGeoTagForm;
private Button btnGeoTag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtShopCode = (EditText) findViewById(R.id.txtShopCode);
btnGeoTag = (Button) findViewById(R.id.btnGeoTag);
mGeoTagForm = (View) findViewById(R.id.geoTagForm);
mProgressView = findViewById(R.id.geoTagProgress);
// 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 = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
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;
}
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
btnGeoTag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String shopid = txtShopCode.getText().toString();
boolean cancel = false;
View focusView = null;
//txtShopCode.setInputType(InputType.TYPE_CLASS_NUMBER);
if (TextUtils.isEmpty(shopid)) {
txtShopCode.setError(getString(R.string.error_field_required));
focusView = txtShopCode;
cancel = true;
}
else {
showProgress(true);
mAuthTask = new GeoTagTask(shopid);
mAuthTask.execute((Void) null);
}
}
});
}
//
// public void btnGeoTag_Click(View v){
//
// }
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
mGeoTagForm.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private final String shopCode;
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
private boolean isConnect;
GeoTagTask(String shopId) {
shopCode = shopId;
isConnect = false;
}
#Override
protected Boolean doInBackground(Void... params) {
boolean res = false;
try {
ContentValues nameValuePairs = new ContentValues();
nameValuePairs.put("Id", shopCode);
nameValuePairs.put("lat", lat);
nameValuePairs.put("lng", lng);
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
Log.i("Latitude", lat+"");
Post post = new Post(getApplicationContext());
String result = "";
// isConnect = post.isConnected();
// if(isConnect) {
result = post.doPost(nameValuePairs);
jsonObj = new JSONObject(result);
Log.i("Result", result+"");
if(jsonObj.getInt("success") == 1)
res = true;
// }
} catch (JSONException e) {
e.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
// Intent intent = new Intent(LoginActivity.this, MainActivity.class);
// intent.putExtra("jsonObj", jsonObj.toString());
// startActivity(intent);
txtShopCode.getText().clear();
txtShopCode.requestFocus();
Toast.makeText(getBaseContext(), "Your shop is geo tagged ", Toast.LENGTH_LONG).show();
} else {
// if(isConnect){
// mPasswordView.setError(getString(R.string.error_incorrect_password));
// mPasswordView.requestFocus();
// }
// else
Toast.makeText(getBaseContext(), R.string.geoTagError, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
#Override
public void onLocationChanged(Location location) {
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();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_main, menu);
// return true;
// }
}
UPDATE
I have added thes lines in GeoTagTask the button is working the app is not crashing but I'm not sure if it's going to work if location is changed because
if( location != null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
is giving me errors .
The lines I have added
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
Problem
Problem is inside GeoTagTask ,
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
You are accessing an uninitialized variable.
Solution
Make onCreate location a global variable,
public class MainActivity extends FragmentActivity implements LocationListener {
Location location;
void onCreate() {
....
location = locationManager.getLastKnownLocation(provider);
....
}
}
Use the global variable inside GeoTagTask,
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
...
}
inside GeoTagTask location object is different one and also doesn't initilized.
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
For an app that I'm currently working on I want to set up a button that finds the distance between two markers on a google maps activity and when you click the button it shows the distance between your current location and the other marker
I don't have any code in my java class for the button yet but at the moment I'm just wondering how I actually find the distance between my current location and my set up marker. Here's my code for finding the users current location and it has a marker set up in a random location.
package dashpage.example.com.myapplication;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
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.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(53.3835, 6.5996)).title("Marker"));
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
//mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
I also know that for finding the distance between two markers in Android Studio you'd use something like
Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lon1);
Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);
float distanceInMeters = loc1.distanceTo(loc2);
So I'm just wondering if anybody would be able to help me implement the code for finding the distance because I'm not sure where it should go in my class or if I'll have to redo some parts of the class to make the distance work
When trying to find distance between markers, I would recommend to convert them back to Location objects to be able to use the in-built Android method of calculating distance.
Given some Marker marker that you have set up and have access through onMarkerClick() or already saved and current position Location currentLocation, inside your onClick(View v) method for the Button:
LatLng markerLatLng = marker.getPosition();
Location markerLocation = new Location("");
markerLocation.setLatitude(markerLatLng.latitude);
markerLocation.setLongitude(markerLatLng.longitude);
currentLocation.distanceTo(markerLocation);
Hi I made an example and its like your qquestion.But you must customise for your build.You can use Collections class.Its easy and perfectly work.
Comparator<Sinemalar> comparator=new Comparator<Sinemalar>() {
#Override
public int compare(Sinemalar left, Sinemalar right) {
return (int)(left.getDistance()-right.getDistance());
}
};
Collections.sort(sinemalarList, comparator);
I hope work for you
public float distanceCounter(String value, Context context) {
Location cinemaLocation = new Location("CinemaLocation");
String s = new String(value);
String[] result = s.split(",");
List<String> elephantList = Arrays.asList(s.split(","));
String longitude = elephantList.get(1);
String latitude = elephantList.get(0);
cinemaLocation.setLatitude(Double.parseDouble(latitude));
cinemaLocation.setLongitude(Double.parseDouble(longitude));
float distance = getCurrrentLocation(context).distanceTo(cinemaLocation)/1000 ;
return distance;
}
String value=34.54665 , 23.54546
Full code here you can use with here.Sory i forgot.
when ia'm building my app i just wanna to display a map with my location
i codded it , but it required me a good internet connection to display or it will crash my all app ..
how can i deal with this issue
is there is any kind of maps can i use in my programming except google maps ???
or any code tricks ??
here is my code :
package com.gideon.address;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
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;
public class map extends android.support.v4.app.FragmentActivity {
private GoogleMap mMap;
private double mlat;
private double mlon;
LocationManager locationManager;
LocationListener locationListener;
// All static variables
static final String URL = "http://procode.co/app_ss/search.php?lat=222&lng=656.111&radius=3200000";
// XML node keys
static final String KEY_MARKER = "marker"; // parent node
static final String KEY_LAT = "lat";
static final String KEY_LNG = "lng";
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_MARKER);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
final ProgressDialog dialog = ProgressDialog.show(map.this, "",
"Loading..Wait..", true);
dialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// your code here
setUpMapIfNeeded();
dialog.dismiss();
}
}, 10000);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
// if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Check if we were successful in obtaining the map.
// if (mMap != null) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
26.0000, 30.0000), 6));
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
public boolean onMyLocationButtonClick() {
locationManager = (LocationManager) map.this
.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the
// network location provider.
mlat = location.getLatitude();
mlon = location.getLongitude();
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mlat, mlon), 12));
MarkerOptions marker = new MarkerOptions().position(
new LatLng(mlat, mlon)).title("My Location");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// adding marker
mMap.addMarker(marker);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
double x = Double.parseDouble(parser.getValue(e,
KEY_LAT));
double y = Double.parseDouble(parser.getValue(e,
KEY_LNG));
mMap.addMarker(new MarkerOptions().title("สอัิ")
.position(new LatLng(x, y)));
}
locationManager.removeUpdates(locationListener);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to
// receive location updates
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListener);
return true;
}
});
// }
// }
}
}
As an alternative to Google Maps, have a look at MapQuest.
http://developer.mapquest.com/web/products/featured/android-maps-api