Android GMaps v2 - Get location of the center of the map & map height and width

心不动则不痛 提交于 2019-12-12 05:22:24

问题


I'm trying to get the latitude and longitude of the center of the map in the Google Maps V2 API & get the width and length of the map.

Here is my old code(from GMaps v1 that I started to modify):

import com.google.android.gms.maps.GoogleMap;

private GoogleMap mGoogleMapView;

public LatLng getMapCenter()
{
  if( mGoogleMapView != null )
  {
     return mGoogleMapView.getMapCenter();
  }
  /*if( mOpenStreetMapView != null )
  {
     return convertOSMGeoPoint( mOpenStreetMapView.getMapCenter() );
  }*/
  return null;
}

public int getHeight()
{
  if( mGoogleMapView != null )
  {
     return mGoogleMapView.getHeight();
  }      
  /*if( mOpenStreetMapView != null )
  {
     return mOpenStreetMapView.getHeight();
  }*/
  return 0;
}

public int getWidth()
{
  if( mGoogleMapView != null )
  {
     return mGoogleMapView.getWidth();
  }
  /*else if( mOpenStreetMapView != null )
  {
     return mOpenStreetMapView.getWidth();
  }*/
  return 0;
} 

How can I perform the same functionality that mapView.getMapCenter(), mapView.getHeight(), and mapView.getWidth() using the Android GMaps V2 API?


回答1:


Getting the center:

GoogleMap map;
LatLng center = map.getCameraPosition().target;

Getting the width and height:

If you're adding the MapFragment to your Activity using a FragmentTransaction, you have to provide some ViewGroup to put the fragment into. Something like a LinearLayout or such. Calling getWidth() and getHeight() on such ViewGroup should get you what you want.

Hope it helps. If you need an example, let me know.

EDIT - adding an example:

Take a look at the Google Maps Android API v2, especially at the section named: Add a Fragment.

Under the part that starts with You can also add a MapFragment to an Activity in code, there is an example. In that example, R.id.my_container is exactly the ViewGroup I wrote about above. Somewhere in the XML layout of your Activity, there is something like this:

<LinearLayout
    android:id="@+id/my_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

What the FragmentTransaction does is that it takes a MapFragment and puts it as a child of this LinearLayout. The only child. Therefore the map has the same width and height as the LinearLayout.

Then you can easily get what you need in your Activity like this.

LinearLayout myContainer = (LinearLayout) findViewById(R.id.my_container);
int mapHeight = myContainer.getHeight();
int mapWidth = myContainer.getWidth();

I hope it's understandable.



来源:https://stackoverflow.com/questions/16348524/android-gmaps-v2-get-location-of-the-center-of-the-map-map-height-and-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!