Google地图中未加载第三方图块

时间:2018-05-20 18:17:03

标签: java android google-maps openstreetmap

我开发使用Google Map API的简单Android应用程序,其中一部分功能可以动态更改地图(平铺)提供程序(例如,在Google Map和Open Street Map拼贴之间更改平铺)。我正在尝试使用Google Map TileProvider,而是OSM tile我没有看到任何东西(比如tile不加载)。如果选择提供商是谷歌一切正常。

下一段代码说明了它的实现方式:

    mapView = (MapView) rootView.findViewById(R.id.map);
    mapView.onCreate(savedInstanceState);


    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        logger.error("Error occurs while map initializing");
    }

    mapView.onResume(); 

    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
           mMap = googleMap;
           if (MapProvider.valueOf(LocalPreferenceManager.getMapProvider(getContext())) != MapProvider.Google) {

                final String osmUrl = "http://a.tile.openstreetmap.org/%d/%d/%d.png";
                TileProvider tileProvider = new UrlTileProvider(256,256) {

                    @Override
                    public URL getTileUrl(int x, int y, int zoom) {
                        URL url = null;
                        try {
                            String s = String.format(osmUrl,zoom, x, y);
                            url = new URL(s);
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }
                        return url;
                    }
                };
                mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
                mMap.addTileOverlay(new TileOverlayOptions().
                        tileProvider(tileProvider));
            }
            //some action...
        }
    });

我很感激任何帮助。

2 个答案:

答案 0 :(得分:1)

似乎 OSM 磁贴服务器需要非空的“User-Agent”标头,否则会失败并显示 HTTP 代码 403。

我没有找到通过 getTileUrl 中的 URL 设置用户代理的方法,并且不得不使用这样的代码实现我自己的 TileProvider

URL url = getTileUrl(x, y, z);
if (url != null) {
   URLConnection conn = url.openConnection();
   conn.setRequestProperty("User-Agent", "any string?");
   ..........
}

答案 1 :(得分:0)

" http://a.tile.openstreetmap.org/%d/%d/%d.png"几天前不再有效。试试" https://a.tile.openstreetmap.org/%d/%d/%d.png"。

虽然事情确实会自动重定向,但并不是每个客户都会这样做。