В одном из моих приложений android я хочу отобразить ссылку WMS с помощью карты Google, для которой я перешел по этой ссылке Ссылка
Но я не могу отобразить свою ссылку WMS.I Не знаю, где я делаю что-то не так. Я также перешел по другим ссылкам Ссылка2 , чтобы разобраться, но ни одна из них мне не помогла. Кто-нибудь может мне помочь?
Ниже приведен код, который я использовал для этого.
Класс MapActivity
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
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.TileOverlay;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends FragmentActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private GoogleMap map;
// list of all permissions required
String[] appPermissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
private static final int PERMISSION_REQUEST_CODE = 101;
/* GOAL:
* Display a WMS overlay from OSGEO on top of a google base map.
* (The data is a white map with state boundaries.)
*
* Create a debugging Maps API Key and add it to the manifest.
*new LatLng(39.0119, -98.4842);//
*/
private LatLng KS = new LatLng(23.903320, 79.968758);
//private LatLng KS = new LatLng(39.0119, -98.4842);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkAndRequestPermissions();
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
map =googleMap;
TileProvider wmsTileProvider = TileProviderFactory.getOsgeoWmsTileProvider();
googleMap.addTileOverlay(new TileOverlayOptions().tileProvider(wmsTileProvider)).setZIndex(0);
//googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(KS, 4));
}
});
}
private void setUpMap() {
// TODO Auto-generated method stub
map.setMyLocationEnabled(true);
TileProvider geoServerTileProvider = TileProviders
.getGeoServerTileProvider();
map.addTileOverlay(
new TileOverlayOptions()
.tileProvider(geoServerTileProvider)
.zIndex(10000)
.visible(true));
}
/*method for checking and giving run time permissions*/
private boolean checkAndRequestPermissions() {
// check which permissions are not granted
List<String> listPermissionsNeeded = new ArrayList<>();
for (String perm : appPermissions) {
if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(perm);
}
}
// ask for non granted permissions
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), PERMISSION_REQUEST_CODE);
return false;
}
// App has all permissions
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
HashMap<String, Integer> permissionResults = new HashMap<>();
int deniedCount = 0;
// gather permission grant results
for (int i = 0; i < grantResults.length; i++) {
// add only permissions which are denied
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
permissionResults.put(permissions[i], grantResults[i]);
deniedCount++;
}
}
// check if all permissions are granted
if (deniedCount == 0) {
} else {
for (Map.Entry<String, Integer> entry : permissionResults.entrySet()) {
String perName = entry.getKey();
int permResult = entry.getValue();
// permission is denied (this is the first time, when "never ask again" is not checked)
// so ask again explaining the usage of permission
// shouldShowRequestPermissionRationale will return true
if (ActivityCompat.shouldShowRequestPermissionRationale(this, perName)) {
// show Dialog of explanation
showDialog("", "This app needs Location permissions to work without problems.", "Yes, Grant permissions", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
checkAndRequestPermissions();
}
}, "No, Exit app", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}, false);
}
// permission is denied and (never ask again is checked)
// shouldShowRequestPermissionRationale will return false
else {
// Ask user to go to settings and manually allow permissions
showDialog("", "You have denied some permissions. Allow all permissions at [Settings] > [Permissions", "Go to Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", getPackageName(), null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
// finish();
}
}, "No, Exit app", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}, false);
break;
}
}
}
}
}
/*method for showing permission dialog*/
private AlertDialog showDialog(String title, String msg, String positiveLabel, DialogInterface.OnClickListener posotiveOnClick,
String negativeLabel, DialogInterface.OnClickListener negativeOnClick, boolean isCancelable) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setCancelable(isCancelable);
builder.setPositiveButton(positiveLabel, posotiveOnClick);
builder.setNegativeButton(negativeLabel, negativeOnClick);
AlertDialog alertDialog = builder.create();
alertDialog.show();
return alertDialog;
}
}
Класс WMSTileProvider
import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import com.google.android.gms.maps.model.UrlTileProvider;
public abstract class WMSTileProvider extends UrlTileProvider {
// Web Mercator n/w corner of the map.
private static final double[] TILE_ORIGIN = {-20037508.34789244, 20037508.34789244};
//array indexes for that data
private static final int ORIG_X = 0;
private static final int ORIG_Y = 1; // "
// Size of square world map in meters, using WebMerc projection.
private static final double MAP_SIZE = 20037508.34789244 * 2;
// array indexes for array to hold bounding boxes.
protected static final int MINX = 0;
protected static final int MAXX = 1;
protected static final int MINY = 2;
protected static final int MAXY = 3;
// cql filters
private String cqlString = "";
// Construct with tile size in pixels, normally 256, see parent class.
public WMSTileProvider(int x, int y) {
super(x, y);
}
@SuppressWarnings("deprecation")
protected String getCql() {
try {
return URLEncoder.encode(cqlString, Charset.defaultCharset().name());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return URLEncoder.encode(cqlString);
}
}
public void setCql(String c) {
cqlString = c;
}
// Return a web Mercator bounding box given tile x/y indexes and a zoom
// level.
protected double[] getBoundingBox(int x, int y, int zoom) {
Log.v("X",""+x);
Log.v("Y",""+y);
Log.v("zoom",""+zoom);
double tileSize = MAP_SIZE / Math.pow(2, zoom);
double minx = TILE_ORIGIN[ORIG_X] + x * tileSize;
double maxx = TILE_ORIGIN[ORIG_X] + (x + 1) * tileSize;
double miny = TILE_ORIGIN[ORIG_Y] - (y + 1) * tileSize;
double maxy = TILE_ORIGIN[ORIG_Y] - y * tileSize;
double[] bbox = new double[4];
bbox[MINX] = minx;
bbox[MINY] = miny;
bbox[MAXX] = maxx;
bbox[MAXY] = maxy;
return bbox;
}
}
TileProviderFactory class
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Locale;
import android.util.Log;
public class TileProviderFactory {
public static WMSTileProvider getOsgeoWmsTileProvider() {
//This is configured for:
// http://beta.sedac.ciesin.columbia.edu/maps/services
// (TODO check that this WMS service still exists at the time you try to run this demo,
// if it doesn't, find another one that supports EPSG:900913
final String url =http://myserver.com/geoserver/app/wms +
"?service=WMS" +
"&version=1.1.1" +
"&request=GetMap" +
"&layers=Mylayer:basemap" +
"&bbox=%f,%f,%f,%f" +
"&width=256" +
"&height=256" +
"&srs=EPSG:32644" +
"&format=image/png" +
"&transparent=true";
WMSTileProvider tileProvider = new WMSTileProvider(256,256) {
@Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
Log.v("String zoom",""+zoom);
double[] bbox = getBoundingBox(x, y, zoom);
String s = String.format(Locale.US, url, bbox[MINX],
bbox[MINY], bbox[MAXX], bbox[MAXY]);
Log.d("WMSDEMO", s);
URL url = null;
try {
url = new URL(s);
Log.d("url", ""+url);
} catch (MalformedURLException e) {
Log.v("Exception","Hello");
e.printStackTrace();
throw new AssertionError(e);
}
return url;
}
};
return tileProvider;
}
/*
* 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 static boolean checkTileExists(int x, int y, int zoom) {
int minZoom = 12;
int maxZoom = 16;
if ((zoom < minZoom || zoom > maxZoom)) {
return false;
}
return true;
}
}