Google Maps compatibility with different Android versions/devices - android

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

Related

Adding 1000+ markers from json to google map makes the android app very slow and struck

In my application am loading 1000+ location form JSON to google map using markers but when i run my application it shows all the markers perfectly but when i tried to zoom or drag the map it get two slow and get struck any solution to solve this ??
The webservice response looks like this given below
{
"DateTime": "8/4/2015 7:27:32 PM",
"IME": "865733024065062",
"IsActivated": null,
"Latitude": "13.0115833333333",
"Longitude": "80.2151833333333",
"RegistrationNo": "AMvTS_01"
},
{
"DateTime": "8/5/2015 12:28:17 PM",
"IME": "887766554433711",
"IsActivated": null,
"Latitude": "16.060578",
"Longitude": "73.489748",
"RegistrationNo": "TN_TEST_803"
},
{
"DateTime": "8/5/2015 12:28:17 PM",
"IME": "887766554433567",
"IsActivated": null,
"Latitude": "9.722656",
"Longitude": "76.287158",
"RegistrationNo": "TN_TEST_659"
},
{
"DateTime": "8/5/2015 12:28:17 PM",
"IME": "887766554433740",
"IsActivated": null,
"Latitude": "14.895189",
"Longitude": "74.103996",
"RegistrationNo": "TN_TEST_832"
},
{
"DateTime": "8/5/2015 12:28:17 PM",
"IME": "887766554433017",
"IsActivated": null,
"Latitude": "12.688946",
"Longitude": "80.217097",
"RegistrationNo": "TN_TEST_048"
},
{
"DateTime": "8/5/2015 12:28:17 PM",
"IME": "887766554433769",
"IsActivated": null,
"Latitude": "8.887102",
"Longitude": "76.591018",
"RegistrationNo": "TN_TEST_861"
}
and this is my mapfragment code given below
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.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
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 com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import android.app.ActionBar;
import android.app.AlarmManager;
import android.app.Fragment;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MapFragment extends Fragment implements LocationListener, OnMapClickListener, OnMapLongClickListener, OnMarkerDragListener{
private static final String LOG_TAG = "ExampleApp";
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
private static final String SERVICE_URL = "http://203.109.107.139/primevts/vtsservice.svc/data";
JSONObject json = null;
JSONArray jsonarray = null;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist1;
private Timer timer;
static String LONG = "Long";
static String LAT = "Lat";
ArrayList<String> ct;
public double latt = 0;
public double lng = 0;
public ArrayList<Integer> dLat;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private Handler handler;
private Marker marker;
private HashMap<String, Marker> mMarkers = new HashMap<>();
int value=1;
// LatLngBounds values ;
double latitude, longitude;
String ime,reg;
boolean markerClicked;
// LatLng val;
static HashMap<String, String> datas;
static HashMap<String, String> map;
String[] latlngvalues;
// LocationManager locman;
Context context;
View rootView;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView)rootView.findViewById(R.id.mapView);
mMapView.onCreate(mBundle);
MapsInitializer.initialize(getActivity());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
/* handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
Log.e("Data in Log", "");
}
}, 1000);
*/
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//mMap.clear();
// Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
});
}
};
timer.schedule(doAsynchronousTask, 20000, 20000);
/*LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);*/
return rootView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Marker")
.draggable(true)
.snippet("Hello")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mMap.setOnMarkerDragListener(this);
markerClicked = false;
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
//mMap.clear();
// setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
// mMap.clear();
if(marker!=null){
marker.remove();
}
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
String ime1 = arraylist1.get(i).get("RegistrationNo");
final MarkerOptions options = new MarkerOptions()
.position(position);
//mMap.addMarker(options);
mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).anchor(0.0f, 1.0f).title(ime1));
// marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
//options.title(ime1);
builder.include(position);
} if(value==1){
LatLng latLng = new LatLng(arg0.getLatitude(), arg0
.getLongitude());
//mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
//mMap.moveCamera(CameraUpdateFactory.newLatLng(newLatLnglatLng));
// mMap.setOnMapClickListener(null);
mMap.setOnMarkerClickListener(null);
//mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to Mountain View
.zoom(10) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
value++;
}
}
});
}
}
}
/* protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
new DownloadJSON().execute();
} */
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String result="";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl(SERVICE_URL);
try {
arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
latitude = json.getDouble("Latitude");
longitude = json.getDouble("Longitude");
ime = json.getString("IME");
reg=json.getString("RegistrationNo");
map.put("Latitude", json.getString("Latitude"));
Log.e("CHECKLAT",""+json.getString("Latitude") );
map.put("Longitude", json.getString("Longitude"));
Log.e("CHECKLONG",""+json.getString("Longitude") );
map.put("RegistrationNo", json.getString("RegistrationNo"));
map.put("IME", json.getString("IME"));
arraylist1.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
/* Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
Log.d("onLocationUpdated!!!","");
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onMapClick(LatLng arg0) {
// TODO Auto-generated method stub
mMap.animateCamera(CameraUpdateFactory.newLatLng(arg0));
markerClicked = false;
}
#Override
public void onMarkerDrag(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMarkerDragEnd(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMarkerDragStart(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMapLongClick(LatLng arg0) {
// TODO Auto-generated method stub
}
}
First you save in List of MarkerOptions your JSON info, when you get it
final List<MarkerOptions> markerOptionsList = new ArrayList<>(arraylist1.size());
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(
Double.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get("Longitude")));
String ime1 = arraylist1.get(i).get("RegistrationNo");
final MarkerOptions options = new MarkerOptions()
.position(position)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.buspng))
.anchor(0.0f, 1.0f)
.title(ime1);
markerOptionsList.add(options);
}
Then, instead of OnMyLocationChangeListener use OnCameraChangeListener
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
mMap.clear();
LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds;
for (MarkerOptions markerOptions : markerOptionsList) {
if (bounds.contains(markerOptions.getPosition())) {
mMap.addMarker(markerOptions);
}
}
}
});
You will clear map and add only visible markers

Change the icon of multiple Android Google maps markers dynamically

I'm trying to change multiple Google Maps marker icon based on urls i get from a webserver. Since I Previously only worked with web applications this is very new to me.
I have read in other topics that i have to create a new thread, but if I want to get multiple photos doesn't that become a problem? Does anyone have a suggestion for my problem?
here is my code:
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
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.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 org.json.JSONArray;
import org.json.JSONException;
public class Mainmap extends ActionBarActivity implements View.OnClickListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LocationManager location;
private String provider;
private double lat;
private double lng;
private double pic_lat;
private double pic_lng;
private String image;
public static String LOG_TAG = "cn-quotes";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainmap);
location = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria c = new Criteria();
provider = location.getBestProvider(c, false);
setUpMapIfNeeded();
View newPhoto = findViewById(R.id.button_local_position);
newPhoto.setOnClickListener(this);
View popPhoto =findViewById(R.id.button_popphoto);
popPhoto.setOnClickListener(this);
}
#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_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
// startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
location.requestLocationUpdates(provider, 300000, 1000, onLocationChange);
setUpMapIfNeeded();
}
LocationListener onLocationChange=new LocationListener() {
public void onLocationChanged(Location location) {
lng = location.getLongitude();
lat = location.getLatitude();
}
public void onProviderDisabled(String provider) {
// required for interface, not used
}
public void onProviderEnabled(String provider) {
// required for interface, not used
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
// required for interface, not used
}
};
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.setMapType(mMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
if (lat != 0) {
LatLng latLng = new LatLng(lat, lng);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
Log.d("DEBUG", "succes");
} else {
Log.d("DEBUG", "fail");
}
}
private void downloadJSON(String downloadurl) {
new JSONDownloader(this, downloadurl).execute();
}
public void updatephotos(JSONArray result) {
Log.d("Debug arraylength", "" + result.length());
for (int i = 0; i < result.length(); i++) {
try {
pic_lat = result.getJSONObject(i).getDouble("latitudes");
pic_lng = result.getJSONObject(i).getDouble("longtitudes");
image = result.getJSONObject(i).getString("images");
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)));
} catch (JSONException e) {
Log.e(Mainmap.LOG_TAG, "JSONException", e);
}
}
}
#Override
public void onClick(View v) {
String downloadurl = "";
switch (v.getId())
{
case R.id.button_popphoto:
downloadurl = "index.php";
break;
case R.id.button_local_position:
downloadurl = "index.php?yourLat=" + lat + "&yourLng=" + lng;
break;
}
downloadJSON(downloadurl);
}
}
And the JSONdownloader:
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JSONDownloader extends AsyncTask<Void, Void, JSONArray> {
private Mainmap mm;
private String downloadurl = "http://student.cmi.hro.nl/0876538/Jaar1/Kwartaal3/IMP03/huiswerk/week04/opdracht/libs/php/";
public JSONDownloader(Mainmap mm, String url) {
this.mm = mm;
this.downloadurl = downloadurl + url;
}
public JSONArray getPhotos() {
JSONArray result = new JSONArray();
HttpURLConnection con = null;
Log.d(Mainmap.LOG_TAG, "Getting photos");
try {
Log.d(Mainmap.LOG_TAG, downloadurl);
URL url = new URL(downloadurl);
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("GET");
con.setDoInput(true);
con.connect();
BufferedReader reader = new BufferedReader(
new InputStreamReader(con.getInputStream(), "UTF-8"));
String payload = reader.readLine();
reader.close();
result = new JSONArray(payload);
} catch (IOException e) {
Log.e(Mainmap.LOG_TAG, "IOException", e);
} catch (JSONException e) {
Log.e(Mainmap.LOG_TAG, "JSONException", e);
} catch (Exception e) {
Log.d(Mainmap.LOG_TAG, "Something went wrong....", e);
} finally {
if (con != null) {
con.disconnect();
}
}
Log.d(Mainmap.LOG_TAG, "-> returned: " + result);
return result;
}
#Override
protected JSONArray doInBackground(Void... params) {
JSONArray photos = getPhotos();
return photos;
}
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
mm.updatephotos(result);
}
}

Draw path to destination android maps v2

I Have some code that showing between two directions which the destination has initialized (known position). The full code like this :
package com.my.app;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.FragmentManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
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.MapFragment;
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.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.SupportMapFragment;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class CobaMap2 extends FragmentActivity {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
double src_lat = -7.81016;
double src_long = 110.46860;
double dest_lat = -7.778031;
double dest_long = 110.494180;
MarkerOptions markerOptions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout2);
myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
myMap.setMyLocationEnabled(true);
// Set Current Location
moveToMyLocation();}
private void moveToMyLocation()
{
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(),
location.getLongitude()), 13));
}
// choose map layout
RadioGroup rgViews = (RadioGroup) findViewById(R.id.rg_views);
rgViews.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.rb_normal){
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}else if(checkedId == R.id.rb_satellite){
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}else if(checkedId == R.id.rb_terrain){
myMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}
}
});
LatLng srcLatLng = new LatLng(src_lat, src_long);
LatLng destLatLng = new LatLng(dest_lat, dest_long);
myMap.addMarker(new MarkerOptions()
.position(srcLatLng).title("Source place"));
myMap.animateCamera(CameraUpdateFactory.newLatLng(srcLatLng));
myMap.addMarker(new MarkerOptions()
.position(destLatLng).title("Destination place"));
// Enabling MyLocation in Google Map
myMap.setMyLocationEnabled(true);
myMap.getUiSettings().setZoomControlsEnabled(true);
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setMyLocationButtonEnabled(true);
myMap.getUiSettings().setAllGesturesEnabled(true);
myMap.setTrafficEnabled(true);
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(srcLatLng,12));
markerOptions = new MarkerOptions();
// Polyline line = myMap.addPolyline(new PolylineOptions().add(srcLatLng, destLatLng).width(5).color(Color.RED));
connectAsyncTask _connectAsyncTask = new connectAsyncTask();
_connectAsyncTask.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cobamap, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_legalnotices:
String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
getApplicationContext());
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(CobaMap2.this);
LicenseDialog.setTitle("Legal Notices");
LicenseDialog.setMessage(LicenseInfo);
LicenseDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
private class connectAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(CobaMap2.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
fetchData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(doc!=null){
NodeList _nodelist = doc.getElementsByTagName("status");
Node node1 = _nodelist.item(0);
String _status1 = node1.getChildNodes().item(0).getNodeValue();
if(_status1.equalsIgnoreCase("OK")){
NodeList _nodelist_path = doc.getElementsByTagName("overview_polyline");
Node node_path = _nodelist_path.item(0);
Element _status_path = (Element)node_path;
NodeList _nodelist_destination_path = _status_path.getElementsByTagName("points");
Node _nodelist_dest = _nodelist_destination_path.item(0);
String _path = _nodelist_dest.getChildNodes().item(0).getNodeValue();
List<LatLng> directionPoint = decodePoly(_path);
PolylineOptions rectLine = new PolylineOptions().width(10).color(Color.BLUE);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding route on the map
myMap.addPolyline(rectLine);
markerOptions.position(new LatLng(dest_lat, dest_long));
markerOptions.draggable(true);
myMap.addMarker(markerOptions);
}else{
showAlert("Unable to find the route");
}
}else{
showAlert("Unable to find the route");
}
progressDialog.dismiss();
}
}
Document doc = null;
private void fetchData()
{
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps/api/directions/xml?origin=");
urlString.append(src_lat);
urlString.append(",");
urlString.append(src_long);
urlString.append("&destination=");//to
urlString.append(dest_lat);
urlString.append(",");
urlString.append(dest_long);
urlString.append("&sensor=true&mode=driving");
Log.d("url","::"+urlString.toString());
HttpURLConnection urlConnection= null;
URL url = null;
try
{
url = new URL(urlString.toString());
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = (Document) db.parse(urlConnection.getInputStream());//Util.XMLfromString(response);
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (ParserConfigurationException e){
e.printStackTrace();
}
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void showAlert(String message){
AlertDialog.Builder alert = new AlertDialog.Builder(CobaMap2.this);
alert.setTitle("Error");
alert.setCancelable(false);
alert.setMessage(message);
alert.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
}
private ArrayList<LatLng> decodePoly(String encoded) {
ArrayList<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
poly.add(position);
}
return poly;
}
}
The code worked perfectly, You can see between two location (source and destination) are known location. then i need change the first location (source location) with my current Location, and current location detected by this code :
// Set Current Location
moveToMyLocation();}
private void moveToMyLocation()
{
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(),
location.getLongitude()), 13));
}
And code to initialized the location is :
LatLng srcLatLng = new LatLng(src_lat, src_long);
LatLng destLatLng = new LatLng(dest_lat, dest_long);
The problem is, how to passing data from my current location to set the data for the source location and show path between location. (Source : My current Location, Destination : Known Location). What the method must i use ?. I mean the app show from my current location to destination location with modify that code ?
Check this question
How to draw interactive Polyline on route google maps v2 android
in this you will get the code to draw a proper route from one place to another using polyLine, also includes current and destination location !
Edit :
Use
src_lat=location.getLatitude()
src_long=location.getLongitude()
inside
if (location != null)
{
src_lat=location.getLatitude()
src_long=location.getLongitude()
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(),
location.getLongitude()), 13));
}
Edit:
try by
Changing :
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
to
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));

Location not updating using google maps apiv2

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.

Location not updating

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
}
}
}

Categories

Resources