如何获取谷歌地图的屏幕中心位置?

Posted

技术标签:

【中文标题】如何获取谷歌地图的屏幕中心位置?【英文标题】:How to get screen center location of google map? 【发布时间】:2015-10-17 06:55:19 【问题描述】:

我想创建一个带有静态标记的地图,以始终显示屏幕中心的位置。我在布局中创建了一个标记,中心是可绘制的图像。 现在我需要获取中心位置坐标并将它们转换为地址。之后在文本视图中显示所选位置作为我选择的位置。 需要帮助

【问题讨论】:

【参考方案1】:

您可以随时通过在您的 GoogleMap 变量实例上调用此函数来获取地图的中心点

mMap.getCameraPosition().target 

现在如果您想在每次更改地图时获取中心点,那么您需要实现OnCameraChangeListener 监听器并调用上面的行来获取新的中心点。

更新: OnCameraChangeListener 已替换为 OnCameraMoveStartedListenerOnCameraMoveListenerOnCameraIdleListener 听众。使用适合您用例的那个。

【讨论】:

你能提供一些例子吗? 它工作得非常好,而且它的代码也比公认的答案更干净 @MANCHAI 如:double CameraLat = mMap.getCameraPosition().target.latitude; double CameraLong = mMap.getCameraPosition().target.longitude; 是的,这应该是公认的答案。如果一个人用 30 行代码给出了答案,而另一个人只用了一行代码给出了答案(没有明显的实现缺点),那么这一行应该始终是公认的答案。【参考方案2】:
protected void userLocationMap() 

        mapFragment = ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map));
        googleMap = mapFragment.getMap();
        int status = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getBaseContext());

        if (status != ConnectionResult.SUCCESS)  
///if play services are not available
            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
                    requestCode);
            dialog.show();

         else 

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);

            // Creating a LatLng object for the current location
            LatLng latLng = new LatLng(latitude, longitude);
            // Showing the current location in Google Map
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            // Zoom in the Google Map
            googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
            Log.i("latitude", "==========" + latitude);
////locationTextView holds the address string
            locationTextView.setText(getCompleteAdressString(latitude, longitude));

            // create marker
            MarkerOptions marker = new MarkerOptions().position(
                    new LatLng(latitude, longitude)).title("My Location");
            // adding marker
            googleMap.addMarker(marker);
        
    

getcompleteAdress 方法是:::::==>

private String getCompleteAddressString(double LATITUDE, double LONGITUDE) 

        String strAdd = "";

        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try 
            List<Address> addresses = geocoder.getFromLocation(LATITUDE,
                    LONGITUDE, 1);

            if (addresses != null) 

                Address returnedAddress = addresses.get(0);

                StringBuilder strReturnedAddress = new StringBuilder("");

                for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) 

                    strReturnedAddress
                            .append(returnedAddress.getAddressLine(i)).append(
                                    ",");
                

                strAdd = strReturnedAddress.toString();

                Log.w("My Current loction address",
                        "" + strReturnedAddress.toString());
             else 
                Log.w("My Current loction address", "No Address returned!");
            
         catch (Exception e) 
            e.printStackTrace();
            Log.w("My Current loction address", "Canont get Address!");
        
        return strAdd;
    

根据点击改变位置====>

 googleMap.setOnMapClickListener(new OnMapClickListener() 

            @Override
            public void onMapClick(LatLng point) 
                Log.d("Map","Map clicked");
                marker.remove();
                double latitude = latLng.latitude;
                double longitude = latLng.longitude;
locationTextView.setText(getCompleteAdressString(latitude,longitude ));
                drawMarker(point);
            
        );

【讨论】:

如果您对我们的回答不满意,请告诉我们 我已编辑我的答案以将您的问题包含在 cmets 中。但问题不是很清楚。如果您不满意,请告诉我们【参考方案3】:

这将提供中心屏幕的纬度和纬度

LatLng centerLatLang = 
mMap.getProjection().getVisibleRegion().latLngBounds.getCenter();

【讨论】:

【参考方案4】:

我已经成功地为我当前的位置创建了地图。但它只提供一次我的位置坐标,我需要在移动到其他位置时获取位置。发布我的代码

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Canvas;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class MapLocation extends FragmentActivity implements LocationListener 

    GoogleMap googleMap;
    MarkerOptions markerOptions;
    LatLng latLng;

    ImageView icon;
    TextView selected;

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

        icon = (ImageView)findViewById(R.id.icon_baby);
        icon.setOnClickListener(new OnClickListener() 

            @Override
            public void onClick(View v) 
                // TODO Auto-generated method stub
                finish();

            
        );


     // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS) // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        else  // Google Play Services are available

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);

            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null)
                onLocationChanged(location);
            
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        
    
    //@Override
    public void onLocationChanged(Location location) 

        TextView tvLocation = (TextView) findViewById(R.id.selected_location);

        // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Showing the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

        // Setting latitude and longitude in the TextView tv_location
        tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );
    
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) 
        // TODO Auto-generated method stub

    
    @Override
    public void onProviderEnabled(String provider) 
        // TODO Auto-generated method stub

    
    @Override
    public void onProviderDisabled(String provider) 
        // TODO Auto-generated method stub

    
    

【讨论】:

以上是关于如何获取谷歌地图的屏幕中心位置?的主要内容,如果未能解决你的问题,请参考以下文章

如何在谷歌地图上获取图像视图坐标(位置/纬度)

如何在谷歌地图的指定位置获取标记(或图钉)?

Yandex MapKit 3.0。获取屏幕和缩放的中心,在地图上获取位置

如何在谷歌地图中获取标记和中心之间的距离

如何使用 Google Maps JavaScript API v3 在谷歌地图中获取查看区域中心的坐标

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