如何从谷歌地图v2 android中的标记获取屏幕坐标

man*_*che 30 android google-maps google-maps-markers

我有一个小的android问题(google maps v2 api)

这是我的代码:

GoogleMaps mMap;
Marker marker =  mMap.addMarker(new MarkerOptions().position(new LatLng(20, 20)));
Run Code Online (Sandbox Code Playgroud)

我试图找到一种方法来获取此标记对象的当前屏幕坐标(x,y).

也许有人有想法?我尝试了getProjection,但它看起来没有用.谢谢!:)

and*_*ndr 80

是的,使用Projection课程.进一步来说:

  1. 获取Projection地图:

    Projection projection = map.getProjection();
    
    Run Code Online (Sandbox Code Playgroud)
  2. 获取标记的位置:

    LatLng markerLocation = marker.getPosition();
    
    Run Code Online (Sandbox Code Playgroud)
  3. 将位置传递给Projection.toScreenLocation()方法:

    Point screenPosition = projection.toScreenLocation(markerLocation);
    
    Run Code Online (Sandbox Code Playgroud)

就这样.现在screenPosition将包含标记相对于整个Map容器​​左上角的位置:)

编辑

请记住,Projection对象只会在地图通过布局过程后返回有效值(即它有效widthheight设置).你可能会得到,(0, 0)因为你试图过早地访问标记的位置,就像在这种情况下:

  1. 通过对布局XML文件进行膨胀来创建映射
  2. 初始化地图.
  3. 将标记添加到地图中.
  4. 查询Projection屏幕上标记位置的地图.

这不是一个好主意,因为地图没有设置有效的宽度和高度.您应该等到这些值有效.其中一个解决方案是将a附加OnGlobalLayoutListener到地图视图并等待布局过程结算.在对布局进行充气并初始化地图之后执行此操作 - 例如onCreate():

// map is the GoogleMap object
// marker is Marker object
// ! here, map.getProjection().toScreenLocation(marker.getPosition()) will return (0, 0)
// R.id.map is the ID of the MapFragment in the layout XML file
View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
if (mapView.getViewTreeObserver().isAlive()) {
    mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            // remove the listener
            // ! before Jelly Bean:
            mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            // ! for Jelly Bean and later:
            //mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            // set map viewport
            // CENTER is LatLng object with the center of the map
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(CENTER, 15));
            // ! you can query Projection object here
            Point markerScreenPosition = map.getProjection().toScreenLocation(marker.getPosition());
            // ! example output in my test code: (356, 483)
            System.out.println(markerScreenPosition);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

请阅读评论以获取更多信息.