Android : Getting coordinates of location touch on google map in android

on Tuesday, August 5, 2014


I want to get coordinates of location that is touched and pass it to another activity. Google map is shown in my activity but its touch event is not working. I want to get coordinates of location that is touch and start another activity passing these coordinates to another activity. Its my code:



public class MapActivity extends Activity {
protected LocationManager locationManager;
String stlatitude = null, stlongitude = null;
private GoogleMap googleMap;
String locationName = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Bundle b = getIntent().getExtras();
stlatitude = b.getString("latitude");
stlongitude = b.getString("longitude");
locationName = b.getString("location_name");

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

try {

initilizeMap();

googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
MarkerOptions marker = new MarkerOptions().position(
new LatLng(Float.parseFloat(stlatitude), Float
.parseFloat(stlongitude))).title(locationName);
googleMap.addMarker(marker);
if (stlatitude != null || stlongitude != null) {
LatLng myLatLng = new LatLng(Float.parseFloat(stlatitude),
Float.parseFloat(stlongitude));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
myLatLng, 12.0f));
}

} catch (Exception e) {
e.printStackTrace();
}

}



@Override
protected void onResume() {
super.onResume();
initilizeMap();
}


private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();

// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}

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

0 comments:

Post a Comment