![](/img/trans.png)
[英]Need to read from a txt file in the assets folder in android studio
[英]How to read a txt file in android studio?
我在 android studio 的資產文件夾中有一個文本文件 speedVan.txt,它存儲坐標,但是當我運行它時,標記不會出現在地圖上。 我的代碼在下面,謝謝。
這是文本文件的內容,文本行之間沒有空格:
52.2651 -9.7112 52.2791 -9.7024
52.2800 -9.7675 52.2746 -9.8096
52.1407 -10.1748 52.1296 -10.2493
52.0724 -9.5753 52.1005 -9.6231
52.1021 -9.6276 52.1065 -9.6425
52.0812 -9.2470 52.0542 -9.3850
52.1134 -9.5169 52.1437 -9.5543
52.4096 -9.5167 52.4208 -9.5078
52.4428 -9.4105 52.4491 -9.4474
這是我的活動:
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);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("speedVan.txt")));
String line;
//Log.e("Reader Stuff",reader.readLine());
while ((line = reader.readLine()) != null) {
Log.e("code",line);
String[] ar1 = line.split(" ");
double startLat = Double.parseDouble(ar1[0]);
double startLong = Double.parseDouble(ar1[1]);
double endLat = Double.parseDouble(ar1[2]);
double endLong = Double.parseDouble(ar1[3]);
LatLng start = new LatLng(startLat, startLong);
LatLng end = new LatLng(endLat, endLong);
mMap.addMarker(new MarkerOptions().position(start).title(""));
mMap.addMarker(new MarkerOptions().position(end).title(""));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(start,14));
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
將 SupportMapFragment 更改為 MapFragment。 像這樣的東西
MapFragment mapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map);
請刪除;;
你已經用過並放了一個;
而不是:
int startLat = Integer.parseInt(ar1[0]);
int startLong = Integer.parseInt(ar1[1]);;
int endLat = Integer.parseInt(ar1[2]);;
int endLong = Integer.parseInt(ar1[3]);;
請放:
double startLat = Double.parseDouble(ar1[0]);
double startLong = Double.parseDouble(ar1[1]);
double endLat = Double.parseDouble(ar1[2]);
double endLong = Double.parseDouble(ar1[3]);
我們使用 double 是因為LatLng
的構造函數需要兩個double
參數。
請注意,因為您的第一條語句Log.e("Reader Stuff",reader.readLine());
文本文件的第一行不會被解析,因為正在讀取和記錄一行,下次調用reader.readLine()
,您將獲得第二行。
編輯:
也許您看不到標記是因為您沒有移動地圖相機。 將相機移動到任何標記處:
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(start,14));
start
是LatLng
, 14
是縮放級別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.