I m struggling for integrating google maps in my app. I have somehow managed to display map with user location and nearby locations but the location is not updating...I have gone through the code several time but havent found a single incorrect command..plz help me sort it out..
NearbyPlacesActivity -
package com.example.travelplanner;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
/*
* MyMapActivity class forms part of Map application
* in Mobiletuts+ tutorial series:
* Using Google Maps and Google Places in Android Apps
*
* This version of the class is for the final part of the series.
*
* Sue Smith
* March/ April 2013
*/
public class NearbyPlacesActivity extends Activity implements LocationListener {
//instance variables for Marker icon drawable resources
private int userIcon, foodIcon, drinkIcon, shopIcon, otherIcon;
//the map
private GoogleMap theMap;
//location manager
private LocationManager locMan;
//user marker
private Marker userMarker;
//places of interest
private Marker[] placeMarkers;
//max
private final int MAX_PLACES = 20;//most returned from google
//marker options
private MarkerOptions[] places;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_places);
//get drawable IDs
userIcon = R.drawable.yellow_point;
foodIcon = R.drawable.red_point;
drinkIcon = R.drawable.blue_point;
shopIcon = R.drawable.green_point;
otherIcon = R.drawable.purple_point;
//find out if we already have it
if(theMap==null){
//get the map
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
//check in case map/ Google Play services not available
if(theMap!=null){
//ok - proceed
theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//create marker array
placeMarkers = new Marker[MAX_PLACES];
//update location
updatePlaces();
}
}
}
//location listener functions
#Override
public void onLocationChanged(Location location) {
Log.v("MyMapActivity", "location changed");
updatePlaces();
}
#Override
public void onProviderDisabled(String provider){
Log.v("MyMapActivity", "provider disabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.v("MyMapActivity", "provider enabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v("MyMapActivity", "status changed");
}
/*
* update the place markers
*/
private void updatePlaces(){
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
Toast.makeText(getApplicationContext(), lat+","+lng, Toast.LENGTH_LONG).show();
//create LatLng
LatLng lastLatLng = new LatLng(lat, lng);
//remove any existing marker
if(userMarker!=null) userMarker.remove();
//create and set marker properties
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
//move to location
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
//build places query string
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=7000&sensor=true" +
"&types=food|bar|movie_theater|museum|bank"+
"&key=AIzaSyBqDgqbxFenOtooTivY5YSsJ2JrwBK42hw";//ADD KEY
//execute query
new GetPlaces().execute(placesSearchStr);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
private class GetPlaces extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... placesURL) {
//fetch places
//build result as string
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
//HTTP Get receives URL string
HttpGet placesGet = new HttpGet(placeSearchURL);
//execute GET with Client - return response
HttpResponse placesResponse = placesClient.execute(placesGet);
//check response status
StatusLine placeSearchStatus = placesResponse.getStatusLine();
//only carry on if response is OK
if (placeSearchStatus.getStatusCode() == 200) {
//get response entity
HttpEntity placesEntity = placesResponse.getEntity();
//get input stream setup
InputStream placesContent = placesEntity.getContent();
//create reader
InputStreamReader placesInput = new InputStreamReader(placesContent);
//use buffered reader to process
BufferedReader placesReader = new BufferedReader(placesInput);
//read a line at a time, append to string builder
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return placesBuilder.toString();
}
//process data retrieved from doInBackground
protected void onPostExecute(String result) {
//parse place data returned from Google Places
//remove existing markers
if(placeMarkers!=null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
}
try {
//parse JSON
//create JSONObject, pass stinrg returned from doInBackground
JSONObject resultObject = new JSONObject(result);
//get "results" array
JSONArray placesArray = resultObject.getJSONArray("results");
//marker options for each place returned
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p=0; p<placesArray.length(); p++) {
//parse each place
//if any values are missing we won't show the marker
boolean missingValue=false;
LatLng placeLL=null;
String placeName="";
String vicinity="";
int currIcon = otherIcon;
try{
//attempt to retrieve place data values
missingValue=false;
//get place at this index
JSONObject placeObject = placesArray.getJSONObject(p);
//get location section
JSONObject loc = placeObject.getJSONObject("geometry")
.getJSONObject("location");
//read lat lng
placeLL = new LatLng(Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
//get types
JSONArray types = placeObject.getJSONArray("types");
//loop through types
for(int t=0; t<types.length(); t++){
//what type is it
String thisType=types.get(t).toString();
//check for particular types - set icons
if(thisType.contains("food")){
currIcon = foodIcon;
break;
}
else if(thisType.contains("bar")){
currIcon = drinkIcon;
break;
}
else if(thisType.contains("movie_theater")){
currIcon = shopIcon;
break;
}
}
//vicinity
vicinity = placeObject.getString("vicinity");
//name
placeName = placeObject.getString("name");
}
catch(JSONException jse){
Log.v("PLACES", "missing value");
missingValue=true;
jse.printStackTrace();
}
//if values missing we don't display
if(missingValue) places[p]=null;
else
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
}
catch (Exception e) {
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length; p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=theMap.addMarker(places[p]);
}
}
}
}
#Override
protected void onResume() {
super.onResume();
if(theMap!=null){
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
}
#Override
protected void onPause() {
super.onPause();
if(theMap!=null){
locMan.removeUpdates(this);
}
}
}
There is no error in logcat. The Manifest is accurate as per my concern...the API keys are also correct..
There is one more thing I want to know....How can I show a particular city's map by clickin on a button of previous activity..for eg: In activity one i typed New York in edittext and clicked button and it opened Activity two containing map and points to New York city...I also want to show the tourist attractions in newyork by different markers.... Can someone show me a way or tut for this..thanks in advance
This is the Revised code as per your guidance..
package com.example.travelplanner;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
/*
* MyMapActivity class forms part of Map application
* in Mobiletuts+ tutorial series:
* Using Google Maps and Google Places in Android Apps
*
* This version of the class is for the final part of the series.
*
* Sue Smith
* March/ April 2013
*/
public class NearbyPlacesActivity extends Activity implements LocationListener {
//instance variables for Marker icon drawable resources
private int userIcon, foodIcon, drinkIcon, shopIcon, otherIcon;
//the map
private GoogleMap theMap;
//location manager
private LocationManager locMan;
//user marker
private Marker userMarker;
//places of interest
private Marker[] placeMarkers;
//max
private final int MAX_PLACES = 20;//most returned from google
//marker options
private MarkerOptions[] places;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_places);
//get drawable IDs
userIcon = R.drawable.yellow_point;
foodIcon = R.drawable.red_point;
drinkIcon = R.drawable.blue_point;
shopIcon = R.drawable.green_point;
otherIcon = R.drawable.purple_point;
//find out if we already have it
if(theMap==null){
//get the map
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
//check in case map/ Google Play services not available
if(theMap!=null){
//ok - proceed
theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//create marker array
placeMarkers = new Marker[MAX_PLACES];
}
}
}
//location listener functions
#Override
public void onLocationChanged(Location location) {
Log.v("MyMapActivity", "location changed");
updatePlaces(location);
}
#Override
public void onProviderDisabled(String provider){
Log.v("MyMapActivity", "provider disabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.v("MyMapActivity", "provider enabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v("MyMapActivity", "status changed");
}
/*
* update the place markers
*/
private void updatePlaces(Location givenlocation){
//get location manager
double lat = givenlocation.getLatitude();
double lng = givenlocation.getLongitude();
Toast.makeText(getApplicationContext(), lat+","+lng, Toast.LENGTH_LONG).show();
//create LatLng
LatLng lastLatLng = new LatLng(lat, lng);
//remove any existing marker
if(userMarker!=null) userMarker.remove();
//create and set marker properties
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
//move to location
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
//build places query string
#SuppressWarnings("deprecation")
String encodedstr = URLEncoder.encode("food|bar|movie_theater|museum|bank");
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=7000&sensor=true"+
"&types="+encodedstr+
"&key=AIzaSyBqDgqbxFenOtooTivY5YSsJ2JrwBK42hw";//ADD KEY
//execute query
new GetPlaces().execute(placesSearchStr);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
private class GetPlaces extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... placesURL) {
//fetch places
//build result as string
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
//HTTP Get receives URL string
HttpGet placesGet = new HttpGet(placeSearchURL);
//execute GET with Client - return response
HttpResponse placesResponse = placesClient.execute(placesGet);
//check response status
StatusLine placeSearchStatus = placesResponse.getStatusLine();
//only carry on if response is OK
if (placeSearchStatus.getStatusCode() == 200) {
//get response entity
HttpEntity placesEntity = placesResponse.getEntity();
//get input stream setup
InputStream placesContent = placesEntity.getContent();
//create reader
InputStreamReader placesInput = new InputStreamReader(placesContent);
//use buffered reader to process
BufferedReader placesReader = new BufferedReader(placesInput);
//read a line at a time, append to string builder
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return placesBuilder.toString();
}
//process data retrieved from doInBackground
protected void onPostExecute(String result) {
//parse place data returned from Google Places
//remove existing markers
if(placeMarkers!=null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
}
try {
//parse JSON
//create JSONObject, pass stinrg returned from doInBackground
JSONObject resultObject = new JSONObject(result);
//get "results" array
JSONArray placesArray = resultObject.getJSONArray("results");
//marker options for each place returned
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p=0; p<placesArray.length(); p++) {
//parse each place
//if any values are missing we won't show the marker
boolean missingValue=false;
LatLng placeLL=null;
String placeName="";
String vicinity="";
int currIcon = otherIcon;
try{
//attempt to retrieve place data values
missingValue=false;
//get place at this index
JSONObject placeObject = placesArray.getJSONObject(p);
//get location section
JSONObject loc = placeObject.getJSONObject("geometry")
.getJSONObject("location");
//read lat lng
placeLL = new LatLng(Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
//get types
JSONArray types = placeObject.getJSONArray("types");
//loop through types
for(int t=0; t<types.length(); t++){
//what type is it
String thisType=types.get(t).toString();
//check for particular types - set icons
if(thisType.contains("food")){
currIcon = foodIcon;
break;
}
else if(thisType.contains("bar")){
currIcon = drinkIcon;
break;
}
else if(thisType.contains("movie_theater")){
currIcon = shopIcon;
break;
}
}
//vicinity
vicinity = placeObject.getString("vicinity");
//name
placeName = placeObject.getString("name");
}
catch(JSONException jse){
Log.v("PLACES", "missing value");
missingValue=true;
jse.printStackTrace();
}
//if values missing we don't display
if(missingValue) places[p]=null;
else
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
}
catch (Exception e) {
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length; p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=theMap.addMarker(places[p]);
}
}
}
}
#Override
protected void onResume() {
super.onResume();
if(theMap!=null){
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
updatePlaces(lastLoc);
}
}
#Override
protected void onPause() {
super.onPause();
if(theMap!=null){
locMan.removeUpdates(this);
}
}
}
Please have a check on it...it is not updating my location...although its showinng nearby locations..thanks in advance
The problems seems to be that whenever you get a call to onLocationChanged(), you are calling updatePlaces() method where you are reintialising your location manager. The line locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE); will return a new instance of the location manager and then you are calling getLastKnownLocation for this new location manager. Your getLastKnownLocation must be returning an outdated location information and hence you may not be seeing any update. You end up using this location instead of the fresh location return by your change listener.
You can initialise these and call updatePlaces in onResume like below :
#Override
protected void onResume() {
super.onResume();
if(theMap!=null){
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
updatePlaces(lastLoc)
}
}
Modify locationchanged:
#Override
public void onLocationChanged(Location location) {
Log.v("MyMapActivity", "location changed");
updatePlaces(location);
}
Modify updateplaces:
private void updatePlaces(Location givenlocation){
double lat = givenlocation.getLatitude();
double lng = givenlocation.getLongitude();
Toast.makeText(getApplicationContext(), lat+","+lng, Toast.LENGTH_LONG).show();
//create LatLng
LatLng lastLatLng = new LatLng(lat, lng);
*****Call further steps using the above location ******
Currently you are using the location API that is part of android platform . I would also suggest you can migrate to the new The Google Location Services API, part of Google Play Services as it handles location updates and battery conservation in an improved manner.
Related
Hi I am developing an application in which i wish to open maps with my current location. And after showing the current location i wish to open some of the custom places to show some description or information regarding. One way i found is using markers. Is that the only way to achieve this. I have gone through google places api and found a way here. But when i try to implement it. I am getting an error in my code
com.example.vivek.yes, PID: 2644
10-20 14:11:56.729 2644-2644/? E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vivek.yes/com.example.vivek.yes.HomePlacesActivity}: java.lang.NullPointerException: GoogleApiClient must not be null
the code which i have written for adding the places in the api are
AddPlaceRequest place =
new AddPlaceRequest(
"Manly Sea Life Sanctuary", // Name
new LatLng(-33.7991, 151.2813), // Latitude and longitude
"W Esplanade, Manly NSW 2095", // Address
Collections.singletonList(Place.TYPE_AQUARIUM), // Place types
"+61 1800 199 742", // Phone number
Uri.parse("http://www.manlysealifesanctuary.com.au/") // Website
);
Places.GeoDataApi.addPlace(mGoogleApiClient, place)
.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
/*Log.i(TAG, "Place add result: " + places.getStatus().toString());
Log.i(TAG, "Added place: " + places.get(0).getName().toString());*/
places.release();
}
});
which is also taken from the native google developers reference. Please suggest me a way how to achieve this. Should i stop implementing this approach move ahead with markers.??
edit 1: Adding the complete code
package com.example.vivek.yes;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
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.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
public class HomePlacesActivity extends FragmentActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
GoogleMap mGoogleMap;
Spinner mSprPlaceType;
private GoogleApiClient mGoogleApiClient;
String[] mPlaceType = null;
String[] mPlaceTypeName = null;
double mLatitude = 0;
double mLongitude = 0;
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homeplaces);
// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
Button btnFind;
// Getting reference to Find Button
btnFind = (Button) findViewById(R.id.btn_find);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
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
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Google Map
mGoogleMap = fragment.getMap();
// Enabling MyLocation in Google Map
mGoogleMap.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 From GPS
try {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
catch (SecurityException e){
e.printStackTrace();
}
// Setting click event lister for the find button
btnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=5000");
sb.append("&sensor=true");
sb.append("&key=AIzaSyA0z5zRlZCsJv3jU5OvTmt51Op7h_zZVVs");
// Creating a new non-ui thread task to download json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
});
}
/*mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
AddPlaceRequest place =
new AddPlaceRequest(
"Manly Sea Life Sanctuary", // Name
new LatLng(-33.7991, 151.2813), // Latitude and longitude
"W Esplanade, Manly NSW 2095", // Address
Collections.singletonList(Place.TYPE_AQUARIUM), // Place types
"+61 1800 199 742", // Phone number
Uri.parse("http://www.manlysealifesanctuary.com.au/") // Website
);
Places.GeoDataApi.addPlace(mGoogleApiClient, place)
.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
*//*Log.i(TAG, "Place add result: " + places.getStatus().toString());
Log.i(TAG, "Added place: " + places.get(0).getName().toString());*//*
places.release();
}
});
mGoogleApiClient.disconnect();*/
}
/** A method to download json data from url */
#SuppressLint("LongLogTag")
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
mGoogleMap.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions);
}
}
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_home_places, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#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
}
}
The error is instructive.
java.lang.NullPointerException: GoogleApiClient must not be null
You have not initialised your GoogleApiClient.
Taken from the Google Places API for Android
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
Also make sure you have your keys and the correct tags in your manifest.
I am having trouble reversing Geo-coding using getFromLocation.
I am using Android Studio and passing the Coordinates via the Device Monitor.
The coordinates show alright, but the address remains empty.
I have tried a number of solutions posted here on StackOverflow, even known none crashes, I still can't get the address.
Here is the snippet of the code. I am using.
#Override
public void onLocationChanged(Location location){
double lat = (location.getLatitude());
double lng = (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
//Get address base on location
try{
Geocoder geo = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geo.getFromLocation(lat, lng, 1);
if (addresses.isEmpty()) {
endereco.setText("Waiting for Location");
}
else {
if (addresses.size() > 0) {
Log.d(TAG,addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
On the Geocoder line, I have tried this aswell
Geocoder geo = new Geocoder(GPSActivity.this.getApplicationContext(), Locale.getDefault());
And if needed here is the code of the entire activity
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.Locale;
/**
* Created by Usuário on 05/02/2015.
*/
public class GPSActivity extends Activity implements LocationListener {
private static final String TAG = null;
private TextView latituteField;
private TextView longitudeField;
private TextView endereco;
private LocationManager locationManager;
private String provider;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
endereco = (TextView) findViewById(R.id.Endereco);
//Get the Location Manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Define the criteria how to select location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria,false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null){
System.out.println("Provider " + provider + " has been selected");
onLocationChanged(location);
}else{
latituteField.setText("Locação não disponível");
longitudeField.setText("Locação não disponível");
}
}
/**
* Request updates at startup
*/
#Override
protected void onResume(){
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/**
* Remove the LocationListener updates when Activity is paused
*/
#Override
protected void onPause(){
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location){
double lat = (location.getLatitude());
double lng = (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
//Get address base on location
try{
Geocoder geo = new Geocoder(GPSActivity.this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(lat, lng, 1);
if (addresses.isEmpty()) {
endereco.setText("Waiting for Location");
}
else {
if (addresses.size() > 0) {
Log.d(TAG,addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
//TODO Auto-generated method tub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
I made a couple of changes in the code and manage to get it to work.
The thing that solved the problem is the bit.
char[] buffer = new char[2048];
Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");
while (true) {
int n = reader.read(buffer);
if (n < 0) {
break;
}
stringBuilder.append(buffer, 0, n);
}
But since I changed a lot of stuff, I will post the complete code bellow.
package br.com.agenciaeisberg.qm;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
/**
* Created by Usuário on 05/02/2015.
*/
public class GPSActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private TextView endereco;
private LocationManager locationManager;
private String provider;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
endereco = (TextView) findViewById(R.id.Endereco);
//Get the Location Manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Define the criteria how to select location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria,false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null){
System.out.println("Provider " + provider + " has been selected");
onLocationChanged(location);
}else{
latituteField.setText("Locação não disponível");
longitudeField.setText("Locação não disponível");
}
}
/**
* Request updates at startup
*/
#Override
protected void onResume(){
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/**
* Remove the LocationListener updates when Activity is paused
*/
#Override
protected void onPause(){
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location){
double lat = (location.getLatitude());
double lng = (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
// Encontrando Endereço
new EncontrarEndereco().execute();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
//TODO Auto-generated method tub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
class EncontrarEndereco extends AsyncTask<String, String, JSONObject> {
ProgressDialog pDialog = new ProgressDialog(GPSActivity.this);
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog.setMessage("Aguarde, enquanto buscamos seu endereço");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
double lat = -19.971864410192393;
double lng = -43.97544760674483;
HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true&language=pt®ion=BR&output=xml&oe=utf8");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
protected JSONObject doInBackground (String... args){
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
char[] buffer = new char[2048];
Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");
while (true) {
int n = reader.read(buffer);
if (n < 0) {
break;
}
stringBuilder.append(buffer, 0, n);
}
int b;
while ((b = reader.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
protected void onPostExecute(final JSONObject jsonObject) {
// Dismiss a caixa de dialogo depois de buscar todos os items
String numero;
String rua;
String bairro;
String cidade;
String estado;
String pais;
String endereco_compelto;
pDialog.dismiss();
Log.i("JSON string =>", jsonObject.toString());
try {
String status = jsonObject.getString("status");
Log.i("status", status);
if(status.equalsIgnoreCase("OK")){
JSONArray results = jsonObject.getJSONArray("results");
JSONObject r = results.getJSONObject(0);
JSONArray addressComponentsArray = r.getJSONArray("address_components");
JSONObject addressComponents = addressComponentsArray.getJSONObject(0);
numero = addressComponents.getString("short_name");
Log.i("Número", numero);
JSONObject addressComponents1 = addressComponentsArray.getJSONObject(1);
rua = addressComponents1.getString("long_name");
Log.i("Rua", rua);
JSONObject addressComponents2 = addressComponentsArray.getJSONObject(2);
bairro = addressComponents2.getString("long_name");
Log.i("Bairro ", bairro);
JSONObject addressComponents3 = addressComponentsArray.getJSONObject(3);
cidade = addressComponents3.getString("long_name");
Log.i("Cidade ", cidade);
JSONObject addressComponents5 = addressComponentsArray.getJSONObject(5);
estado = addressComponents5.getString("short_name");
Log.i("Estado ", estado);
JSONObject addressComponents6 = addressComponentsArray.getJSONObject(6);
pais = addressComponents6.getString("long_name");
Log.i("Pais ", pais);
endereco_compelto = rua + ", " + numero + " - " + bairro + ", " + cidade + " - " + estado + ", " + pais;
endereco.setText(endereco_compelto);
}
}catch (JSONException e) {
Log.e("testing","Failed to load JSON");
e.printStackTrace();
}
}
}
}
I have this class to get actual location , the second point (marker) is set by another fragment.
I really need to update my location automatically instead clicking the google button for it.
How can I make this? What is the best way to make this? I don´t figure out where to place it.
I was thinking in placing a timer or something like that. I would prefer to make it with just google maps functionalities.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
}
}, 0, 500000);
Or with a handler
final Runnable r = new Runnable() {
public void run() {
//Here add your code location listener call
handler.postDelayed(this, 300000 );
}
};
handler.postDelayed(r, 300000 );
Here is the googleXdon class:
package com.example.mysqltest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONObject;
import android.content.Context;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class googleXdon extends Fragment {
static GoogleMap map;
static LatLng myPosition;
static RadioButton rbDriving;
static RadioButton rbBiCycling;
static RadioButton rbWalking;
RadioGroup rgModes;
static ArrayList<LatLng> markerPoints;
static int mMode=0;
final static int MODE_DRIVING=0;
final static int MODE_BICYCLING=1;
final static int MODE_WALKING=2;
int fragVal;
static Context ontext2;
static googleXdon init(int val, Context contexts) {
googleXdon X = new googleXdon();
ontext2 = contexts;
// Supply val input as an argument.
Bundle args = new Bundle();
args.putInt("val", val);
X.setArguments(args);
return X;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.actgooglex, container,
false);
fragVal = getArguments() != null ? getArguments().getInt("val") : 1;
// Getting reference to rb_driving
rbDriving = (RadioButton) layoutView.findViewById(R.id.rb_driving);
// Getting reference to rb_bicylcing
rbBiCycling = (RadioButton) layoutView.findViewById(R.id.rb_bicycling);
// Getting reference to rb_walking
rbWalking = (RadioButton) layoutView.findViewById(R.id.rb_walking);
// Getting Reference to rg_modes
rgModes = (RadioGroup) layoutView.findViewById(R.id.rg_modes);
rgModes.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// Checks, whether start and end locations are captured
if(markerPoints.size() >= 2){
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
});
// Initializing
markerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
map = fm.getMap();
// Enable MyLocation Button in the Map
map.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
/*LocationManager locationManager = (LocationManager) ontext2.getSystemService(Context.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
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null) {
// 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);
myPosition = new LatLng(latitude, longitude);
markerPoints.add(myPosition);*/
// Setting onclick event listener for the map
/* map.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Already two locations value is 1
if(markerPoints.size()>1){
markerPoints.clear();
map.clear();
}
// Adding new item to the ArrayList
markerPoints.add(point);
// Draws Start and Stop markers on the Google Map
drawStartStopMarkers();
// Checks, whether start and end locations are captured
if(markerPoints.size() >= 2){
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
});
}*/
return layoutView;
}
//este antes no era final
public static void agregarMarket( LatLng point) {
// Already two locations
if(markerPoints.size()>1){
markerPoints.clear();
map.clear();
}
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) ontext2.getSystemService(Context.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
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null) {
// 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);
myPosition = new LatLng(latitude, longitude);
markerPoints.add(myPosition);
// Adding new item to the ArrayList
markerPoints.add(point);
// Draws Start and Stop markers on the Google Map
drawStartStopMarkers();
// Checks, whether start and end locations are captured
if(markerPoints.size() >= 2){
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
}
// Drawing Start and Stop locations
private static void drawStartStopMarkers(){
for(int i=0;i<markerPoints.size();i++){
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(markerPoints.get(i) );
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(i==0){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(i==1){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
map.addMarker(options);
}
}
private static String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Travelling Mode
String mode = "mode=driving";
if(rbDriving.isChecked()){
mode = "mode=driving";
mMode = 0 ;
}else if(rbBiCycling.isChecked()){
mode = "mode=bicycling";
mMode = 1;
}else if(rbWalking.isChecked()){
mode = "mode=walking";
mMode = 2;
}
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+mode;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
private static String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
static class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
static class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
// Changing the color polyline according to the mode
if(mMode==MODE_DRIVING)
lineOptions.color(Color.RED);
else if(mMode==MODE_BICYCLING)
lineOptions.color(Color.GREEN);
else if(mMode==MODE_WALKING)
lineOptions.color(Color.BLUE);
}
if(result.size()<1){
Toast.makeText(ontext2, "No Points", Toast.LENGTH_SHORT).show();
return;
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} */
}
First of all see this link which says to use a Handler to request one update with requestSingleUpdate() every 5 minutes.
Here is an example for the onLocationChanged()...
inside onCreate()
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
MyLocationListener class
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location)
{
//Set marker here
LatLng pos=new LatLng(location.getLatitude(), location.getLongitude());
map.addMarker(new MarkerOptions().position(pos).icon(BitmapDescriptorFactory.fromResource(markericon)));
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
There is no any guarantee how often the location changes will come. And you can make it in two ways.
You do not need to read the location every X seconds. Just save the last location from onLocationChanged() and use it on your timer ticks. You can also check if this location is different from the last used, if this matters
The other way is to use LocationClient and its method getLastLocation(). You can use getLastLocation() in any time (after proper initialization), like every 5 sec.
Something like this:
timer.scheduleAtFixedRate( new UpdateLocationTask(), 1000, 5000 );
class UpdateLocationTask extends TimerTask
{
public void run()
{
final Location location = mLocationClient.getLastLocation();
if ( location != null )
{
runOnUiThread( new Runnable()
{
public void run()
{
// do whatever you want here
}
});
}
}
}
I've developed an Android application that uses Google Maps API v2 to display a map that show the user location, different other points (shops...), a tracking blue point that represents the user when he moves and direction to a specific location.
All of this is correctly working on some devices, but not on others, and I don't know why?
Works well with Android 4.2.2, 4.3, 2.3.7
But not with Android 2.3.6, 4.0.1 for example.
Is it something related to Google Play Services that maybe is not installed on the other devices?
Is there something wrong with my code?
Here's my code:
package com.app.connexion;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;
import com.datatype.AppData;
import com.datatype.OrderInfo;
import com.datatype.ShopInfo;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.utils.GMapV2Direction;
import com.utils.RequestTask;
import com.utils.RequestTask1;
import com.utils.RequestTaskDelegate;
import com.utils.WebServiceMethod;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class DetailOrder extends FragmentActivity implements RequestTaskDelegate{
/** Called when the activity is first created. */
String request;
String basket;
ImageButton checkout;
ProgressDialog prog;
GoogleMap mMap;
GMapV2Direction md;
String toaddr = "";
LatLng fromPosition = new LatLng(13.687140112679154, 100.53525868803263);
LatLng toPosition = new LatLng(13.683660045847258, 100.53900808095932);
String orderid,gps;
PolylineOptions rectLine;
ArrayList<ShopInfo> shops;
ImageButton posbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
setContentView(R.layout.detailorderone);
checkout = (ImageButton)findViewById(R.id.imageButton1);
orderid = getIntent().getStringExtra("orderid");
gps = getIntent().getStringExtra("others");
posbtn = (ImageButton)findViewById(R.id.imageButton2);
posbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mMap.clear();
sendGPS();
positionredraw();
}
});
checkout.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(v.getContext(),DetailProductVC.class);
intent.putExtra("basket", basket);
intent.putExtra("orderid", orderid);
startActivity(intent);
}
});
prog = ProgressDialog.show(this, "", "Processing...",true,false);
RequestTask task = new RequestTask();
task.delegate = this;
request = WebServiceMethod.kCommandeInfosMethode;
task.execute(request,orderid);
getCurrentPosition();
}
public void positionredraw()
{
//prog = ProgressDialog.show(this, "", "Processing...",true,false);
viewmap1();
}
public void getCurrentPosition()
{
mMap = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
mMap.setMyLocationEnabled(true);
UiSettings ui = mMap.getUiSettings();
ui.setMyLocationButtonEnabled(false);
mMap.getMyLocation();
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
fromPosition = new LatLng(location.getLatitude(),location.getLongitude());
/*
mMap.clear();
sendGPS();
positionredraw();
*/
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(provider, 1000, 1, locationListener);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
String message = String.format("Current Location \n Longitude: %1$s \n Latitude: %2$s",location.getLongitude(), location.getLatitude());
fromPosition = new LatLng(location.getLatitude(),location.getLongitude());
//fromPosition = new LatLng(48.8966175,2.327197);
Log.d("current",message);
}
}
public void sendGPS()
{
Thread t;
t = new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try{
sendGPSData();
}catch(Exception e)
{
}
}
});
t.start();
}
public void sendGPSData()
{
SharedPreferences shared = getSharedPreferences("connexion",MODE_PRIVATE);
String shopperid = shared.getString("shopperid", "");
HttpClient client = new DefaultHttpClient();
HttpPost post;
post = new HttpPost(WebServiceMethod.serverurl);
Log.d("gps", "send gps");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("key", WebServiceMethod.key));
nameValuePairs.add(new BasicNameValuePair("secret", WebServiceMethod.secret));
nameValuePairs.add(new BasicNameValuePair("shopperid", shopperid));
nameValuePairs.add(new BasicNameValuePair("latitude", String.valueOf(fromPosition.latitude)));
nameValuePairs.add(new BasicNameValuePair("longitude", String.valueOf(fromPosition.longitude)));
nameValuePairs.add(new BasicNameValuePair("act", WebServiceMethod.kUpdateShopperStatusMethode));
try{
post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
HttpResponse response = client.execute(post);
//response = client.execute(post);
HttpEntity resEntity = response.getEntity();
String str = EntityUtils.toString(resEntity);
Log.d("gpsResult",str);
}catch(Exception e)
{
}
}
public void viewmap1()
{
LatLng from,to;
//prog.dismiss();
rectLine = new PolylineOptions().width(10).color(Color.BLUE);
mMap.addMarker(new MarkerOptions().position(fromPosition).title("Moi"));
//mMap.addMarker(new MarkerOptions().position(toPosition).title("B"));
String[] gpss = gps.split("#");
from = fromPosition;
to = null;
for(int i = 0; i < gpss.length - 1;i++)
{
to = new LatLng(Double.parseDouble(gpss[i].split(",")[0]),Double.parseDouble(gpss[i].split(",")[1]));
viewmap(from,to);
from = to;
}
int len = gpss.length - 1;
viewmap(from,new LatLng(Double.parseDouble(gpss[len].split(",")[0]),Double.parseDouble(gpss[len].split(",")[1])));
ArrayList<OrderInfo> orders = ((AppData)this.getApplication()).orders;
for(int i = 0; i < gpss.length;i++)
{
OrderInfo order = orders.get(i);
to = new LatLng(Double.parseDouble(gpss[i].split(",")[0]),Double.parseDouble(gpss[i].split(",")[1]));
mMap.addMarker(new MarkerOptions().position(to).title(order.name));
}
LatLng coordinates = new LatLng((fromPosition.latitude + to.latitude)/2, (fromPosition.longitude + to.longitude)/2);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 13));
mMap.addPolyline(rectLine);
try{
for(int i = 0;i < shops.size();i++)
{
mMap.addMarker(new MarkerOptions().position(shops.get(i).pos).title(shops.get(i).name));
}
}catch(Exception e)
{
}
}
public void viewmap(LatLng from,LatLng to)
{
SharedPreferences shared = getSharedPreferences("connexion",MODE_PRIVATE);
String type = shared.getString("type", "");
md = new GMapV2Direction(type);
//LatLng coordinates = new LatLng(13.685400079263206, 100.537133384495975);
Document doc;
if(type.equals("0"))
doc = md.getDocument(from, to, GMapV2Direction.MODE_WALKING);
else
doc = md.getDocument(from, to, GMapV2Direction.MODE_DRIVING);
/*
int duration = md.getDurationValue(doc);
String distance = md.getDistanceText(doc);
String start_address = md.getStartAddress(doc);
String copy_right = md.getCopyRights(doc);
*/
ArrayList<LatLng> directionPoint = md.getDirection(doc);
for(int i = 0 ; i < directionPoint.size() ; i++) {
rectLine.add(directionPoint.get(i));
}
}
#Override
public void backgroundActivityComp(String response) {
// TODO Auto-generated method stub
if(request.equals(WebServiceMethod.kCommandeInfosMethode))
{
try {
JSONObject json = new JSONObject(response);
String str = json.getString("Results");
if(!str.equals("false"))
{
json = new JSONObject(str);
JSONObject gps = new JSONObject(json.getString("addr"));
JSONObject gps1 = new JSONObject(gps.getString("gps"));
toPosition = new LatLng(Double.parseDouble(gps1.getString("latitude")),Double.parseDouble(gps1.getString("longitude")));
toaddr = gps.getString("name");
basket = json.getString("basket");
SharedPreferences shared = getSharedPreferences("connexion",MODE_PRIVATE);
RequestTask task = new RequestTask();
task.delegate = this;
request = WebServiceMethod.kShipInfosMethode;
task.execute(request,shared.getString("shipid", ""));
return;
}
}catch(Exception e)
{
e.printStackTrace();
prog.dismiss();
}
return;
}
if(request.equals(WebServiceMethod.kShipInfosMethode))
{
try{
prog.dismiss();
JSONObject json = new JSONObject(response);
shops = new ArrayList<ShopInfo>();
if(!json.getString("Results").equals("false"))
{
json = new JSONObject(json.getString("Results"));
//shops = new ArrayList<ShopInfo>();
JSONArray jsons = new JSONArray(json.getString("shops"));
for(int i = 0; i < jsons.length();i++)
{
ShopInfo shop = new ShopInfo();
json = new JSONObject(jsons.get(i).toString());
shop.name = json.getString("name");
shop.pos = new LatLng(Double.parseDouble(json.getString("latitude")),Double.parseDouble(json.getString("longitude")));
shops.add(shop);
}
viewmap1();
return;
}
}
catch(Exception e)
{
prog.dismiss();
return;
}
}
}
}
I believe there were some updates with Google Maps, which were not applied on older devices. Try updating older devices, if not done so. Or just make another version of app for older devices
I have succeed in making a map that shows nearby locations but its not updating the locations...Is there something wrong with the code..coz i m not finding anythin wrong...any help wud be appreciated..thanks in advance
package com.example.travelplanner;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class NearbyPlacesActivity extends Activity implements LocationListener {
//instance variables for Marker icon drawable resources
private int userIcon, foodIcon, drinkIcon, shopIcon, otherIcon;
//the map
private GoogleMap theMap;
//location manager
private LocationManager locMan;
//user marker
private Marker userMarker;
//places of interest
private Marker[] placeMarkers;
//max
private final int MAX_PLACES = 20;//most returned from google
//marker options
private MarkerOptions[] places;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_places);
//get drawable IDs
userIcon = R.drawable.yellow_point;
foodIcon = R.drawable.red_point;
drinkIcon = R.drawable.blue_point;
shopIcon = R.drawable.green_point;
otherIcon = R.drawable.purple_point;
//find out if we already have it
if(theMap==null){
//get the map
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
//check in case map/ Google Play services not available
if(theMap!=null){
//ok - proceed
theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//create marker array
placeMarkers = new Marker[MAX_PLACES];
}
}
}
//location listener functions
#Override
public void onLocationChanged(Location location) {
Log.v("MyMapActivity", "location changed");
updatePlaces(location);
}
#Override
public void onProviderDisabled(String provider){
Log.v("MyMapActivity", "provider disabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.v("MyMapActivity", "provider enabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v("MyMapActivity", "status changed");
}
/*
* update the place markers
*/
private void updatePlaces(Location givenlocation){
//get location manager
double lat = givenlocation.getLatitude();
double lng = givenlocation.getLongitude();
Toast.makeText(getApplicationContext(), lat+","+lng, Toast.LENGTH_LONG).show();
//create LatLng
LatLng lastLatLng = new LatLng(lat, lng);
//remove any existing marker
if(userMarker!=null) userMarker.remove();
//create and set marker properties
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
//move to location
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
//build places query string
#SuppressWarnings("deprecation")
String encodedstr = URLEncoder.encode("food|bar|movie_theater|museum|bank");
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=7000&sensor=true"+
"&types="+encodedstr+
"&key=AIzaSyBqDgqbxFenOtooTivY5YSsJ2JrwBK42hw";//ADD KEY
//execute query
new GetPlaces().execute(placesSearchStr);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
private class GetPlaces extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... placesURL) {
//fetch places
//build result as string
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
//HTTP Get receives URL string
HttpGet placesGet = new HttpGet(placeSearchURL);
//execute GET with Client - return response
HttpResponse placesResponse = placesClient.execute(placesGet);
//check response status
StatusLine placeSearchStatus = placesResponse.getStatusLine();
//only carry on if response is OK
if (placeSearchStatus.getStatusCode() == 200) {
//get response entity
HttpEntity placesEntity = placesResponse.getEntity();
//get input stream setup
InputStream placesContent = placesEntity.getContent();
//create reader
InputStreamReader placesInput = new InputStreamReader(placesContent);
//use buffered reader to process
BufferedReader placesReader = new BufferedReader(placesInput);
//read a line at a time, append to string builder
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return placesBuilder.toString();
}
//process data retrieved from doInBackground
protected void onPostExecute(String result) {
//parse place data returned from Google Places
//remove existing markers
if(placeMarkers!=null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
}
try {
//parse JSON
//create JSONObject, pass stinrg returned from doInBackground
JSONObject resultObject = new JSONObject(result);
//get "results" array
JSONArray placesArray = resultObject.getJSONArray("results");
//marker options for each place returned
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p=0; p<placesArray.length(); p++) {
//parse each place
//if any values are missing we won't show the marker
boolean missingValue=false;
LatLng placeLL=null;
String placeName="";
String vicinity="";
int currIcon = otherIcon;
try{
//attempt to retrieve place data values
missingValue=false;
//get place at this index
JSONObject placeObject = placesArray.getJSONObject(p);
//get location section
JSONObject loc = placeObject.getJSONObject("geometry")
.getJSONObject("location");
//read lat lng
placeLL = new LatLng(Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
//get types
JSONArray types = placeObject.getJSONArray("types");
//loop through types
for(int t=0; t<types.length(); t++){
//what type is it
String thisType=types.get(t).toString();
//check for particular types - set icons
if(thisType.contains("food")){
currIcon = foodIcon;
break;
}
else if(thisType.contains("bar")){
currIcon = drinkIcon;
break;
}
else if(thisType.contains("movie_theater")){
currIcon = shopIcon;
break;
}
}
//vicinity
vicinity = placeObject.getString("vicinity");
//name
placeName = placeObject.getString("name");
}
catch(JSONException jse){
Log.v("PLACES", "missing value");
missingValue=true;
jse.printStackTrace();
}
//if values missing we don't display
if(missingValue) places[p]=null;
else
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
}
catch (Exception e) {
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length; p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=theMap.addMarker(places[p]);
}
}
}
}
#Override
protected void onResume() {
super.onResume();
if(theMap!=null){
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
updatePlaces(lastLoc);
}
}
#Override
protected void onPause() {
super.onPause();
if(theMap!=null){
locMan.removeUpdates(this);
}
}
}
Please try to use this class.
public class LocationListenerClass {
private static LocationListenerClass instance;
private static Context context;
private LocationManager myLocationManager;
private LocationListener myLocationListener;
private static Double latitude = 0d;
private static Double longitude = 0d;
public static LocationListenerClass getInstance(Context context) {
LocationListenerClass.context = context;
if (null == instance) {
instance = new LocationListenerClass();
}
return instance;
}
public void getCurrentLocation() {
try {
myLocationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 30000, 100,
myLocationListener);
Location location;
location = myLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
myLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 30000, 100,
myLocationListener);
location = myLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
try {
latitude = location.getLatitude();
Data.CURENT_LATITUDE = latitude;
Log.v(ConstantLib.LOG, " latitude : "
+ Data.CURENT_LATITUDE);
longitude = location.getLongitude();
Data.CURENT_LONGITUDE = longitude;
Log.v(ConstantLib.LOG, " longitude : "
+ Data.CURENT_LONGITUDE);
} catch (Exception e) {
}
}
} catch (Exception e) {
}
}
public void removeLocationUpdates() {
try {
if (myLocationManager != null) {
myLocationManager.removeUpdates(myLocationListener);
}
} catch (Exception e) {
}
}
class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
try {
if (location != null) {
Data.CURENT_LATITUDE = location.getLatitude();
Log.v(ConstantLib.LOG, "LOCATION CHANGED" + " latitude : "
+ Data.CURENT_LATITUDE);
longitude = location.getLongitude();
Data.CURENT_LONGITUDE = location.getLongitude();
Log.v(ConstantLib.LOG, "LOCATION CHANGED" + " longitude : "
+ Data.CURENT_LONGITUDE);
}
} catch (Exception e) {
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}