Add static square grids using google map api in an

2019-08-07 01:12发布

问题:

In my project, I need to define areas in google map. So, I thought of dividing google map in static square grids in android using google-maps-API. I am new to google-maps-API so any help would be great.

回答1:

The similar question was asked before and @MaciejGórski provided a nice solution:

https://stackoverflow.com/a/16359857/5140781

There are several notes I can add because the aforementioned answer is quite old and links are not valid anymore. They refer to the project in Google code that was deprecated a couple of years ago. I searched and figured out that the project moved from Google code to GitHub:

https://github.com/mg6maciej/android-maps-extensions

So you can follow instructions of @MaciejGórski and copy files DebugHelper.java and SphericalMercator.java from the following URLs

https://github.com/mg6maciej/android-maps-extensions/blob/develop/android-maps-extensions/src/main/java/com/androidmapsextensions/impl/DebugHelper.java

https://github.com/mg6maciej/android-maps-extensions/blob/develop/android-maps-extensions/src/main/java/com/androidmapsextensions/utils/SphericalMercator.java

Also note that onCameraChange in Google Maps Android API was deprecated, so you have to use onCameraIdle instead.

I created a sample project and was able to create a grid

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnCameraIdleListener {

    private GoogleMap mMap;
    private DebugHelper hlp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        LatLng center = new LatLng(41.385064,2.173403);

        mMap.getUiSettings().setZoomControlsEnabled(true);

        hlp =  new DebugHelper();
        mMap.setOnCameraIdleListener(this);

        mMap.moveCamera(CameraUpdateFactory.newLatLng(center));
    }

    @Override
    public void onCameraIdle() {
        Projection projection = mMap.getProjection();
        double l1 = projection.getVisibleRegion().farLeft.longitude;
        double l2 = projection.getVisibleRegion().farRight.longitude;

        double grdSize = Math.abs(l2-l1) / 8.0;

        hlp.drawDebugGrid(mMap, grdSize);
    }
}

You can find a complete sample project on GitHub

https://github.com/xomena-so/so48834248

Please replace my API key with yours in google_maps_api.xml.

I hope this helps!