我在尝试根据给定的一组位置及其纬度和经度值下载不同缩放级别的 OSM 特定图块时遇到问题。
我要做的是确定左上/下角和右上角/右下角的 MapTile 编号,然后循环这些数字以下载图块。现在,我正在尝试在构造函数中下载高于给定缩放级别 1 和低于 1 的缩放级别。
public class MapDownload extends AsyncTask<String, Void, String>{
int zoom;
private ArrayList<GeoPoint> places;
private Coordinates topRight = new Coordinates(); // a java class I did for myself
private Coordinates bottomRight = new Coordinates();
private Coordinates topLeft = new Coordinates();
private Coordinates bottomLeft = new Coordinates();
public MapDownload(ArrayList<GeoPoint> placeList, int zoom){
this.places = placeList;
this.zoom = zoom;
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
for (int w = zoom -1 ; w <= zoom +1; w++){
double maxLat = 0.0;
double maxLon = 0.0;
double minLat = 0.0;
double minLon = 0.0;
for(GeoPoint point: places) {
double lon = (double) ( point.getLongitudeE6() / 1E6 * 1.0);
double lat = (double) (point.getLatitudeE6() / 1E6 * 1.0);
if(lat > maxLat) {
maxLat = lat;
}
if(lat < minLat || minLat == 0.0) {
minLat = lat;
}
if(lon> maxLon) {
maxLon = lon;
}
if(lon < minLon || lon == 0.0) {
minLon = lon;
}
}
topRight = topRight.gpsToMaptile(maxLon, maxLat, w); //top right
bottomRight = bottomRight.gpsToMaptile(maxLon, minLat, w); //bottom right
topLeft = topLeft.gpsToMaptile(minLon, maxLat, w); //top left
bottomLeft = bottomLeft.gpsToMaptile(minLon, minLat, w); //bottom left
for (int x = topLeft.getYTile(); x < bottomLeft.getYTile(); x++){
for(int y = topLeft.getXTile(); y < bottomRight.getXTile(); y++){
try {
String urlStr = "http://a.tile.openstreetmap.org/"+ w +"/"+y+"/"+x+".png";
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
File newFileDir = new File(Environment.getExternalStorageDirectory().toString()
+ "/downloadMap/test/"+w+"/"+y);
newFileDir.mkdirs();
File newFile = new File(newFileDir, x+".png");
OutputStream output = new FileOutputStream(newFile);
int read;
while ((read = in.read()) != -1) {
output.write(read);
output.flush();
}
urlConnection.disconnect();
} catch (Exception e) {
Log.e("URL::: ERROR", e.getMessage());
e.printStackTrace();
}
}
}
}
return null;
}
在我的 MainActivity 类中,这就是我调用此 AsyncTask 的方法:
public class MainActivity extends Activity implements LocationListener, MapViewConstants {
public void onCreate(Bundle savedInstanceState) {
MapDownload mapDownload = new MapDownload(placeList, 12);
mapDownload.execute("");
}
}
当我为 int x 和 int y (对于单个缩放层)进行循环时,一切都很好。然而,一旦我用 int w 放置第三个循环(循环不同的缩放级别),事情开始变得混乱,它开始将每个图块下载到手机中。
我已经单独测试了代码逻辑(通过打印 urlStr),它确实可以确定下载所需的特定 MapTiles。然而,相同的代码放在这个 AsyncTask 类中时不起作用,这让我相信这样的代码可能对 AsyncTask 的实现有问题。
希望有人能指出我的错误。谢谢!