Highlight whole countries in Google Maps for Android

随声附和 提交于 2019-11-27 23:22:08
xomena

The question about country or other features borders in Google Maps APIs was asked many times, however, unfortunately Google doesn't expose this data publicly.

To highlight the country you should apply your own data as the Google Maps layer. Nice work around was proposed in the following answer

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

You can download country borders in GeoJSON format from OSM. After that you can use the Google Maps Android API Utility Library to add GeoJsonLayer in your application.

For my example I downloaded the boundaries of Spain in GeoJSON format and loaded the GeoJSON file using GeoJsonLayer.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @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;

        mMap.getUiSettings().setZoomControlsEnabled(true);

        LatLng madrid = new LatLng(40.416775,-3.70379);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(madrid, 3F));

        try {
            GeoJsonLayer layer = new GeoJsonLayer(mMap, R.raw.es_geojson, getApplicationContext());

            GeoJsonPolygonStyle style = layer.getDefaultPolygonStyle();
            style.setFillColor(Color.MAGENTA);
            style.setStrokeColor(Color.MAGENTA);
            style.setStrokeWidth(1F);

            layer.addLayerToMap();

        } catch (IOException ex) {
            Log.e("IOException", ex.getLocalizedMessage());
        } catch (JSONException ex) {
            Log.e("JSONException", ex.getLocalizedMessage());
        }
    }
}

You can download the complete sample project from github, don't forget to change the API key in values/google_maps_api.xml

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

I hope this helps!

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