How to add balloons in OpenStreetMap? - java

How do I add balloons like those on Google Maps (such as the one shown here) into OpenStreetMap? This is my OpenStreetMap code below:
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
public class MainActivity extends Activity {
MyItemizedOverlay myItemizedOverlay = null;
private MapController myMapController;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
myMapController = mapView.getController();
myMapController.setZoom(16);
Drawable marker=getResources().getDrawable(android.R.drawable.star_big_on);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
ResourceProxy resourceProxy = new
DefaultResourceProxyImpl(getApplicationContext());
myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
mapView.getOverlays().add(myItemizedOverlay);
GeoPoint myPoint1 = new GeoPoint(24.893379000000000000, 67.028060900000010000);
myItemizedOverlay.addItem(myPoint1, "myPoint1", "myPoint1");
GeoPoint myPoint2 = new GeoPoint(24.824796300000000000, 67.031565699999990000);
myItemizedOverlay.addItem(myPoint2, "myPoint2", "myPoint2");
}
}
import java.util.ArrayList;
import org.osmdroid.ResourceProxy;
import org.osmdroid.api.IMapView;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.overlay.ItemizedOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> overlayItemList = new ArrayList<OverlayItem>();
public MyItemizedOverlay(Drawable pDefaultMarker,
ResourceProxy pResourceProxy) {
super(pDefaultMarker, pResourceProxy);
// TODO Auto-generated constructor stub
}
public void addItem(GeoPoint p, String title, String snippet){
OverlayItem newItem = new OverlayItem(title, snippet, p);
overlayItemList.add(newItem);
populate();
}
#Override
public boolean onSnapToItem(int arg0, int arg1, Point arg2, IMapView arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
protected OverlayItem createItem(int arg0) {
// TODO Auto-generated method stub
return overlayItemList.get(arg0);
}
#Override
public int size() {
// TODO Auto-generated method stub
return overlayItemList.size();
}
}

I was with the same question and now I found a way:
Download the osmbonuspack here: https://code.google.com/p/osmbonuspack/
Follow this code:
ArrayList<ExtendedOverlayItem> overlayItemArray = new ArrayList<ExtendedOverlayItem>();
ExtendedOverlayItem item = new ExtendedOverlayItem("Title, "Description, new GeoPoint(Double latitude, Double longitude), this);
//creates a layer with ballons
ItemizedOverlayWithBubble<ExtendedOverlayItem> poiMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, overlayItemArray, mapView, new CustomMapInfoWindow(mapView));
// add the layer
mapView.getOverlays().add(poiMarkers);
Create a class called CustomMapInfoWindow:
import org.osmdroid.bonuspack.overlays.DefaultInfoWindow;
import org.osmdroid.bonuspack.overlays.ExtendedOverlayItem;
import org.osmdroid.views.MapView;
public class CustomMapInfoWindow extends DefaultInfoWindow {
public CustomMapInfoWindow(MapView mapView) {
super(R.layout.bonuspack_bubble, mapView);
}
#Override
public void onOpen(ExtendedOverlayItem item) {
super.onOpen(item);
}
}
Go to OSMBONUSPACKDEMO REPOSITORY and get bonuspack_bubble.xml and the drawables into drawable-mdpi folder.

You should take a look at the osmbonuspack library, which is an add-on for osmdroid. It includes an overlay that will display popup balloons:
https://code.google.com/p/osmbonuspack/

Related

Images is not shown in my Full screen Activity from my json response..? while swiping also

How to swipe my full screen images from gridview...and that images should Loading from JSON response...?
i'm new to android...please help me friends...
But i want to use only One url in my program(JSON URL)...from that i need
Gridview--->FullScreenImage(zooming and swiping)
This is my gridView Activity...
package com.example.admin.loadingimagefromwebgridandswipe;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.widget.GridView;
import android.widget.ListView;
import com.example.admin.adapter.GridViewImageAdapter;
import com.example.admin.helper.AppConstant;
import com.example.admin.helper.JSONfunctions;
import com.example.admin.helper.Utils;
import com.example.admin.ndimageslider.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class GridViewActivity extends Activity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
// ArrayList<HashMap<String, String>> imagePaths;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view);
gridView = (GridView) findViewById(R.id.grid_view);
utils = new Utils(this);
// Initilizing Grid View
InitilizeGridLayout();
new DownloadJSON().execute();
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() -
((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(GridViewActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
imagePaths = new ArrayList<>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("actors");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
imagePaths.add( jsonobject.getString("name"));
imagePaths.add(jsonobject.getString("country"));
imagePaths.add( jsonobject.getString("spouse"));
imagePaths.add(jsonobject.getString("image"));
// Set the JSON Objects into the array
// imagePaths.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
gridView = (GridView) findViewById(R.id.grid_view);
// Pass the results into ListViewAdapter.java
adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,columnWidth);
// Set the adapter to the ListView
gridView.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
this is my Gridview Adapter...
package com.example.admin.adapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.admin.loadingimagefromwebgridandswipe.FullScreenViewActivity;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class GridViewImageAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> filePaths = new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this.activity = activity;
this.filePaths = filePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this.filePaths.size();
}
#Override
public Object getItem(int position) {
return this.filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(activity);
} else {
imageView = (ImageView) convertView;
}
String designationUrl = filePaths.get(position);
// Log.d("designationUrl",""+designationUrl);
// URL url = null;
// try {
// url = new URL(designationUrl);
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// Bitmap bmp = null;
// try {
// bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
// } catch (IOException e) {
// e.printStackTrace();
// }
Picasso.with(activity)
.load(designationUrl)
.resize(imageWidth, imageWidth).into(imageView);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
//Toast.makeText(GridViewImageAdapter.this,"url: "+designationUrl,Toast.LENGTH_LONG).show();
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
// Toast.makeText(GridViewImageAdapter.this,"url: "+,Toast.LENGTH_LONG).show();
Intent i = new Intent(activity, FullScreenViewActivity.class);
i.putExtra("position", _postion);
activity.startActivity(i);
}
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
Fullscreen imageViewActivity....
package com.example.admin.loadingimagefromwebgridandswipe;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.widget.ImageView;
import com.example.admin.Application;
import com.example.admin.adapter.FullScreenImageAdapter;
import com.example.admin.helper.JSONfunctions;
import com.example.admin.helper.Utils;
import com.example.admin.ndimageslider.R;
public class FullScreenViewActivity extends Activity{
private Utils utils;
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
private ImageView flag;
private ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
viewPager = (ViewPager) findViewById(R.id.pager);
utils = new Utils(getApplicationContext());
//flag=(ImageView)findViewById(R.id.flag);
image=(ImageView)findViewById(R.id.image);
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,
Application.url());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
}
}
FullScreenImageAdapter:
package com.example.admin.adapter;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import com.example.admin.helper.TouchImageView;
import com.example.admin.ndimageslider.R;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
import java.util.ArrayList;
public class FullScreenImageAdapter extends PagerAdapter {
private Activity activity;
private ArrayList<String> imagePaths;
private LayoutInflater inflater;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this.activity = activity;
this.imagePaths = imagePaths;
}
#Override
public int getCount() {
return this.imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TouchImageView imgDisplay;
Button btnClose;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
btnClose = (Button) viewLayout.findViewById(R.id.btnClose);
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
// imgDisplay.setImageBitmap(bitmap);
Picasso.with(activity)
.load(imagePaths.get(position)).into(imgDisplay);
// close button click event
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.finish();
}
});
((ViewPager) container).addView(viewLayout,0);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
Application:
package com.example.admin;
import android.widget.Toast;
import com.example.admin.helper.FileCache;
import java.util.ArrayList;
public class Application extends android.app.Application {
public static ArrayList<String> url(){
ArrayList<String> filePaths = new ArrayList<String>();
filePaths.add("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
return filePaths;
}
}
JSONfunctions:
package com.example.admin.helper;
/**
* Created by Admin on 14-03-2016.
*/
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
you'll have to implement Viewpage in your application. Take a look at this tutorial for the application you are trying to make.
http://www.androidhive.info/2013/09/android-fullscreen-image-slider-with-swipe-and-pinch-zoom-gestures/
Follow this link. Cheers.

Can't get OnTouchListner to work

I am trying to create my first android game (in eclipse) and I cannot seem to get OnTouchListner to work, mostly because I don't know how or where to create it. I am trying to figure out where someone taps the screen. Can someone please tell me how and where to create the OnTouchListner!
Activity class:
package com.gregsapps.fallingbird;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class Game extends Activity implements OnTouchListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.){
System.out.println("TOUCH");
}
return false;
}
}
View class:
package com.gregsapps.fallingbird;
import android.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;
public class GameView extends View{
private Bird bird;
private boolean runOnce = false;
private Context context;
public GameView(Context context) {
super(context);
this.context = context;
this.setDrawingCacheEnabled(true);
// TODO add setup code
}
protected void onDraw(Canvas canvas){
update(canvas);
//TODO add drawing code
this.buildDrawingCache();
//bird.canvasImage = this.getDrawingCache(true);
canvas.drawBitmap(bird.image, bird.x, bird.y, null);
System.out.println("drawing");
invalidate();
}
private void update(Canvas canvas){
//TODO add code to update stuff
if(runOnce == false){
bird = new Bird(canvas, com.gregsapps.fallingbird.R.drawable.bird, context);
runOnce = true;
}
bird.move();
}
}
Implement it like this :-
public class Game extends Activity implements OnTouchListener{
GameView gv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gv = new GameView(this);
setContentView(gv);
gv.setOnTouchListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = event.getX();
int y = event.getY();
System.out.println("Touched view at X: " + X + " Y: " + Y );
}
return false;
}
}
You should just be able to set it on the view you create:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GameView gv = new GameView(this);
setContentView(gv);
// set the touch listener for the view
gv.setOnTouchListener(this);
}

Google Maps Android - tracking location changes

I'm developing a tracking application, for which I would also like be able to continue tracking when the application is sent to background. For this purpose I implemented a LocationListener. But clearly I'm missing something here, because during runtime none of the debug printlns appear, so the application never enters any of the inherited LocationListener functions.
michal.myapp.activities;
import java.util.ArrayList;
import java.util.Calendar;
import michal.myapp.R;
import michal.myapp.db.DataSource;
import michal.myapp.model.Track;
import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
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.PolylineOptions;
/**
* #author Michał Szydłowski
*
* Class representing user's map activity with location change detection and sensors.
*
*/
public class MapActivity extends FragmentActivity implements LocationListener,
SensorEventListener{
private GoogleMap map;
private DataSource dataSource;
private SensorManager sensorManager;
private Sensor senAccelerometer;
private ArrayList <LatLng> trackPoints;
private boolean zoomEnabled;
private Button saveTrackButton;
private static final long INTERVAL = 1000;
private static final float ACCURACY = 20;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
initialize();
check();
saveTrackButton = (Button) findViewById(R.id.saveTrackButton);
saveTrackButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getDataFromPopupWindow();
}
});
}
private void check() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) != ConnectionResult.SUCCESS) {
System.out.println("yes");
}
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
Log.i("provider", "" + provider);
if (provider.equals("")) {
System.out.println("nope");
}
setUpMapIfNeeded();
}
private void initialize()
{
dataSource = new DataSource(this);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
senAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
trackPoints = new ArrayList <LatLng> ();
zoomEnabled = true;
}
private void getDataFromPopupWindow()
{
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.save_track_window, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
final EditText editName = (EditText) popupView.findViewById (R.id.trackName);
editName.requestFocus();
Button btnDismiss = (Button)popupView.findViewById(R.id.cancel);
btnDismiss.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}
});
Button btnSave = (Button) popupView.findViewById(R.id.save);
btnSave.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String trackName = editName.getText().toString();
saveTrack(trackName);
popupWindow.dismiss();
}
});
popupWindow.setFocusable(true);
popupWindow.update();
popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
popupWindow.showAtLocation(saveTrackButton, Gravity.CENTER, 0, 0);
}
/**
* Saves the track to database when finished
*/
private void saveTrack(String trackName){
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String date = String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(day) ;
Track recordedTrack = new Track(trackName, trackPoints, date);
dataSource.open();
dataSource.insertTrack(recordedTrack);
dataSource.close();
}
/**
* Centers the view of the map around the current user's location.
* #param loc LatLng object representing user's current coordinates.
*/
private void zoom (LatLng loc)
{
if(zoomEnabled)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16));
zoomEnabled = false;
}
}
/** Initializes the GoogleMap object if it hasn't been already done.
* If successful, enables location tracking.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (map != null) {
//setUpMap();
setUpMap();
}
}
}
private void setUpMap()
{
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, INTERVAL, ACCURACY, this);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
System.out.println("setupmap");
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
dataSource.close();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
dataSource.open();
super.onResume();
setUpMapIfNeeded();
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
Sensor mySensor = event.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if(event.values[0] > 15 || event.values[1] > 15 || event.values[2] > 15)
{
// Intent intent = new Intent(this, CameraActivity.class);
// startActivity(intent);
}
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
trackPoints.add(loc);
map.addPolyline(new PolylineOptions().addAll(trackPoints).width(5).color(Color.BLUE));
zoom (loc);
System.out.println("location changed");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
System.out.println("status changed");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
System.out.println("provider enabled");
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
System.out.println("provider disabled");
}
}
I have the following permissions in my Android Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCELEROMETER"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
It is also worth mentioning, that I already try to attach an OnMyLocationChangeListener to my GoogleMap object, and it did track location changes, but not if the application was sent to background. Any ideas?

Android - GMapsV2 - Why is my activity not drawing the polyline?

I'm trying to get a red polyline to draw whenever the user moves. Here is the following code I have:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
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.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationSource, LocationListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
TextView tvLocInfo;
LocationManager myLocationManager = null;
OnLocationChangedListener myLocationListener = null;
Criteria myCriteria;
Location lastLocationloc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
myCriteria = new Criteria();
myCriteria.setAccuracy(Criteria.ACCURACY_FINE);
myLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#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(MainActivity.this);
LicenseDialog.setTitle("Legal Notices");
LicenseDialog.setMessage(LicenseInfo);
LicenseDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
//Register for location updates using a Criteria, and a callback on the specified looper thread.
myLocationManager.requestLocationUpdates(
0L, //minTime
0.0f, //minDistance
myCriteria, //criteria
this, //listener
null); //looper
//Replaces the location source of the my-location layer.
myMap.setLocationSource(this);
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
#Override
protected void onPause() {
myMap.setLocationSource(null);
myLocationManager.removeUpdates(this);
super.onPause();
}
#Override
public void activate(OnLocationChangedListener listener) {
myLocationListener = listener;
}
#Override
public void deactivate() {
myLocationListener = null;
}
/*#Override
public void onLocationChanged(Location location) {
if (myLocationListener != null) {
myLocationListener.onLocationChanged(location);
double lat = location.getLatitude();
double lon = location.getLongitude();
tvLocInfo.setText(
"lat: " + lat + "\n" +
"lon: " + lon);
}
}*/
#Override
public void onLocationChanged(Location location) {
if (lastLocationloc == null) {
lastLocationloc = location;
}
LatLng lastLatLng = locationToLatLng(lastLocationloc);
LatLng thisLatLng = locationToLatLng(location);
//Log.e(TAG, "Last LatLng is :"+lastLatLng);
//Log.e(TAG, "Last LatLng is :"+thisLatLng);
myMap.addPolyline(new PolylineOptions().add(lastLatLng).add(thisLatLng).width(3).color(Color.RED));
lastLocationloc = location;
}
public static LatLng locationToLatLng(Location loc) {
if (loc != null)
return new LatLng(loc.getLatitude(), loc.getLongitude());
return null;
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
When I go to run application on an actual device nothing happens. No polyline appears. What am I doing wrong?

MapView Null Pointer Exception

I've finished my Hello MapView tutorial but there is a problem in application when I touch the market it just force closes and in LogCat shows java.lang.NullPointerException .
Here is the code:
package rs.iz.stevy.wifi;
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
public class WiFiKupacicaActivity extends MapActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapa= (MapView) findViewById(R.id.Mapa1);
mapa.setBuiltInZoomControls(true);
mapa.setSatellite(true);
List<Overlay> mapOverlays = mapa.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.green);
MapOverlay itemizedoverlay = new MapOverlay(drawable);
GeoPoint point = new GeoPoint(19240000,-99120000);
OverlayItem overlayitem = new OverlayItem(point, "Hello","Just don't force close");
GeoPoint point2 = new GeoPoint(35410000, 139460000);
OverlayItem overlayitem2 = new OverlayItem(point2, "Sekai, konichiwa","Japan!");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
itemizedoverlay.addOverlay(overlayitem2);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
And the second class:
package rs.iz.stevy.wifi;
import java.util.ArrayList;
import android.graphics.drawable.Drawable;
import android.app.AlertDialog;
import android.content.Context;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class MapOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem>mOverlays= new ArrayList<OverlayItem>();
private Context mContext;
public MapOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i); }
#Override
public int size() {
return mOverlays.size();
}
//itemizedoverlay.addOverlay(overlayitem);
//mapOverlays.add(itemizedoverlay);
//#Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
I think problem is probably somewhere about context = mContext; but I can't find where error could be. Please I'll appreciate any help.
Yes it is the context, the onTap method doesn't know what it is, so replace:
public MapOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
with
public MapOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
and your calls to the constructor
with
MapOverlay itemizedoverlay = new MapOverlay(drawable, this);

Categories