2

I have used mapFragment to show google map in my app. I wanted to get latitude and longitude of center of the map.

I have placed marker image at center of the map in xml file,

<fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

     <ImageView  android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/marker_image"
        />

So this places marker at center of the screen so as user drags map i should be able to get latitude and longitude of the center of the map.

This is what i used to get center of the map,

VisibleRegion visibleRegion = googleMap.getProjection()
                    .getVisibleRegion();

Point x = googleMap.getProjection().toScreenLocation(visibleRegion.farRight);

Point y = googleMap.getProjection().toScreenLocation(visibleRegion.nearLeft);

Point centerPoint = new Point(x.x / 2, y.y / 2);

LatLng centerFromPoint = googleMap.getProjection().fromScreenLocation(
                    centerPoint);

Issue is i am getting value of centerFromPoint LatLng value as 0.0.

I even tried to use

LatLng loc = googleMap.getCameraPosition().target;

Even in this case i am getting loc value as 0.0.

I am not able to figure out why i am not getting latitude and longitude value.

Joyal
  • 414
  • 7
  • 19
Nav
  • 467
  • 4
  • 18
  • As far as I can say, you should recheck how you calculated the `centerPoint` because you should actually have four points to determine the centre (2 points to calculate the centre along x and 2 points to calculate the centre along y) right? What values did you get for `x` and `y`? – shyam Aug 25 '14 at 06:27
  • i used visibleregion method using this link http://stackoverflow.com/questions/13904505/how-to-get-center-of-map-for-v2-android-maps – Nav Aug 25 '14 at 06:46
  • Try printing out x.x and x.y. And on a side note why didn't you try the first answer to that question?(Seems more straight forward to me) – shyam Aug 25 '14 at 07:36
  • @shyam i tried using first method itself from cameraposition but there i got lat long 0.0 so tried visible region. And i tried to print points , i am getting points only as 0. – Nav Aug 25 '14 at 07:42

1 Answers1

7

You are probably trying to get the camera position when the map wasn't yet loaded. Instead wait for that with the OnMapLoadedCallback listener and get the center then:

mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
    @Override
    public void onMapLoaded() {
        Log.e("TAG", googleMap.getCameraPosition().target.toString());
    }
});
Simas
  • 43,548
  • 10
  • 88
  • 116