How to place multiple markers using lat long from JSON - android

In my app I want to show the multiple marker using latitude and longitude from JSON but when I run the application it only shows one marker, other markers are not shown. Please help - here is my code:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progressDialog; // class variable
private void showProgressDialog(String title, String message)
{
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle(title); // set title
progressDialog.setMessage(message); // set message
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog("Loading...", "Please wait for few seconds");
// dialog = new ProgressDialog(getActivity().this);
// dialog.setMessage("Loading, please wait");
// dialog.setTitle("Connecting server");
// dialog.show();
// dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// Date a = new Date();
// a.setTime(System.currentTimeMillis()-(60*60*1000));
// Log.e("onehourback",""+a);*/
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("SingleIMEs");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
// Log.e("object",""+object);
/*try {
array.add(jarray.getJSONObject(i));
Log.e("array",""+array);
} catch (JSONException e)
{
e.printStackTrace();
}*/
for(int j=0; j < 1;j++)
{
latvalue=object.getString("Latitude");
longvalue=object.getString("Longitude");
latt=Double.parseDouble(latvalue);
lng=Double.parseDouble(longvalue);
Log.e("lat",""+latt);
Log.e("lon",""+lng);
}
}
}
//}
return true;
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
/* adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getActivity().getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
*/
}
}
private void setUpMapIfNeeded(View inflatedView) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.clear();
mMap.addMarker(new MarkerOptions().position(new LatLng(latt,lng)).title("eee"));
Log.e("lat",""+latt);
Log.e("lon",""+lng);
mMap.setMyLocationEnabled(true);
if (mMap != null) {
//setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("WePOP"));
// mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)).position( new LatLng(Double.parseDouble(datas.get("Lat")), Double.parseDouble(datas.get("Long")))));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
});
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}

It looks like you're overwriting your latt and lng variables multiple times in this code:
for(int j=0; j < 1;j++)
{
latvalue=object.getString("Latitude");
longvalue=object.getString("Longitude");
latt=Double.parseDouble(latvalue);
lng=Double.parseDouble(longvalue);
Log.e("lat",""+latt);
Log.e("lon",""+lng);
}
I would suggest you create a List that holds some sort of object containing latt and lng information (something like List positions).
Then modify your code in setUpMapIfNeeded to cycle through all your LatLngs. Something like this:
for(LatLng latlng: positions) {
mMap.addMarker(new MarkerOptions().position(new LatLng(latlng.getLat(),latlng.getLng())).title("eee"));
Log.e("Added marker at lat: " + latlng.getLat() + ", lng: " + latlng.getLng());
}
Notice: It's been quite some time since i've used android and google maps, so the code i've written here probably isn't perfect - but the idea should be good :-)

Related

MapsActivity marker won't displayed for second time

I have a MapsActivity in my app which starts by clicking on a button in MainActivity and when activity started I will get markers coordinates by JSON and show them in MapsActivity, but this will happen only in first time and once I press back and go to MainActivity and press the button again MapsActivity starts but markers won't be displayed in that . I tried to finish or destroy activity but that didn't help.
any help will be much appreciated
this is my MapsActivity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
check_activity = 1;
backgroundTask2 = new BackgroundTask2(textView);
backgroundTask2.execute();
ma_fin = this;
MainActivity.maps_adv = 1;
if (flag == 1) {
map_update();
maps_adv = 0;
}
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
checkLocationPermission();
setUpMapIfNeeded();
map_update();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
mGoogleApiClient.disconnect();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0,
0)).title("Marker"));
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("Your Location");
mMap.addMarker(options);
float zoomLevel = 13.0f; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " +
connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
final ArrayList myList;
if (checker==0) {
myList = (ArrayList<Object>) getIntent().getSerializableExtra("maps");
}
else
{
checker = 0;
myList = maps;
}
mMap = googleMap;
mMap.clear();
for (int i = 0; i < myList.size(); i++) {
LatLng sydney = new LatLng(((Double) (((ArrayList) myList.get(i))).get(2)).doubleValue(), ((Double) (((ArrayList) myList.get(i))).get(3)).doubleValue());
mMap.addMarker(new MarkerOptions().position(sydney).title((String) (((ArrayList) myList.get(i))).get(1)).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon)));
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String position = "0";
String title = marker.getTitle();
for (int i = 0; i < myList.size(); i++) {
if (title.equals(((ArrayList) myList.get(i)).get(1).toString())) {
position = ((ArrayList) myList.get(i)).get(0).toString();
titlename = ((ArrayList) myList.get(i)).get(1).toString();
address = ((ArrayList) myList.get(i)).get(4).toString();
}
}
foo = Integer.valueOf(position);
a = ((ArrayList) myList.get(foo)).get(0).toString();
backgroundTask = new BackgroundTask(textView);
backgroundTask.execute();
map_check = 1;
MainActivity.maps_adv = 0;
return true;
}
});
} catch (RuntimeException e) {
e.printStackTrace();
}
}
private class BackgroundTask extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(MainActivity.url);
try {
jsonobj = new JSONObject();
jsonobj.put("hotel_id_post", foo);
Log.i("EEE", a);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("req", jsonobj.toString()));
nameValuePairs.add(new BasicNameValuePair("func", "2"));
nameValuePairs.add(new BasicNameValuePair("adv", MainActivity.features.toString()));
nameValuePairs.add(new BasicNameValuePair("adv_cont", ("" + features_count).toString()));
nameValuePairs.add(new BasicNameValuePair("date", MainActivity.current_date));
nameValuePairs.add(new BasicNameValuePair("during", "1"));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServerhotel = str.getStringFromInputStream(inputStream);
Log.e("responseqqqqqqq", "response -----" + responseServerhotel);
HotelList.jsonroom = new JSONObject(responseServerhotel);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
if (responseServerhotel.equals("{\"types\":null}"))
{
MainActivity.nothing = "no room to show";
Intent intent = new Intent(MapsActivity.this,Nothing.class);
startActivity(intent);
}
else
{
Intent intent = new Intent(MapsActivity.this, RoomList.class);
startActivity(intent);
}
}
}
private class BackgroundTask1 extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask1(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(MainActivity.url);
try {
//mMap.clear();
jsonadv = new JSONObject();
jsonadv_cont = new JSONObject();
jsonobj = new JSONObject();
jsonads = new JSONObject();
MainActivity.features = "";
features_count = 0;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("func", "11"));
nameValuePairs.add(new BasicNameValuePair("adv",
MainActivity.features.toString()));
nameValuePairs.add(new BasicNameValuePair("adv_cont", ("" +
features_count).toString()));
nameValuePairs.add(new BasicNameValuePair("date",
MainActivity.current_date));
nameValuePairs.add(new BasicNameValuePair("during", num));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
// Use UrlEncodedFormEntity to send in proper format which we need
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServer = str.getStringFromInputStream(inputStream);
Log.e("response", "response -----" + responseServer);
jsonmap = new JSONObject(responseServer);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
backgroundTask2 = new BackgroundTask2(textView);
backgroundTask2.execute();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (backgroundTask != null) {
backgroundTask.cancel(true);
}
if (backgroundTask1 != null) {
backgroundTask1.cancel(true);
}
if (backgroundTask2 != null) {
backgroundTask2.cancel(true);
}
finish();
}
private class BackgroundTask2 extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask2(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MainActivity.url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray mapsarr = jsonmap.getJSONArray("maps");
for (int i = 0; i < mapsarr.length(); i++) {
ArrayList<Object> mapping = new ArrayList<>();
JSONObject c = mapsarr.getJSONObject(i);
String id = c.getString("hotel_id");
String name = c.getString("hotel_name");
Double x = c.getDouble("hotel_x");
Double y = c.getDouble("hotel_y");
String address = c.getString("hotel_address");
mapping.add(0, id);
mapping.add(1, name);
mapping.add(2, x);
mapping.add(3, y);
mapping.add(4, address);
maps.add(i, mapping);
}
Log.i("MAPTEST", mapsarr.toString());
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
final TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
onMapReady(mMap);
checker = 1;
}
}
public static class InputStreamToStringExample {
public static void main(String[] args) throws IOException {
// intilize an InputStream
InputStream is =
new ByteArrayInputStream("file content..blah blah".getBytes());
String result = getStringFromInputStream(is);
System.out.println(result);
System.out.println("Done");
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
}
public void map_update() {
maps.clear();
backgroundTask1 = new BackgroundTask1(textView);
backgroundTask1.execute();
}
public static void refresh()
{
flag = 0;
MapsActivity ma = new MapsActivity();
ma.map_update();
}

Clear all markers when refresh google maps - Android

I want to remove all the markers and remove setInfoWindowAdapter when i refresh the maps. But the app will crash if i refresh it.
Here's my code
private final BroadcastReceiver mNetworkReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
//Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
new GetInfo().execute(Config.INFO_URL);
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
//Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
new GetInfo().execute(Config.INFO_URL);
}
}
}
};
class GetInfo extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MapsActivity.this);
dialog.setMessage("Mohon tunggu");
dialog.setTitle("Mendapatkan data...");
dialog.show();
dialog.setCancelable(true);
}
#Override
protected Boolean doInBackground(String... urls) {
array.clear();
mMarkersHashMap.clear();
mMyMarkersArray.clear();
markerPoints.clear();
targets.clear();
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray konten = jsono.getJSONArray("konten");
mMarkersHashMap = new HashMap<Marker, MyMarker>();
for (int i = 0; i < konten.length(); i++) {
HashMap<String,String> newMap=new HashMap<String,String>();
JSONObject object = konten.getJSONObject(i);
newMap.put("nama", object.getString("nama"));
newMap.put("deskripsi",object.getString("deskripsi"));
newMap.put("foto",object.getString("foto"));
newMap.put("marker", object.getString("marker"));
newMap.put("lat",object.getString("lat"));
newMap.put("lng",object.getString("lng"));
array.add(newMap);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(final Boolean result) {
dialog.cancel();
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!result) {
//Toast.makeText(getApplicationContext(), "Tidak dapat mengambil data dari server, silahkan cek koneksi internet anda", Toast.LENGTH_LONG).show();
showInfo();
}
else {
for (int i = 0; i < array.size(); i++) {
HashMap<String, String> newMap = new HashMap<String, String>();
newMap = array.get(i);
mMyMarkersArray.add(new MyMarker(newMap.get("nama"), newMap.get("deskripsi"), newMap.get("foto"), newMap.get("marker"), Double.parseDouble(newMap.get("lat")), Double.parseDouble(newMap.get("lng"))));
}
plotMarkers(mMyMarkersArray);
}
}
});
}
}
Here's the plotMarkers
public void plotMarkers(ArrayList<MyMarker> markers) {
if(markers.size() > 0) {
for (MyMarker myMarker : markers)
{
dest = new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude());
markerOption = new MarkerOptions().position(dest);
location_marker = mMap.addMarker(markerOption);
Target target = new PicassoMarker(location_marker);
targets.add(target);
ImageView image = new ImageView(this);
image.setImageResource(R.mipmap.marker);
int width = image.getDrawable().getIntrinsicWidth();
int height = image.getDrawable().getIntrinsicHeight();
Picasso.with(MapsActivity.this).load(myMarker.getmIcon()).resize(width, height).onlyScaleDown().into(target);
mMarkersHashMap.put(location_marker, myMarker);
i = getIntent();
if(i.getBooleanExtra("maps", true)) {
location_marker.setTitle(i.getStringExtra("nama"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dest, 16));
}
else {
mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
}
}
}
}
Here's the refresh menu on action bar
case R.id.action_refresh:
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
return true;
What's wrong with my code?
I'm assuming you still have similar implementation from before.. In order to remove all Markers. You could just call Marker.remove() on the marker instance. In your case, you put the marker instance in a HashMap. So what you could do is something like this:
private void removeAllMarkers() {
// hmap here is the HashMap you have.
for (HashMap.Entry<Marker, MyMarker> entry : hmap.entrySet()) {
entry.getKey().remove();
}
}
This iterates over the HashMap where you add the Markers in plotMarkers function and remove them all. Just call this function in the code where you refresh the Map.
Regarding your concern with the setInfoWindowAdapter, if you're pertaining to the InfoWindow of the Marker, I think so long as you are able to remove the Marker itself, you'll no longer have a problem with it.
Found this answer that shows how to remove a marker. I think this post on iterating over hashmaps would also be helpful for you.

How to move marker in google map for a vechicle tracking application

In my application I want to track the vehicles,am getting multiple latitude and longitude from JSON I plotted the latlong in the google map,when the latlong changes in JSON the marker has to move.but here it moves by creating an new marker the previous marker is still exist.how can I remove the marker in the previous location
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
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("IME");
final MarkerOptions options = new MarkerOptions()
.position(position);
//mMap.addMarker(options);
//mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
//options.title(ime1);
builder.include(position);
}
LatLng latLng = new LatLng(arg0.getLatitude(), arg0
.getLongitude());
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// mMap.setOnMapClickListener(null);
mMap.setOnMarkerClickListener(null);
mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
}
});
}
}
}
/* 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);
// pubname = json.getString("PubName");
latitude = json.getDouble("Latitude");
longitude = json.getDouble("Longitude");
ime = json.getString("IME");
// map.put("PubName", json.getString("PubName"));
//map.put("PubID", json.getString("PubID"));
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("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 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
}
}
if (marker != null) {
marker.remove();
}
Do you actually have a function to remove the marker here? If not, you have to remove the marker from the map and set it to null in order to remove it.
marker.setMap(null);
Source: marker API documentation

Can not get the current speed from location.getSpeed()

I am trying to get the latitude, longitude, current address, current speed and send to the server for every 5 min. I can get the lat, long, address. But I can not get the current speed from location.getSpeed().
Herewith I have attached my entire code. Please review and give me your valuable suggestions to resolve my problem
public class MainActivity extends FragmentActivity implements LocationListener {
private GoogleMap googleMap;
private LocationManager locationManager;
private String provider;
Location location;
UserSessionManager session;
private Handler customHandler = new Handler();
String currentdatetime_tosend, latitude_tosend, logitude_tosend,
address_tosend, speed_tosend, username_tosend, startTime_tosend;
Boolean isInternetAvail = false;
ConnectionCheck conChk;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle(GlobalConstants.loginDriverName);
System.out.println("GlobalConstants.loginDriverName==> "+GlobalConstants.loginDriverName);
session = new UserSessionManager(getApplicationContext());
try {
initilizeMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(false);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);
conChk = new ConnectionCheck(getApplicationContext());
GetLocaion();
} catch (Exception e) {
e.printStackTrace();
}
}
private void AddMarker(double latitude, double longitude, String driverName) {
googleMap.clear();
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title(driverName);
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.driver_car));
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Double lat = (Double) (location.getLatitude());
Double lng = (Double) (location.getLongitude());
speed_tosend = Float.toString(location.getSpeed());
Toast.makeText(getApplicationContext(),
"Speed==> " + speed_tosend.toString() + "",
Toast.LENGTH_SHORT).show();
latitude_tosend = lat.toString();
logitude_tosend = lng.toString();
getAddress();
AddMarker(lat, lng, GlobalConstants.loginDriverName);
if (conChk.isConnectingToInternet())
new SendDetailsInBackground().execute();
} else
Toast.makeText(getApplicationContext(),
"Getting Location.. Please Wait..", Toast.LENGTH_SHORT)
.show();
}
private void BackgroundProcess() {
customHandler.postDelayed(updateTimerThread, 0);
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
GetLocaion();
customHandler.postDelayed(this, 30000);
}
};
private void StartTheProcess() {
BackgroundProcess();
}
private void StopGetingLocation() {
customHandler.removeCallbacks(updateTimerThread);
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
private void GetLocaion() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
Toast.makeText(getApplicationContext(), "Location Activated",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"No location found..!!", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "GPS IS Ennabled..!!",
Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.startGettingLocation) {
startTime_tosend = getDateTime();
StartTheProcess();
return true;
}
if (id == R.id.stopGetingLocation) {
StopGetingLocation();
return true;
}
if (id == R.id.logout) {
exit();
}
return super.onOptionsItemSelected(item);
}
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
class SendDetailsInBackground extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("currentdatetime",
startTime_tosend));
params.add(new BasicNameValuePair("driver_mobile",
GlobalConstants.loginDriverNumber));
params.add(new BasicNameValuePair("username",
GlobalConstants.loginDriverName));
params.add(new BasicNameValuePair("lattitude", latitude_tosend));
params.add(new BasicNameValuePair("longtitude", logitude_tosend));
params.add(new BasicNameValuePair("currentaddress", address_tosend));
params.add(new BasicNameValuePair("currentspeed", speed_tosend));
String json = sendToServer(GlobalConstants.url_pass_tripdetail,
params);
Log.d("Create Response", json.toString());
return null;
}
protected void onPostExecute(String file_url) {
}
}
public String sendToServer(String url, List<NameValuePair> params) {
String TAG = "";
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String response = EntityUtils.toString(httpEntity);
System.out.println("Response==> " + response);
TAG = response;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return TAG;
}
private void getAddress() {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(
Double.parseDouble(latitude_tosend),
Double.parseDouble(logitude_tosend), 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i) + ",");
Toast.makeText(getApplicationContext(), "Address Found..!!!",
Toast.LENGTH_LONG).show();
address_tosend = sb.toString();
} else {
Toast.makeText(getApplicationContext(), "Address is empty!",
Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "No Address returned!",
Toast.LENGTH_SHORT).show();
}
}
public void exit() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Logout")
.setMessage("Are you sure you want to Logout?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
session.logoutUser();
StopGetingLocation();
finish();
}
}).setNegativeButton("No", null).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}

Google Maps API to get JSON data and set it as info window

I have a somehow long question. I am now learning about Google Maps API and I am required to make the app get some JSON data from a website, then set some of this data in an info window as the title or whatever.
The important part is that I have to do this with an interface class, whereas the AsyncTask that downloads this data must also be in another class. So I am currently very confused how to make this communication possible, and to have as little code as possible in the AsyncTask class. I also don't understand very well this interface thing.
Please someone help.
So here is the main activity:
package com.example.gmapsexample;
public class MainActivity extends Activity {
private GoogleMap mMap;
Marker marker = null;
HttpClient klient;
String data;
String s;
Double latt, lngg;
GoogleMapOptions options;
String adres = "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=en&username=sartheris";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
options = new GoogleMapOptions();
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
options.mapType(GoogleMap.MAP_TYPE_SATELLITE).compassEnabled(true).rotateGesturesEnabled(true).tiltGesturesEnabled(true).zoomControlsEnabled(true);
klient = new DefaultHttpClient();
GetJson gg = new GetJson();
gg.execute();
/** On Info Window Click */
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
marker.setTitle(s);
Toast.makeText(getApplicationContext(), "Info Window Clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
Here is the GetJson class
package com.example.gmapsexample;
public class GetJson extends AsyncTask<String, Void, String> {
HttpClient klient;
String adres = "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=en&username=sartheris";
String s;
Double latt, lngg;
private GoogleMap mMap;
Marker marker;
GoogleMapOptions options;
#Override
protected String doInBackground(String... params) {
klient = new DefaultHttpClient();
options = new GoogleMapOptions();
StringBuilder url = new StringBuilder(adres);
HttpGet hg = new HttpGet(url.toString());
HttpResponse hr = null;
try {
hr = klient.execute(hg);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
int status = hr.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity he = hr.getEntity();
String data = null;
try {
data = EntityUtils.toString(he);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jsonGet = null;
try {
jsonGet = new JSONObject(data);
} catch (JSONException e1) {
e1.printStackTrace();
}
if (jsonGet.has("geonames")) {
try {
JSONObject arrGet = jsonGet.getJSONArray("geonames").getJSONObject(0);
s = arrGet.getString("toponymName");
latt = arrGet.getDouble("lat");
lngg = arrGet.getDouble("lng");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
marker = new Marker(this);
marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latt, lngg))
.title("HELLO WORLD").snippet("BLQ")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.draggable(true));
}
}
And now I need an interface class that would help with the data passing...
In your main class create an interface:
public interface ParsingCallback{
void onFinishedParsing(MarkerOptions marker);
}
Pass it a copy to your AsyncTask
GetJson gg = new GetJson(new ParsingCallback(){
void onFinishedParsing(MarkerOptions marker) {
mMap.addMarker(marker);
}
);
gg.execute();
In your AsyncTask create the constructor
private ParsingCallback _callback;
public GetJson (ParsingCallback callback){
_callback = callback;
}
And then in your onPostExecute:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
_callback.onFinishedParsing(new MarkerOptions()
.position(new LatLng(latt, lngg))
.title("HELLO WORLD")
.snippet("BLQ")
);
}
Hope that helps :)

Categories

Resources