使用Java从GeoJSON坐标中提取纬度和经度值分别转换为所需格式

时间:2019-10-12 23:51:36

标签: java regex geojson

我正在尝试将GeoJSON坐标拆分为单独的纬度和经度值,以形成所需的格式(如所需的输出所示)。

我有一个GeoJSON文件,通过该文件我仅提取坐标值。这些坐标值存储为String变量,如下所示: GeoJSON : ":[[[7.365046,46.948655],[7.365046,46.949254],[7.367558,46.949254],[7.367558,46.948655],[7.365046,46.948655]]]}}。 如何从给定的String中分别提取纬度和经度的特定值。从GeoJSON文件提取坐标的代码段如下所示:


String GeoJSON = GeoJSONFromFile().split("coordinates")[1];
System.out.println("GeoJSON : " + GeoJSON );

//Splitting within the brackets
String delims = "\\[(.*?)\\]";
String[] tokens = GeoJSON.split(delims);

GeoJSON = GeoJSON.split("}")[0];

我想要实现的预期输出如下:

\"points\": [\n" +
"            {\n" +
"              \"@type\": \"Point\",\n" +
"              \"lat\": 46.948655,\n" +
"              \"lon\": 7.365046\n" +
"            },\n" +
"            {\n" +
"              \"@type\": \"Point\",\n" +
"              \"lat\": 46.949254,\n" +
"              \"lon\": 7.365046\n" +
"            },\n" +
"            {\n" +
"              \"@type\": \"Point\",\n" +
"              \"lat\": 46.949254,\n" +
"              \"lon\": 7.367558\n" +
"            },\n" +
"            {\n" +
"              \"@type\": \"Point\",\n" +
"              \"lat\": 46.948655,\n" +
"              \"lon\": 7.367558\n" +
"            },\n" +
"            {\n" +
"              \"@type\": \"Point\",\n" +
"              \"lat\": 46.948655,\n" +
"              \"lon\": 7.365046\n" +
"            }\n" 
"          ]

最终结果应单独包含上述格式所示的坐标。

1 个答案:

答案 0 :(得分:3)

我猜这类似于:

(?::\[\[)?\[([-+]?\d+\.\d+)\s*,\s*([-+]?\d+\.\d+)\]\s*,?(?:\]\]}})?

使用适当的替换项,将$1$2用作latlon,例如:

{\n"@type": "point",\n"lat":"$1",\n"lon":"$2"\n},\n

在某种程度上可能会起作用,但不能完全发挥作用。

Demo

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){

        final String regex = "(?::\\[\\[)?\\[([-+]?\\d+\\.\\d+)\\s*,\\s*([-+]?\\d+\\.\\d+)\\]\\s*,?(?:\\]\\]\\}})?";
        final String string = ":[[[7.365046,46.948655],[7.365046,46.949254],[7.367558,46.949254],[7.367558,46.948655],[7.365046,46.948655]]]}}";
        final String subst = "{\"@type\": \"point\",\"lat\":\"$1\",\"lon\":\"$2\"},";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        final String result = matcher.replaceAll(subst);

        System.out.println(result);

    }
}

输出

  

{“ @ type”:“ point”,“ lat”:“ 7.365046”,“ lon”:“ 46.948655”},{“ @ type”:   “ point”,“ lat”:“ 7.365046”,“ lon”:“ 46.949254”},{“ @ type”:   “ point”,“ lat”:“ 7.367558”,“ lon”:“ 46.949254”},{“ @ type”:   “ point”,“ lat”:“ 7.367558”,“ lon”:“ 46.948655”},{“ @ type”:   “ point”,“ lat”:“ 7.365046”,“ lon”:“ 46.948655”},

RegEx电路

jex.im可视化正则表达式:

enter image description here