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.
Related
Using Map Api V2 I have drawn a route on the map. Now i wish to save this route in my database.
So I need to get the lat/lng of points on the route say after each 100 meters which i will save as a polygon. How can i do it in Google Map V2 in android.
i am stuck on it from last 10 days but not getting a solution.
any help will be appriciable :)
public class NavigationActivity extends FragmentActivity {
public static final String TAG_SLAT = "sourcelat";
public static final String TAG_SLONG = "sourcelong";
public static final String TAG_DLAT = "destinationlat";
public static final String TAG_DLONG = "destinationg";
private static LatLng Source = null;
private static LatLng Destination = null;
private GoogleMap map;
private SupportMapFragment fragment;
private LatLngBounds latlngBounds;
private Button bNavigation;
private Polyline newPolyline;
private Marker smarker;
private Marker dmarker;
Geocoder geocoder;
private boolean isTraveling = false;
private int width, height;
private String sourcelat;
private String sourcelong;
private String destinationg;
private String destinationlat;
double slat;
double slong;
double dlat;
double dlong;
double d;
double tempDistance;
String distance;
ConnectionDetector cd;
Boolean isConnectingToInternet = false;
String ts;
LatLng latLng;
GPSTracker gps;
List<Address> addresses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_navigation);
cd = new ConnectionDetector(getApplicationContext());
isConnectingToInternet = cd.isConnectingToInternet();
if (isConnectingToInternet) {
Intent in = getIntent();
sourcelat = in.getStringExtra(TAG_SLAT);
destinationlat = in.getStringExtra(TAG_DLAT);
destinationg = in.getStringExtra(TAG_DLONG);
sourcelong = in.getStringExtra(TAG_SLONG);
slat = Double.parseDouble(sourcelat);
slong = Double.parseDouble(sourcelong);
dlat = Double.parseDouble(destinationlat);
dlong = Double.parseDouble(destinationg);
Source = new LatLng(slat, slong);
Destination = new LatLng(dlat, dlong);
getSreenDimanstions();
fragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
map = fragment.getMap();
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
map.setTrafficEnabled(true);
ImageButton cureent_location = (ImageButton) findViewById(R.id.clocation);
cureent_location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onLocationChanged();
}
});
if (!isTraveling) {
isTraveling = true;
findDirections(Source.latitude, Source.longitude, Destination.latitude, Destination.longitude, GMapV2Direction.MODE_DRIVING);
} else {
isTraveling = false;
}
}else {
AlertUtils.showAlertDialog(NavigationActivity.this, "No Internet Detected", "Please check your internet connection.", false);
}
}
public double calculateDistance(double fromLatitude,double fromLongitude,double toLatitude,double toLongitude)
{
float results[] = new float[1];
try {
Location.distanceBetween(fromLatitude, fromLongitude, toLatitude, toLongitude, results);
} catch (Exception e) {
if (e != null)
e.printStackTrace();
}
if (Source.equals(Destination)){
distance="0";
}
else {
int dist = (int) results[0];
if (dist <= 0)
return 0D;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
results[0] /= 1000D;
distance = decimalFormat.format(results[0]);
double d = Double.parseDouble(distance);
double speed = 40;
double time = d / speed;
ts = manual(time);
Log.v("fdf", String.valueOf(ts));
}
return d;
}
private static String manual(double eta) {
int hour = (int) eta;
eta = (eta - hour) * 60;
int minutes = (int) eta;
eta = (eta - minutes) * 60;
int seconds = (int) eta;
eta = (eta - seconds) * 1000;
int ms = (int) eta;
//Log.d("ffgfh", String.valueOf(eta));
return String.format("%dHr %dMin ", hour, minutes);
}
#Override
protected void onResume() {
super.onResume();
latlngBounds = createLatLngBoundsObject(Source, Destination);
map.moveCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 100));
}
public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) {
PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.RED);
//MarkerOptions marker = new MarkerOptions().position(Source).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
MarkerOptions marker1 = new MarkerOptions().position(Destination).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
for(int i = 0 ; i < directionPoints.size() ; i++)
{
rectLine.add(directionPoints.get(i));
}
if (newPolyline != null)
{
newPolyline.remove();
}
newPolyline = map.addPolyline(rectLine);
//smarker = map.addMarker(marker);
dmarker = map.addMarker(marker1);
if (isTraveling) {
latlngBounds = createLatLngBoundsObject(Source, Destination);
map.animateCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 100));
Dialog dialog_help = new Dialog(this);
dialog_help .requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog_help.setContentView(R.layout.title_multi_selectitems_dialog);
calculateDistance(slat, slong, dlat, dlong);
TextView dis = (TextView) dialog_help.findViewById(R.id.distance);
dis.setText("Distance " + distance + "Km ");
TextView tim = (TextView) dialog_help.findViewById(R.id.time);
tim.setText("Time " + ts);
dialog_help.setCancelable(true);
dialog_help.setTitle("Distance & Time" );
dialog_help.setCanceledOnTouchOutside(true);
dialog_help.show();
dialog_help.getWindow().setGravity(Gravity.CENTER);
dialog_help.getWindow().setBackgroundDrawable(new ColorDrawable(Color.LTGRAY));
dialog_help.getWindow().setLayout(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
}
else {
map.animateCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 100));
}
}
private void getSreenDimanstions()
{
Display display = getWindowManager().getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
}
private LatLngBounds createLatLngBoundsObject(LatLng firstLocation, LatLng secondLocation)
{
if (firstLocation != null && secondLocation != null)
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(firstLocation).include(secondLocation);
return builder.build();
}
return null;
}
public void findDirections(double fromPositionDoubleLat, double fromPositionDoubleLong, double toPositionDoubleLat, double toPositionDoubleLong, String mode)
{
Map<String, String> map = new HashMap<String, String>();
map.put(GetDirectionsAsyncTask.USER_CURRENT_LAT, String.valueOf(fromPositionDoubleLat));
map.put(GetDirectionsAsyncTask.USER_CURRENT_LONG, String.valueOf(fromPositionDoubleLong));
map.put(GetDirectionsAsyncTask.DESTINATION_LAT, String.valueOf(toPositionDoubleLat));
map.put(GetDirectionsAsyncTask.DESTINATION_LONG, String.valueOf(toPositionDoubleLong));
map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE, mode);
GetDirectionsAsyncTask asyncTask = new GetDirectionsAsyncTask(this);
try {
asyncTask.execute(map);
}catch (Exception e){
Toast.makeText(getBaseContext(), "Something went Wrong", Toast.LENGTH_SHORT).show();
}
}
public void onLocationChanged( ){
TextView cl = (TextView) findViewById(R.id.latlongLocation);
cd = new ConnectionDetector(getApplicationContext());
isConnectingToInternet = cd.isConnectingToInternet();
if (isConnectingToInternet) {
gps = new GPSTracker(NavigationActivity.this);
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
latLng = new LatLng(latitude, longitude);
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0);
String prmises = addresses.get(0).getAddressLine(1);
String city = addresses.get(0).getAddressLine(2);
String country = addresses.get(0).getAddressLine(3);
cl.setText(address + " " + prmises + " " + city + " " + country);
}else {
AlertUtils.showAlertDialog(NavigationActivity.this, "No Internet Detected", "Please check your internet connection.", false);
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}
You can try it with this map application: http://maps.cloudmade.com/.
At first you create your route with waypoints. Click on the button "Get directions" (upper left corner) and create your route (clicking on the map). After that you can export (there is a button on the upper right corner) your route (include waypoints) to a gpx-or a json-file. You can load both files to a GIS.
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.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to put JSON lOutput (latitude and longitude) on the map
I have a main activity which parses the JSON data from my mysql (table tracking:Lattitude and longitude) Now I want to pass this data in to my MapActivity and display on google maps. Any help is highly appreciated. Thanks!
this my JSONactivity
public class JSONActivity extends Activity{
private JSONObject jObject;
private String xResult ="";
//Seusuaikan url dengan nama domain
private String url = "http://10.0.2.2/labiltrack/daftartracking.php";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.daftartrack);
TextView txtResult = (TextView)findViewById(R.id.TextViewResult);
//url += "?lattitude=" + UserData.getEmail();
xResult = getRequest(url);
try {
parse(txtResult);
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse(TextView txtResult) throws Exception {
// TODO Auto-generated method stub
jObject = new JSONObject(xResult);
JSONArray menuitemArray = jObject.getJSONArray("joel");
String sret="";
//int j = 0;
for (int i = 0; i < menuitemArray.length(); i++) {
sret +=menuitemArray.getJSONObject(i).
getString("lattitude").toString()+" : ";
System.out.println(menuitemArray.getJSONObject(i)
.getString("lattitude").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"longitude").toString());
sret +=menuitemArray.getJSONObject(i).getString(
"lattitude").toString()+"\n";
//j=i;
}txtResult.setText(sret);
}
/**
* Method untuk Mengirimkan data keserver
* event by button login diklik
*
* #param view
*/
private String getRequest(String url) {
// TODO Auto-generated method stub
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try{
HttpResponse response = client.execute(request);
sret =request(response);
}catch(Exception ex){
Toast.makeText(this,"jo "+sret, Toast.LENGTH_SHORT).show();
}
return sret;
}
/**
* Method untuk Menenrima data dari server
* #param response
* #return
*/
private String request(HttpResponse response) {
// TODO Auto-generated method stub
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
}
and this my mapActivity
public class mapactivity extends MapActivity {
private MapView mapView;
MapController mc;
GeoPoint p;
//private MyLocationOverlay me = null;
class MapOverlays extends com.google.android.maps.Overlay
{
#Override
public boolean draw (Canvas canvas, MapView mapView, boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
//translate the geopoint to screen pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//tambah marker
Bitmap bmp = BitmapFactory.decodeResource(getResources (), R.drawable.pin_red);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
//mapView.setSatellite(true);
return true;
}
#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();
mc.animateTo(p);
//geocoding
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.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";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
} }
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview1);
//utk mnampilkan zoom
mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
mapView.displayZoomControls(true);
//menampilkan default peta banda aceh
mc = mapView.getController();
String coordinates[] = {"5.550381", "95.318699"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(14);
mapView.invalidate();
//tambah marker
MapOverlays mapOverlay = new MapOverlays();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
public void btnSatelitClick(View v){
mapView.setSatellite(true);
mapView.setStreetView(false);
}
public void btnjalanClick (View v){
mapView.setSatellite(false);
mapView.setStreetView(true);
}
protected boolean isRouteDisplayed()
{
//auto generate method
return false;
}
}
as you have only to variable to pass so use intent and pass the data ......and i think you have rest of code writen
put in the JSONActivity from where you want to open mapActivity and you alos have the variable latitude and longitude with their values
Intent i= new Intent(getApplicationContext(), mapActivity.class);
i.putExtra("lattitude",lattitude);
i.putExtra("longitude",longitude);
startActivity(i);
Then in the new activity mapActivity, retrieve those values:
inplace of this put String coordinates[] = {"5.550381", "95.318699"};
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String lattitude= extras.getString("lattitude");
String longitude= extras.getString("longitude");
double lat = Double.parseDouble(lattitude);
double lng = Double.parseDouble(longitude);
}
I want display Google maps in the Android Based on the user edit text value lat and lang and place name and then i finally click on the search button the maps was displayed in Android.
you need to create some object like.
MapView mapView;
MapController mc;
GeoPoint p;
String add = "";
double lattitude ;
double longitude;
Searching location by Name and show Maps.
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Search Location");
alert.setMessage("Enter Location Name: ");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
// Do something with value!
Log.d("value", value);
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
value, 5);
String add = "";
if (addresses.size() > 0) {
p = new GeoPoint(
(int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
mc.animateTo(p);
mapView.invalidate();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
Searching location by Entering Latitude and Longitude and show map..
searchUsingLangLat()
{
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.latlong, null);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Search Location");
alert.setMessage("Enter Lattitude and Longitude: ");
alert.setView(textEntryView);
// Set an EditText view to get user input
AlertDialog latLongPrompt = alert.create();
final EditText lat = (EditText) textEntryView.findViewById(R.id.lat);
final EditText longi = (EditText) textEntryView.findViewById(R.id.longi);
//alert.setView(lat);
//alert.setView(longi);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(getBaseContext(), "clicked ok ", Toast.LENGTH_SHORT).show();
Double value1 = Double.parseDouble(lat.getText().toString());
Double value2 = Double.parseDouble(longi.getText().toString());
// Do something with value!
// Log.d("value1", value1);
//Log.d("value2", value2);
p = new GeoPoint(
(int) (value1 * 1E6),
(int) (value2 * 1E6));
mc.animateTo(p);
mc.setZoom(17);
mapView.invalidate();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
And finally you need to show map. write following code in onCreate() method.
mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
mc = mapView.getController();
String coordinates[] = {"1.352566007", "103.78921587"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.setCenter(p);
mc.setZoom(17);
//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);
Try this code...if you get any error free to ask.
If you store the Latitude and Longitude of a bunch of locations in a SQLite Database, You could retrieve these values and place them each in an OverlayItem class for use in Google's Map code!!
Database name: database
Table name: place
Fields in place Table:
id
title
description
latitude
longitude
You would want to do a query like this:
SELECT title, description, latitude, longitude
FROM place
Which can be done in Android like this:
// get your database object here using your DbHelper object and the
// method getReadableDatabase();
ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
Cursor locationCursor = databaseObject.query("place", new String[] {
"title", "description", "latitude", "longitude" }, null, null,
null, null, null);
locationCursor.moveToFirst();
do {
String title = locationCursor.String(locationCursor
.getColumnIndex("title"));
String description = locationCursor.String(locationCursor
.getColumnIndex("description"));
int latitude = (int) (locationCursor.getDouble(locationCursor
.getColumnIndex("latitude")) * 1E6);
int longitude = (int) (locationCursor.getDouble(locationCursor
.getColumnIndex("longitude")) * 1E6);
items.add(new OverlayItem(new GeoPoint(latitude, longitude), title,
description));
} while (locationCursor.moveToNext());
You need to times the double values by 1e6 because Android uses an integer representation of the lat/long values. If you already took care of this when populating the database, skip the multiplication and use locationCursor.getInt(...).
Im trying to display the address from an EditText using geoCoder and also it would be able editable to click on the finder button and update the googlemap display on the top of the screen, this is my code:
Geocoder geocoder = null;
MapView mapView = null;
int lat, lng;
EditText loc;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.geoMap);
try
{
loc = (EditText)findViewById(R.id.location);
String locationName = loc.getText().toString();
List<Address> addressList = geocoder.getFromLocationName(locationName, 5);
if (addressList != null && addressList.size() > 0) {
lat = (int) addressList.get(0).getLatitude() * 1000000;
lng = (int) addressList.get(0).getLongitude() * 1000000;
GeoPoint pt = new GeoPoint(lat, lng);
mapView.getController().setZoom(10);
mapView.getController().setCenter(pt);
mapView.getController().animateTo(pt);
}
}
catch
(IOException e)
{
e.printStackTrace();
}
//
Button geoBtn = (Button) findViewById(R.id.geocodeBtn);
geocoder = new Geocoder(this);
//
geoBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
EditText loc = (EditText) findViewById(R.id.location);
String locationName = loc.getText().toString();
List<Address> addressList = geocoder.getFromLocationName(locationName, 5);
if (addressList != null && addressList.size() > 0) {
int lat = (int) addressList.get(0).getLatitude() * 1000000;
int lng = (int) addressList.get(0).getLongitude() * 1000000;
GeoPoint pt = new GeoPoint(lat, lng);
mapView.getController().setZoom(10);
mapView.getController().setCenter(pt);
mapView.getController().animateTo(pt);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
But it crashes at this point: List addressList = geocoder.getFromLocationName(locationName, 5);
Im using googles APi 2.3.3.