簡體   English   中英

Java將位置坐標轉換為long和lat的double

[英]Java convert location coordinates into double for long and lat

我一直在android studio上制作一個移動android應用程序,並且在數據庫中保存了位置。 我需要將這些經度和緯度轉換為雙精度,以便可以在Google地圖片段中使用。

目前,它正在從數據庫中獲取字符串,如下所示:

  Cursor res = dbHelper3.getEvent(journey, message);
    if (res.getCount() == 0) {
        showMessageData("Error", "No data");
        return;
    }
    StringBuffer buffer = new StringBuffer();
    while (res.moveToNext()) {
        buffer.append(res.getString(1));

    }

但由於將long和lat都保存為一個大字符串,因此將其轉換為double存在一個問題。 例如它將打印:

“ 52.301293 0.185935”

當我嘗試這個

 String location = buffer.toString();
    locationText.setText(buffer.toString().trim());
    float f = Float.parseFloat(location);

它給出了一個錯誤:

不能將其轉換為雙精度數,因為它有兩個單獨的數字嗎?是否有辦法將它們分成兩個雙精度數,還是我必須重新設計數據庫獲取位置的方式?

您需要像這樣分別保存緯度和經度信息:

String location = "52.301293 0.185935";

String[] afterSplitLoc = location.split(" ");

之后,將它們轉換為Double:

double latitude = Double.parseDouble(afterSplitLoc[0]);

double longitude = Double.parseDouble(afterSplitLoc[1]);

並且比在地圖上使用。 例如添加一個標記:

   private GoogleMap googleMap((MapView)rootView.findViewById(R.id.YOURMAPID)).getMap();

   googleMap.addMarker(new MarkerOptions().position(new LatLng( latitude, -longitude)).title("Marker"));

您正在嘗試將包含空格的字符串轉換為double,這最終將使應用程序崩潰。 您需要按空格將字符串“位置”分成兩個字符串,如下所示:

String[] splited = location.split("\\s+");

然后,您可以將其隱藏為以下內容的兩倍

double latitude = Double.parseDouble(splited[0]);

double longitude = Double.parseDouble(splited[1]);

只需使用以下內容:

String location = buffer.toString().trim();
String[] latLon = location.split(" ");
double lat = Double.parseDouble(latLon[0]);
double lon = Double.parseDouble(latLon[1]);

謝謝kshetline,

工作完美

 String string = buffer.toString();
    String[] parts = string.split(" ");
    String part1 = parts[0]; // 004
    String part2 = parts[1]; // 034556

    locationText.setText(part1 + "\n" + part2);

    float longNum = Float.parseFloat(part1);
    float latNum = Float.parseFloat(part2);

    locationText.setText(longNum + "\n" + latNum);

    final LatLng eventLocation1 = new LatLng(longNum, latNum);

IMO,除非有特殊原因,否則應將緯度和經度保存在單獨的列中,因為這將使以后的更新操作更容易。


您可以使用split()方法來分隔兩個值:

String location = "52.301293 0.185935"; 
String[] latlng = location.split(" ");
System.out.println("Lat = " +latlng[0]+" Longitude = "+latlng[1]);
//You will get sth like "Lat = 52.301293 Longitude = 0.185935"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM