我一直在尝试使用 openmap 库显示 shapefile。单击第一个活动上的按钮时,应用程序转到第二个活动(也是第二个页面),但随后突然崩溃。
我运行调试器并意识到 mapFragment 变量仍然为空,它正在从 findFragmentById 获取值。我最终打算在我的应用程序的第二页上显示一个 shapefile。
public class ShapeFileParser extends AppCompatActivity implements OnMapReadyCallback {
GoogleMap mMap;
ShapeFile shapeFile;
File file;
public void setUpMap() {
try {
org.apache.commons.io.FileUtils.copyInputStreamToFile((ShapeFileParser.this.getAssets().open("healthsites.shp")), file);
} catch (IOException e) {
e.printStackTrace();
}
try {
shapeFile = new ShapeFile(file);
} catch (IOException e) {
e.printStackTrace();
}
try {
for (ESRIRecord esriRecord = shapeFile.getNextRecord(); esriRecord!=null; esriRecord = shapeFile.getNextRecord()){
String shapeTypeStr = ShapeUtils.getStringForType(esriRecord.getShapeType());
Log.v("myapp","shape type = " + esriRecord.getRecordNumber() + "-" + shapeTypeStr);
if (shapeTypeStr.equals("POLYGON")) {
// cast type after checking the type
ESRIPolygonRecord polyRec = (ESRIPolygonRecord)esriRecord;
Log.v("myapp","number of polygon objects = " + polyRec.polygons.length);
for (int i=0; i<polyRec.polygons.length; i++){
// read for a few layers
ESRIPoly.ESRIFloatPoly poly = (ESRIPoly.ESRIFloatPoly)polyRec.polygons[i];
PolygonOptions polygonOptions = new PolygonOptions();
polygonOptions.strokeColor(Color.argb(150,200,0,0));
polygonOptions.fillColor(Color.argb(150,0,0,150));
polygonOptions.strokeWidth(2.0f);
Log.v("myapp","Points in the polygon = " + poly.nPoints);
for (int j=0; j<poly.nPoints; j++){
//Log.v("myapp",poly.getY(j) + "," + poly.getX(j));
polygonOptions.add(new LatLng(poly.getY(j), poly.getX(j)));
}
mMap.addPolygon(polygonOptions);
Log.v("myapp","polygon added");
}
}
else {
Log.v("myapp","error polygon not found (type = " + esriRecord.getShapeType() + ")");
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeMap();
}
private void initializeMap() {
if (mMap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// mapFrag is null on checking with the debugger
mapFrag.getMapAsync(this);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
}
}
这是我的 XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ShapeFileParser" >
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
我只是在尝试一个将形状文件呈现到第二页的示例,但我觉得自过去两天以来我无处可去。如果有的话,请提出一些意见。
我是android dev的新手,请耐心等待。非常感谢!