summaryrefslogtreecommitdiff
path: root/platform/android/MapboxGLAndroidSDKTestApp/src/main/java/com/mapbox/mapboxsdk/testapp/utils/GeoParseUtil.java
blob: cace2083da9e4943bac4018d6c96991cd49cf66c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.mapbox.mapboxsdk.testapp.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;

import com.mapbox.geojson.Feature;
import com.mapbox.geojson.FeatureCollection;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.geometry.LatLng;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class GeoParseUtil {

  public static String loadStringFromAssets(final Context context, final String fileName) throws IOException {
    if (TextUtils.isEmpty(fileName)) {
      throw new NullPointerException("No GeoJSON File Name passed in.");
    }
    try (AssetManager as = context.getAssets()) {
      try (InputStream is = as.open(fileName)) {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        return readAll(rd);
      }
    }
  }

  public static List<LatLng> parseGeoJsonCoordinates(String geojsonStr) {
    List<LatLng> latLngs = new ArrayList<>();
    FeatureCollection featureCollection = FeatureCollection.fromJson(geojsonStr);
    for (Feature feature : featureCollection.features()) {
      if (feature.geometry() instanceof Point) {
        Point point = (Point) feature.geometry();
        latLngs.add(new LatLng(point.latitude(), point.longitude()));
      }
    }
    return latLngs;
  }

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }
}