Как правильно получить тайловый слой погоды?

Я пытаюсь сделать так, чтобы слой погоды с осадками отображался в моих действиях на Картах Google, но не могу понять, почему он не отображается на карте. Я реализовал свой ключ Google Maps в app\src\debug\res\values\google_maps_api.xml, установил службы Google Play в диспетчере Android SDK и настроил учетную запись с OpenWeatherMap для их API (которая приведена ниже).

Карта загружается нормально, и когда я ищу слой в отдельном браузере с введенным масштабированием, x, y, он отображается нормально, но я не могу заставить слой отображаться в моей активности на Картах Google.

Нужно ли мне определять x, y, масштабирование или они взяты из URL-адреса?

Вот моя джава:

package com.example.user.project;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.TileOverlay;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import com.google.android.gms.maps.model.UrlTileProvider;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Locale;

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);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Move the camera
        LatLng indy = new LatLng(39, -86.5);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(indy, 8));

        TileProvider tileProvider = new UrlTileProvider(256, 256) {
            @Override
            public URL getTileUrl(int x, int y, int zoom) {

    /* Define the URL pattern for the tile images */
                String s = String.format(Locale.US, "http://tile.openweathermap.org/map/precipitation/%d/%d/%d.png?appid={my_key}",
                        zoom, x, y);

                if (!checkTileExists(x, y, zoom)) {
                    return null;
                }

                try {
                    return new URL(s);
                } catch (MalformedURLException e) {
                    throw new AssertionError(e);
                }
            }

            /*
             * Check that the tile server supports the requested x, y and zoom.
             * Complete this stub according to the tile range you support.
             * If you support a limited range of tiles at different zoom levels, then you
             * need to define the supported x, y range at each zoom level.
             */
            private boolean checkTileExists(int x, int y, int zoom) {
                int minZoom = 12;
                int maxZoom = 16;

                return !(zoom < minZoom || zoom > maxZoom);

            }
        };

        TileOverlay tileOverlay = mMap.addTileOverlay(new TileOverlayOptions()
                .tileProvider(tileProvider));
    }
}

Вот сгенерированный Android Studio макет:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:map="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/map"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context="com.example.user.project.MapsActivity"/>

Я следил за учебными пособиями и документацией, предлагаемыми OpenWeatherMap, API Карт Google и разработчиками Android, но не понимаю, почему это не работает.

Что мне не хватает?


person braj    schedule 05.04.2017    source источник


Ответы (1)


Вы устанавливаете уровень 8 в качестве уровня масштабирования для своей карты, но вы также ограничиваете уровни масштабирования от 12 до 16, чтобы ваш TileProvider был виден.

Удали это:

if (!checkTileExists(x, y, zoom)) {
    return null;
}

Если вам не нужны какие-либо ограничения масштаба, вы также можете удалить метод checkTileExists.

person antonio    schedule 05.04.2017
comment
Да! Большое спасибо, это сработало. Я неправильно понял, что камера влияет на это. - person braj; 05.04.2017