How do I restrict Google Maps API to a specific area when its latitude and longitude bound is given?

柔情痞子 提交于 2021-02-11 15:33:06

问题


I only want to display a google map of a specific area on the mobile screen. The map should not move beyond that area when there is user interaction such as zoom or moving the map.

For example: These are latitude and longitude bound:

LatLng one = new LatLng(42.0140555,-88.2131937);
LatLng two = new LatLng(40.993729,-87.6622417); 

回答1:


I have found the solution this way. Do this on onMapReady() function.

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

    //get latlong for corners for a specified area of map

    LatLng one = new LatLng(42.0140555,-88.2131937);
    LatLng two = new LatLng(40.993729,-87.6622417); 

    LatLngBounds.Builder builder = new LatLngBounds.Builder();

    //add them to builder
    builder.include(one);
    builder.include(two);

    LatLngBounds bounds = builder.build();

    //get width and height to current display screen
    int width = getResources().getDisplayMetrics().widthPixels;
    int height = getResources().getDisplayMetrics().heightPixels;

    // 20% padding
    int padding = (int) (width * 0.20);

    //set latlong bounds
    mMap.setLatLngBoundsForCameraTarget(bounds);

    //move camera to fill the bound to screen
    mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));

    //set zoom to level to current so that you won't be able to zoom out viz. move outside bounds
    mMap.setMinZoomPreference(mMap.getCameraPosition().zoom);
}


来源:https://stackoverflow.com/questions/59576306/how-do-i-restrict-google-maps-api-to-a-specific-area-when-its-latitude-and-longi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!