はい、Projection
クラスを使用します。すなわち:
Projection
地図を入手する:
Projection projection = map.getProjection();
マーカーの場所を取得します。
LatLng markerLocation = marker.getPosition();
Projection.toScreenLocation()
メソッドに場所を渡します。
Point screenPosition = projection.toScreenLocation(markerLocation);
それで全部です。screenPosition
これで、マップコンテナ全体の左上隅を基準にしたマーカーの位置が含まれます:)
編集
オブジェクトは、マップがレイアウトプロセスを通過した後(つまり、有効で設定された後)Projection
にのみ有効な値を返すことに注意してください。このシナリオのように、マーカーの位置にすぐにアクセスしようとしているため、おそらく取得しています。width
height
(0, 0)
- レイアウトXMLファイルを膨らませてマップを作成します
- マップを初期化します。
- マップにマーカーを追加します。
Projection
画面上のマーカー位置のマップのクエリ。
マップには有効な幅と高さが設定されていないため、これはお勧めできません。これらの値が有効になるまで待つ必要があります。解決策の1つは、マップビューにをアタッチし、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);
}
});
}
追加情報については、コメントをお読みください。