user3598397
user3598397

Reputation: 55

Getting coordinates of location touch on google map in android

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

Upvotes: 3

Views: 7472

Answers (3)

Rohit Singh
Rohit Singh

Reputation: 18212

You don't need to implement any Click listener. GoogleMaps API comes with an inbuilt listener which gives the coordinate(LatLng) on Map Click.

Full Code

Activity Code

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMapClickListener{

    private GoogleMap Map;
    private SupportMapFragment mapFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_map);

       mapFragment = (SupportMapFragment) getSupportFragmentManager()
                                              .findFragmentById(R.id.map);

       mapFragment.getMapAsync(this);

    }

   /* 
    *   Its the callback method for OnMapReadyCallback interface
    *   attach listener when the map is ready
    */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setOnMapClickListener(this);
    }

    // Its the callback method for GoogleMap.OnMapClickListener interface
    @Override
    public void onMapClick(LatLng latLng) {
        Log.d("Map", latlng.toString());
    }


}

Layout code: activity_map.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".activities.MapActivity">
    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".activities.AddressActivity"
    />
</RelativeLayout>

Note:

Most important point is to attach the MapClickListener when the map is ready.
For this we put mMap.setOnMapClickListener(this); in onMapReady(GoogleMap googleMap) method else you will get a null pointer exception

Upvotes: 0

Tueti
Tueti

Reputation: 318

Google Maps provides an OnMapClickListener that takes the LatLng. First of, set an onMapClickListener to your map and then do your stuff within the listener. From the top of my head this should look something like

googleMap.setOnMapClickListener(new OnMapClickListener() {
   @Override
   public void onMapClick(LatLng point) {
      Log.d("DEBUG","Map clicked [" + point.latitude + " / " + point.longitude + "]");
      //Do your stuff with LatLng here
      //Then pass LatLng to other activity
   }
});

Put this in initilizeMap() after you made sure, your googleMap isn't null.

I'm currently not able to test the code, but I'm pretty sure it should look like that. Otherwise Google Docs about OnMapClickListener and about LatLng should help out.

Hope this helps you, let me know!

Upvotes: 8

Guy S
Guy S

Reputation: 1424

add OnMapClickListener to your activity and get the coordinates in onMapClick

Upvotes: 0

Related Questions