I'm coding an application using osmdroid to show a map and i would like to add a marker to it when user taps over map, actually i have been able to do this usin motion event but this adds a marker even when user is zooming in or out the map i don't want this.
This is the code i have to add the marker:
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int actionType = ev.getAction();
switch (actionType) {
case MotionEvent.ACTION_DOWN:
Projection proj = myOpenMapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int)ev.getX(), (int)ev.getY());
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
List<OverlayItem> anotherOverlayItemArray = new ArrayList<OverlayItem>();
ExtendedOverlayItem mapItem = new ExtendedOverlayItem("", "", new GeoPoint((((double)loc.getLatitudeE6())/1000000), (((double)loc.getLongitudeE6())/1000000)), this);
mapItem.setMarker(this.getResources().getDrawable(R.drawable.marker));
anotherOverlayItemArray.add(mapItem);
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay
= new ItemizedIconOverlay<OverlayItem>(
this, anotherOverlayItemArray, null);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
Toast toast = Toast.makeText(getApplicationContext(), "Longitude: "+ longitude +" Latitude: "+ latitude , Toast.LENGTH_LONG);
toast.show();
}
return super.dispatchTouchEvent(ev);
}
This is how i finally solved it:
Overlay touchOverlay = new Overlay(this){
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = null;
#Override
protected void draw(Canvas arg0, MapView arg1, boolean arg2) {
}
#Override
public boolean onSingleTapConfirmed(final MotionEvent e, final MapView mapView) {
Projection proj = mapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int)e.getX(), (int)e.getY());
longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
ArrayList<OverlayItem> overlayArray = new ArrayList<OverlayItem>();
OverlayItem mapItem = new OverlayItem("", "", new GeoPoint((((double)loc.getLatitudeE6())/1000000), (((double)loc.getLongitudeE6())/1000000)));
mapItem.setMarker(marker);
overlayArray.add(mapItem);
if(anotherItemizedIconOverlay==null){
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
myOpenMapView.invalidate();
}else{
myOpenMapView.getOverlays().remove(anotherItemizedIconOverlay);
myOpenMapView.invalidate();
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
}
dlgThread();
return true;
}
};
myOpenMapView.getOverlays().add(touchOverlay);
You should create an Overlay and override the onSingleTapConfirmed() method to get single-taps:
#Override
public boolean onSingleTapConfirmed(final MotionEvent event, final MapView mapView) {
// Handle single-tap here, then return true.
return true;
}
Related
I'm using osmdroid API for maps in my project.
Below is the code I wrote to put an overlay(marker) on selected location.
If I click on map to select any location, it puts an overlay there, but if I tap on map again to select any new location, it shows a new overlay over there (it should) but it doesn't remove the overlay from previous location.
So if I select 10 locations, it shows 10 overlays!
My question is, how to remove previously put overlays when a new location is selected?
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int actionType = ev.getAction();
switch (actionType) {
case MotionEvent.ACTION_UP:
Projection proj = mMapView.getProjection();
IGeoPoint loc = proj.fromPixels((int)ev.getX(), (int)ev.getY());
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
GeoPoint mypointicon = new GeoPoint(loc.getLatitude(), loc.getLongitude());
final ArrayList<OverlayItem> items=new ArrayList<>();
items.add(new OverlayItem("Here", "Sample Description", mypointicon));
this.mMyLocationOverlay = new ItemizedIconOverlay<>(items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
return true;
}
#Override
public boolean onItemLongPress(final int index, final OverlayItem item) {
return false;
}
}, mResourceProxy);
this.mMapView.getOverlays().add(this.mMyLocationOverlay);
mMapView.invalidate();
Toast.makeText(getApplicationContext(),
"Longitude: "+ longitude +" Latitude: "+ latitude , Toast.LENGTH_LONG).show();
}
return super.dispatchTouchEvent(ev);
}
Basically, you have to manage your map overlays.
You could add an overlay: this.mMapView.getOverlays().add(this.mMyLocationOverlay);
So you also can remove it: this.mMapView.getOverlays().remove(index);
And you can remove all of them: this.mMapView.getOverlays().clear();
I have an application where I fetch longitude and latitude from my database and want to display it in a MapView. I am able to show the one stored most recently, but I think some array is needed in a for loop to add it in an overlay. I don't know how to implement it though.
Here is my buttonClick on which it will fetch lat/long and display it in a MapView:
buttonShowMarkers = (Button) findViewById(R.id.button_SHOW_MARKERS);
buttonShowMarkers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
db = openOrCreateDatabase("LocationFetch.db", MODE_PRIVATE , null);
cursor = db.rawQuery("SELECT * FROM user" , null);
cursor.moveToFirst();
do {
int dataID = cursor.getColumnIndex("id");
String dataString = cursor.getString(0);
Log.d("ID DATA FROM DATABASE---->" , dataString);
String dataNAME = cursor.getString(1).toString().trim();
Log.d("NAME DATA FROM DATABASE---->", dataNAME);
String dataLAT = cursor.getString(2).toString().trim();
Log.d("LAT DATA FROM DATABASE----->" , dataLAT);
int latitude = cursor.getColumnIndex("latitude");
String dataLON = cursor.getString(3).toString().trim();
Log.d("LON DATA FROM DATABASE----->" , dataLON);
int longitude = cursor.getColumnIndex("longitude");
showLatLon(latitude , longitude , dataNAME);
// ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
/* List<Overlay> ListOverlays = mapView.getOverlays();
* OverlayItem[] markerItem = {new OverlayItem(new GeoPoint(latitude, longitude) , ""+dataNAME , ""+dataString)};
* OverlayItem markerItem = new OverlayItem(new GeoPoint((int)(latitude *1E6), (int)(longitude *1E6)) , ""+dataNAME , ""+dataString);
* drawableOne = getResources().getDrawable(R.drawable.location_blue);
* helloItemizedOverlay = new HelloItemizedOverlay(drawableOne);
* helloItemizedOverlay.addOverlayItem(markerItem);
* mapView.getOverlays().add(helloItemizedOverlay);
* ListOverlays.add(myItemizedOverlay);*/
//for(int i = dataID ; )
} while (cursor.moveToNext());
/*String[] arrLat = new String[]{LATdata};
String[] arrLon = new String[]{LONdata};*/
//showLatLon(dataLAT , dataLON);
cursor.moveToNext();
} catch(SQLException e) {
e.printStackTrace();
} finally {
cursor.close();
}
db.close();
}
private void showLatLon(int latitude , int longitude , String nAMEdata) {
// GeoPoint point = new GeoPoint( (latitude) , (latitude) );
List<Overlay> ListOverlays = mapView.getOverlays();
//OverlayItem[] markerItem = {new OverlayItem(new GeoPoint(latitude, longitude) , ""+dataNAME , ""+dataString)};
OverlayItem markerItem = new OverlayItem(new GeoPoint(latitude,latitude ) , ""+nAMEdata , null);
drawableOne = getResources().getDrawable(R.drawable.location_blue);
helloItemizedOverlay = new HelloItemizedOverlay(drawableOne);
helloItemizedOverlay.addOverlayItem(markerItem);
mapView.getOverlays().add(helloItemizedOverlay);
ListOverlays.add(myItemizedOverlay);
}
});
You can try using this solution -
Create a class named LatLonPoint - this basically does the conversion from latlon to GeoPoint -
public class LatLonPoint extends GeoPoint {
public LatLonPoint(double latitude, double longitude) {
super((int) (latitude * 1E6), (int) (longitude * 1E6));
}
}
Create a Itemized Overlay -
public class HelloItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
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();
}
#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;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event, MapView mapView) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
}
return super.onKeyDown(keyCode, event, mapView);
}
}
Now in the main activity -
try {
db = openOrCreateDatabase("LocationFetch.db", MODE_PRIVATE , null);
cursor = db.rawQuery("SELECT * FROM user" , null);
cursor.moveToFirst();
do {
int dataID = cursor.getColumnIndex("id");
String dataString = cursor.getString(0);
Log.d("ID DATA FROM DATABASE---->" , dataString);
String dataNAME = cursor.getString(1).toString().trim();
Log.d("NAME DATA FROM DATABASE---->", dataNAME);
String dataLAT = cursor.getString(2).toString().trim();
Log.d("LAT DATA FROM DATABASE----->" , dataLAT);
int latitude = cursor.getColumnIndex("latitude");
String dataLON = cursor.getString(3).toString().trim();
Log.d("LON DATA FROM DATABASE----->" , dataLON);
int longitude = cursor.getColumnIndex("longitude");
// Add the item here --
itemizedoverlay.addOverlay(new OverlayItem(new LatLonPoint(latitude, longitude), dataNAME, null));
//showLatLon(latitude , longitude , dataNAME);
// ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
/* List<Overlay> ListOverlays = mapView.getOverlays();
* OverlayItem[] markerItem = {new OverlayItem(new GeoPoint(latitude, longitude) , ""+dataNAME , ""+dataString)};
* OverlayItem markerItem = new OverlayItem(new GeoPoint((int)(latitude *1E6), (int)(longitude *1E6)) , ""+dataNAME , ""+dataString);
* drawableOne = getResources().getDrawable(R.drawable.location_blue);
* helloItemizedOverlay = new HelloItemizedOverlay(drawableOne);
* helloItemizedOverlay.addOverlayItem(markerItem);
* mapView.getOverlays().add(helloItemizedOverlay);
* ListOverlays.add(myItemizedOverlay);*/
//for(int i = dataID ; )
} while (cursor.moveToNext());
// Add all itemized overlay here
mapOverlays.add(itemizedoverlay);
/*String[] arrLat = new String[]{LATdata};
String[] arrLon = new String[]{LONdata};*/
//showLatLon(dataLAT , dataLON);
//cursor.moveToNext();
} catch(SQLException e) {
e.printStackTrace();
} finally {
cursor.close();
}
For the above block you have to initialize these two items beffore the do.. while -
List<Overlay> mapOverlays = mMapView.getOverlays();
and
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(
drawable, this);
EDIT-- Adding iterating Cursor Part -
Drawable drawable = this.getResources().getDrawable(
R.drawable.ic_launcher);
List<Overlay> mapOverlays = mMapView.getOverlays();
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(
drawable, this);
while(cursor.moveToNext())
{
// get the values --
int dataID = cursor.getColumnIndex("id");
String dataString = cursor.getString(0);
Log.d("ID DATA FROM DATABASE---->" , dataString);
String dataNAME = cursor.getString(1).toString().trim();
Log.d("NAME DATA FROM DATABASE---->", dataNAME);
String dataLAT = cursor.getString(2).toString().trim();
Log.d("LAT DATA FROM DATABASE----->" , dataLAT);
int latitude = cursor.getColumnIndex("latitude");
String dataLON = cursor.getString(3).toString().trim();
Log.d("LON DATA FROM DATABASE----->" , dataLON);
int longitude = cursor.getColumnIndex("longitude");
// Assuming your logic for retrieving values is correct
// Add into the itemized Overlay here
itemizedoverlay.addOverlay(new OverlayItem(new LatLonPoint(latitude, longitude), dataNAME, null));
}
mapOverlays.add(itemizedoverlay);
I've been trying to add my GeoPoints to the itemizedOverlay Array in order to draw the points on the map. Unfortunately, the app crashing at this point.
My Code:
package com.example.phooogle;
public class GoogleMapsAppActivity extends MapActivity {
private MapView mapView;
private MapController mc;
private MyLocationOverlay myLocationOverlay;
private myMapService mms;
String[] ms;
private LocationManager lm;
private LocationListener locationListener;
private MyLocationOverlay myLocOverlay;
GeoPoint p;
GeoPoint progress1[];
List<GeoPoint> geoPointsArray = new ArrayList<GeoPoint>();
int latitude;
int longitude;
private ProgressDialog progress;
MotionEvent event;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cool_map);
progress= new ProgressDialog(this);
progress.setIndeterminate(true);
progress.setMessage("I am thinking");
InitTask init_task= new InitTask();
init_task.execute("144.963620993985", "-37.8140023779914", "20", "Litter Bin");
try {
String[] arrs = init_task.strArr2;
//Log.d(" print points", " Array Size " + arrs.length);
Drawable makerDefault = this.getResources().getDrawable(R.drawable.poke);
MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
for(int j=0; j<arrs.length ;j++)
{
double y =0;
double x =0;
if(j == 1)
{
/// x
//Log.d("Results", "2If statem " + strArr2[j] );
x = Double.parseDouble(arrs[j]);
y = Double.parseDouble(arrs[j+1]);
//Log.d(" print points", "lat " + x + " long" + y);
itemizedOverlay.addOverlayItem((int) x , (int) y , "La trobe");
mapView.getOverlays().add(itemizedOverlay );
}
}
MapController mc = mapView.getController();
mc.setCenter(new GeoPoint((int) (1E6 * -37.720754), (int) (1E6 * 145.048798))); // Some where .
mc.zoomToSpan(itemizedOverlay.getLatSpanE6(), itemizedOverlay.getLonSpanE6());
} finally {}
initMap();
initMyLocation();
// theRouteDraw();
/*
Drawable makerDefault = this.getResources().getDrawable(R.drawable.poke);
MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
itemizedOverlay.addOverlayItem(init_task.geoPointsArray, "La trobe");
mapView.getOverlays().add(itemizedOverlay );
MapController mc = mapView.getController();
mc.setCenter(new GeoPoint((int) (1E6 * -37.720754), (int) (1E6 * 145.048798))); // Some where .
mc.zoomToSpan(itemizedOverlay.getLatSpanE6(), itemizedOverlay.getLonSpanE6());
for (int i = 0; i < geoPointsArray.size() ; i++)
{
Log.d(" print points", " points " + geoPointsArray.get(i));
}*/
// Log.d(" print points", " Size " + init_task.geoPointsArray.size());
/*
mapView = (MapView) findViewById(R.id.mapview);
List<Overlay> mapOverlays = mapView.getOverlays();
//add any icon here for the marker
Drawable drawable = GoogleMapsAppActivity.this.getResources().getDrawable(R.drawable.poke);
MapViewItemizedOverlay itemizedOverlay = new MapViewItemizedOverlay(drawable,this);
//use your array here instead
//GeoPoint point1 = new GeoPoint(lat,lng);
OverlayItem overlayitem1 = new OverlayItem(point1, "Info", "You are here!" );
itemizedOverlay.addOverlay(overlayitem1);
mapOverlays.add(itemizedOverlay);
*/
}
private void initMap()
{
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// mapView.setStreetView(true);
mc = mapView.getController();
}
public void theRouteDraw(GeoPoint p){
mc.animateTo(p);
mc.setZoom(13);
mapView.invalidate();
mapView.setSatellite(true);
}
private void initMyLocation() {
myLocOverlay = new MyLocationOverlay(this, mapView);
myLocOverlay.enableMyLocation();
mapView.getOverlays().add(new myLocOverlay());
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class myLocOverlay extends Overlay{
public void draw(Canvas canvas, MapView mapv, boolean shadow){
super.draw(canvas, mapv, shadow);
Projection projection = mapView.getProjection();
Path p1 = new Path();
for (int i = 0; i < geoPointsArray.size(); i++) {
if (i == geoPointsArray.size() - 1) {
break;
}
Point from = new Point();
Point to = new Point();
projection.toPixels(geoPointsArray.get(i), from);
projection.toPixels(geoPointsArray.get(i + 1), to);
p1.moveTo(from.x, from.y);
p1.lineTo(to.x, to.y);
}
Paint mPaint = new Paint();
mPaint.setStyle(Style.STROKE);
mPaint.setColor(Color.BLACK);
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(4);
canvas.drawPath(p1, mPaint);
super.draw(canvas, mapView, shadow);
}
}
private class InitTask extends AsyncTask<String, GeoPoint, List<GeoPoint>> {
List<GeoPoint> geoPointsArray = new ArrayList<GeoPoint>();
GeoPoint p;
private ProgressDialog progressDialog;
private String rst = " " ;
private String[] strArr1;
private String[] strArr2;
protected void onPreExecute() {
//progress.show();
}
#Override
protected List<GeoPoint> doInBackground(String... arg0) {
String result = "";
int responseCode = 0;
int executeCount = 0;
HttpResponse response;
StringBuilder sb = new StringBuilder();
String line;
try
{
HttpClient client = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://xxxx/ccvo/mel-asset-data/query.php?lon="+ arg0[0].toString() + "&lat="+ arg0[1].toString() +"&within=" + arg0[2].toString() + "&keyword="+ arg0[3].toString().replace(" ", "%20"));
do
{
// progressDialog.setMessage("Passing paratmeters.. ("+(executeCount+1)+"/5)");
// Execute HTTP Post Request
executeCount++;
response = client.execute(httppost);
responseCode = response.getStatusLine().getStatusCode();
} while (executeCount < 5 && responseCode == 408);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null)
{
result = line.trim();
sb.append(line);
}
}catch (Exception e2) {
responseCode = 408;
e2.printStackTrace();
}
rst = result.toString();
// splits everything
if(rst != null && rst.length() > 0)
{
strArr1 = rst.split("\\|");
for(int i=0;i<strArr1.length;i++)
{
// Log.d("Results", "Array size1.1 " + i);
Log.v("Results", "Array split1.2 " + strArr1[i] );
if(strArr1[i] != null && strArr1[i].length() >0 && strArr1[i].contains(","))
{
strArr2 = strArr1[i].split(",");
for(int j=0; j<strArr2.length ;j++)
{
double y =0;
double x =0;
if(j == 1)
{
/// x
//Log.d("Results", "2If statem " + strArr2[j] );
x = Double.parseDouble(strArr2[j]);
y = Double.parseDouble(strArr2[j+1]);
geoPointsArray.add(new GeoPoint((int)(x*1e6), (int)(y*1e6)));
Log.d("geoPointsArray", "geoPointsArray " + geoPointsArray.toString() );
}
}
}
}
}
return geoPointsArray;
}
#Override
protected void onProgressUpdate(GeoPoint... progress1) {
theRouteDraw(progress1[0]);
geoPointsArray.add(progress1[0]);
int lon=progress1[0].getLongitudeE6();
int lat=progress1[0].getLatitudeE6();
GeoPoint p2=new GeoPoint(lon,lat);
geoPointsArray.add(p2);
initMyLocation();
}
#Override
protected void onPostExecute(List<GeoPoint> geoPointsArray)
{
//super.onPostExecute(geoPointsArray);
progress.dismiss();
//startActivity(i);
//i.getCharExtra("Geop", geoPointsArray);
Log.d("Lista", " check " + geoPointsArray.size());
// theRouteDraw(geoPointsArray);
}
}
}
My MirItemizedOverlay Class:
class MirItemizedOverlay extends ItemizedOverlay {
private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public MirItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
mOverlays.add(overlayItem);
populate();
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
}
return false;
}
private Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
public void addOverlayItem(int lat, int lon, String title) {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
}
/* public void addOverlayItem(GeoPoint point , String title) {
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
//GeoPoint point = new GeoPoint(lat, lon);
}*/
}
The error :
: E/AndroidRuntime(2752): FATAL EXCEPTION: main
: E/AndroidRuntime(2752): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.phooogle/com.example.phooogle.GoogleMapsAppActivity}: java.lang.NullPointerException
: E/AndroidRuntime(2752): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
: E/AndroidRuntime(2752): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
: E/AndroidRuntime(2752): at android.app.ActivityThread.access$600(ActivityThread.java:130)
: E/AndroidRuntime(2752): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
: E/AndroidRuntime(2752): at android.os.Handler.dispatchMessage(Handler.java:99)
: E/AndroidRuntime(2752): at android.os.Looper.loop(Looper.java:137)
: E/AndroidRuntime(2752): at android.app.ActivityThread.main(ActivityThread.java:4745)
: E/AndroidRuntime(2752): at java.lang.reflect.Method.invokeNative(Native Method)
: E/AndroidRuntime(2752): at java.lang.reflect.Method.invoke(Method.java:511)
: E/AndroidRuntime(2752): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
: E/AndroidRuntime(2752): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
: E/AndroidRuntime(2752): at dalvik.system.NativeStart.main(Native Method)
: E/AndroidRuntime(2752): Caused by: java.lang.NullPointerException
: E/AndroidRuntime(2752): at com.example.phooogle.GoogleMapsAppActivity.onCreate(GoogleMapsAppActivity.java:68)
I've tried several ways to do like I tried to change the addOverlayItem method to accept the GeoPoitns from the AsyncTask return but also failed. I almost gave me on this. :)
Update
The problem resolved. Here is the fix:
try {
//String[] arrs = init_task.strArr2;
List<GeoPoint> geoL = init_task.get();
//Log.d(" Get the size " , " Geo List " + geoL.get(1).toString());
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
List<Overlay> listOfOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.poke);
MyItemizedOverlay itemizedoverlay = new MyItemizedOverlay(drawable, this);
for ( int i = 0; i < geoL.size() ; i++)
{
OverlayItem overlayitem1 = new OverlayItem(geoL.get(i), Selectedword + "s found! " , "It's withing " + selectedDistance + " To your position");
itemizedoverlay.addOverlay(overlayitem1);
listOfOverlays.add(itemizedoverlay);
}
//mc.animateTo(geoL.get(1));
mc.setCenter(new GeoPoint((int) (1E6 * gps.getLatitude() ), (int) (1E6 * gps.getLongitude() ))); // Some where .
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {}
initMap();
initMyLocation();
// theRouteDraw();
Your issue is that mapView is null, you haven't called initMap() yet. This causes mapView.getOverlays().add(itemizedOverlay ); to fail.
In my mapview, Used geocding inside SingleTapUp.
Whenever zoom controls of mapview are used, singleTapUp also gets invoked.
Any suggestions to overcome this scenario.
The code in my main method
public static TextView info;
private MapController mapController;
private MapView mapView;
public LocationManager orgManager;
private MyOverlays itemizedoverlay, blackmarker;
public boolean gps_enabled = false;
public boolean network_enabled = false;
public Criteria c;
public String bestProvider;
public double orginLongitude, orginLatitude, destLongtitude, destLatitude,
currLatitude, currLongtitude, lat, lon;
public boolean isLongPress= false, GPSfix = false;
Location originLocation = new Location("source");
Location currLocation = new Location("current");
Location destinationLocation = new Location("destination");
Location fixlocation= new Location("fix");
NotificationManager nm;
Vibrator v;
MediaPlayer mp = new MediaPlayer();
private TextToSpeech myTTS;
private int MY_DATA_CHECK_CODE = 0;
private List<Overlay> mapOverlays;
private Projection projection;
GestureDetector gestureScanner;
long lastGesture = System.currentTimeMillis();
GeoPoint markerPoint = null;
private int count = 0;
MyLocationOverlay mo;
public GeoPoint source;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
info = (TextView) findViewById(R.id.infopane);
mapView = (MapView) findViewById(R.id.mapView);
//Button myloc = (Button)findViewById(R.id.myloc);
info.setText("Please Tap on the Map");
orgManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
markerPoint = null;
mapController = mapView.getController();
mapController.setZoom(16); // Zoom 1 is world view
mapView.invalidate();
mo = new MyLocationOverlay(MapClass.this, mapView);
mapView.getOverlays().add(mo);
mapOverlays = mapView.getOverlays();
projection = mapView.getProjection();
Drawable drawable = this.getResources()
.getDrawable(R.drawable.mark_red);
Drawable black_marker = this.getResources().getDrawable(
R.drawable.marker_black);
itemizedoverlay = new MyOverlays(drawable);
blackmarker = new MyOverlays(black_marker);
try {
gps_enabled = orgManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.i("success", "Gps:" + String.valueOf(gps_enabled)+ "N/w:" + String.valueOf(network_enabled) );
} catch (Exception ex) {
Log.i("sample", "sample");
}
if (!gps_enabled) {
Log.i("failure", "Gps:" + String.valueOf(gps_enabled)+ "N/W:" + String.valueOf(network_enabled) );
final AlertDialog.Builder builder = new AlertDialog.Builder(MapClass.this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please open app after enabling GPS & wireless networks").setCancelable(false).setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if(gps_enabled){
orgManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
fixlocation = orgManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.i("fix", String.valueOf(fixlocation.getLatitude() + fixlocation.getLongitude()));
if (fixlocation!=null){
originLocation.setLatitude(fixlocation.getLatitude());
originLocation.setLongitude(fixlocation.getLongitude());
Log.i("origin fix", String.valueOf(originLocation.getLatitude() + originLocation.getLongitude()));
GPSfix = true;
}else Toast.makeText(MapClass.this, "", Toast.LENGTH_SHORT).show();
}
if (GPSfix) {
// double a = originLocation.getLatitude();
// double b = originLocation.getLongitude();
source = new GeoPoint(
(int) ((fixlocation.getLatitude()) * 1E6),
(int) ((fixlocation.getLongitude()) * 1E6));
mapController.animateTo(source);
mapView.getMapCenter();
createMarker();
Toast.makeText( MapClass.this," Source GPS Values Latitude: "
+ fixlocation.getLatitude() + " Longitude: "
+ fixlocation.getLongitude(), Toast.LENGTH_SHORT).show();
}
else Toast.makeText(MapClass.this, "Wait for GPS", Toast.LENGTH_SHORT).show();
gestureScanner = new GestureDetector(this, this);
}
The code in gesture scanner method.
onLongPress
#Override
public void onLongPress(final MotionEvent e) {
// TODO Auto-generated method stuMapClass Toast.makeText(MapClass.this,
// "LongPress", Toast.LENGTH_SHORT)
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MapClass.this);
// Setting Dialog Title
alertDialog.setTitle("Alert!!");
// Setting Dialog Message
alertDialog.setMessage("Do you want to select this as destination");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
String add = "";
GeoPoint geopoint = mapView.getProjection().fromPixels(
(int) e.getX(), (int) e.getY());
// latitude
lat = geopoint.getLatitudeE6() / 1E6;
// longitude
lon = geopoint.getLongitudeE6() / 1E6;
Geocoder geoCoder = new Geocoder(getBaseContext(),
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
geopoint.getLatitudeE6() / 1E6,
geopoint.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int i = 0; i < addresses.get(0)
.getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i)
+ "\n";
}
Toast.makeText(getBaseContext(), add,
Toast.LENGTH_SHORT).show();
} catch (IOException ioe) {
ioe.printStackTrace();
}
mapOverlays.add(new MyOverlay((originLocation
.getLatitude()),
(originLocation.getLongitude()), lat, lon));
destinationLocation.setLatitude(lat);
destinationLocation.setLongitude(lon);
String distance = Float.toString((originLocation
.distanceTo(destinationLocation) / 1000));
createblack();
count++;
Toast.makeText(getBaseContext(), distance + "kms",
Toast.LENGTH_SHORT).show();
info.setText("Selected destination is " + "\n" + add
+ "\n" + " The journey distance is " + distance
+ " Kms ");
mapView.postInvalidate();
isLongPress = true;
mapController.animateTo(source);
mapView.getMapCenter();
}
private void createblack() {
// TODO Auto-generated method stub
GeoPoint p = new GeoPoint((int) (lat * 1E6),
(int) (lon * 1E6));
OverlayItem overlayitem = new OverlayItem(p,
"Destination", "");
blackmarker.addOverlay(overlayitem);
mapView.getOverlays().add(blackmarker);
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(),
"You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
OnsingeTapup
#Override
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
Log.i("SingleTap", arg0.toString());
GeoPoint geopoint = mapView.getProjection().fromPixels(
(int) arg0.getX(), (int) arg0.getY());
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
geopoint.getLatitudeE6() / 1E6,
geopoint.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0) {
for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
if (count == 0) {
info.setText("The location you have selected is" + "\n" + add
+ "\n" + "To confirm it longpress the location");
} else
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT)
.show();
} catch (IOException ioe2) {
ioe2.printStackTrace();
}
return true;
}
Additionally used a Overlay Class to place markers..
It is a bit hard to debug your code as there are important parts missing but I would suggest taking a look at the following answer to a similar StackOverflow question:
https://stackoverflow.com/a/2990749/376016
The proposed solution for recognising gestures on the MapView is to create a custom Overlay that only handles touch events and insert it as the first overlay. Using this approach I was able to create a small test application that used most of your code and correctly ignored the pinch to zoom gestures on the MapView.
I'm trying to apply the tutorial: http://deckjockey.blogspot.com/2010/01/android-baloon-display-on-map.html?showComment=1322215574598#c3178096297154271518 on my code, and I'm facing a small difficulty - it doesn' work,
here is my code:
public void HuntCl(View v) throws UnknownHostException, IOException{
String sentenceX, sentenceY = null;
try {
clientSocket = new Socket("10.0.2.2", 1234);
Log.d("LatitudeE6", ""+point.getLatitudeE6());
Log.d("LongitudeE6", ""+point.getLongitudeE6());
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentenceX = ""+point.getLatitudeE6();
sentenceY = ""+point.getLongitudeE6();
outToServer.writeBytes(sentenceX + " "+ sentenceY+'\n');
String ciekawostka = inFromServer.readLine();
String [] holder = ciekawostka.split("\\s+");
for(int i =0; i<holder.length; i++){
x = Integer.valueOf(holder[i]);
y= Integer.valueOf(holder[i+1]);
marker=getResources().getDrawable(R.drawable.pin);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
POI funPlaces = new POI(marker,x,y);
mapView.getOverlays().add(funPlaces);
GeoPoint pt = funPlaces.getCenter();
mapView.getController().setCenter(pt);
}
} catch (Exception e) {
Log.d("error","TCP Error: " + e.toString());
}
}
class POI extends ItemizedOverlay {
private List<OverlayItem> locations = new ArrayList<OverlayItem>();
private Drawable marker;
public POI(Drawable marker, int tX, int tY)
{
super(marker);
this.marker=marker;
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
BaloonLayout noteBaloon = (BaloonLayout) layoutInflater.inflate(R.layout.ballon, null);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(200,100);
layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
noteBaloon.setLayoutParams(layoutParams);
mapView.removeView(noteBaloon);
noteBaloon.setVisibility(View.VISIBLE);
// TextView textmsg = (TextView) noteBaloon.findViewById(R.id.note_text);
TextView textmsg = (TextView) noteBaloon.findViewById(R.id.text);
textmsg.setText("I am a Popup Balloon!!!");
mapView.addView(noteBaloon, new MapView.LayoutParams(200,200, new OverlayItem(new GeoPoint((int)(tX),(int)(tY)), "Seven Lagoon", "Seven Lagoon").getPoint(),MapView.LayoutParams.BOTTOM_CENTER));
mapView.setEnabled(false);
locations.add(new OverlayItem(new GeoPoint((int)(tX),(int)(tY)), "Seven Lagoon", "Seven Lagoon"));
populate();
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
boundCenterBottom(marker);
}
#Override
protected OverlayItem createItem(int i) {
return locations.get(i);
}
#Override
public int size() {
return locations.size();
}
}
}
android-mapviewballoons library provides an easy way to annotate map overlay items with a simple information balloon when using Google Maps. Create a subclass of
BalloonItemizedOverlay
in the same way you would do for the base
ItemizedOverlay
class.
Here is a sample output