Search code examples
javaandroidgoogle-mapsgoogle-maps-api-2

Getting maps center coordinates on button press, crashes


I'm trying to get the latitude and longitude of the maps center (google maps api v2) to display in a textview on button press. But it keeps crashing. I've tried a couple of things, and this is what looks the best to me, but in crashes once you press the button:

I think it crashes on this line: MapView mapView = (MapView)findViewById(R.id.map); (cause i tried deleting everything else in the onClick, and it still crahes)

Java:

public class Main extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
        final GoogleMap map = ((SupportMapFragment)  getSupportFragmentManager().findFragmentById(R.id.map))
                   .getMap();

        map.setMyLocationEnabled(true);


        final TextView latitudeTV = (TextView) findViewById(R.id.latitude);
        final TextView longitudeTV = (TextView) findViewById(R.id.longitude);

        Button buttonCoor = (Button) findViewById(R.id.getCoor);    
        buttonCoor.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                MapView mapView = (MapView)findViewById(R.id.map);
                GeoPoint mapCenter = mapView.getMapCenter();
                int latInt = mapCenter.getLatitudeE6();
                int lonInt = mapCenter.getLongitudeE6();
                latitudeTV.setText(latInt);
                longitudeTV.setText(lonInt);

            }
        });

    }

What's wrong with my code?

I can't run it on the emulator due to api keys, so can't get any logcat info.

Thank you

UPDATE:

I have also tried this, but same result (crash on button press)

        MapView mapView = (MapView)findViewById(R.id.map);
    GeoPoint mapCenter = mapView.getProjection().fromPixels(
        mapView.getWidth()/2,
        mapView.getHeight()/2);

final int lat = mapCenter.getLatitudeE6();
final int lon = mapCenter.getLongitudeE6();

Solution

  • I finally solved spend almost 4 hours , haha! This is what i ended up with:

    final GoogleMap map = ((SupportMapFragment)  getSupportFragmentManager().findFragmentById(R.id.map)).getMap();  
    ...
    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();
    int height = display.getHeight();
    Point point = new Point(width / 2, height / 2);
    LatLng latLng = map.getProjection().fromScreenLocation(point);
    
    latitudeTV.setText(String.valueOf(latLng));
    

    Thanks to this guy's tutorial:

    http://patesush.blogspot.dk/2012/12/how-to-create-app-for-google-map-v2-in.html