Search code examples
androidgoogle-maps-api-2google-polyline

Adding points to PolylineOptions in Android GoogleMap api 2 not working


I am trying to add Polylines from the points I added to my GoogleMap. They should be displayed on the road (set as .geodesic(true). When I add only two points from my xml there is drawn a line but it is not geodesic... But the real problem is: if I try to add all point which are in my XML the App isn't working at all. Does anybody have an idea what might be wrong with my code?

XML File:

    <?xml version="1.0" encoding="utf-8"?>
 <resources>

 <string-array name="coordinates">
    <item name="waypoint1">50.991185 , 7.131250</item>
    <item name="waypoint2">50.990601 , 7.131534</item>
    <item name="waypoint3">50.991678 , 7.130603</item>
    <item name="waypoint4">51.000614 , 7.137122</item> 
    <item name="waypoint5">51.003929, 7.146833</item> 
    <item name="waypoint6">51.003853, 7.146931</item> 
    <item name="waypoint7">51.003697, 7.147666</item> 
    <item name="waypoint8">51.003964, 7.148090</item> 
    <item name="waypoint9">51.003982, 7.148470</item> 
 </string-array> 
   </resources>

Method which isn't working:

    private void drawline(){
    String[] coordinates = getResources().getStringArray(R.array.coordinates);
    List<LatLng> waypoints = new ArrayList<LatLng>();
    LatLng[] latlng = new LatLng[coordinates.length];


    for(int i=0;i < coordinates.length;i++){
        String coordinate[] = coordinates[i].split(",");
        double x = Double.parseDouble(coordinate[i]);
        double y = Double.parseDouble(coordinate[i]);
        latlng[i] = new LatLng(x,y);    
    } 

    for (int i=0; i < coordinates.length; i++){
    waypoints.add(latlng[i]);   
    }

    PolylineOptions options = new PolylineOptions()
        .color(Color.BLUE)
        .geodesic(true)
        .width(5)
        .addAll(waypoints);

    Polyline pfad = mMap.addPolyline(options);
    }

I tried lots of different ways to save my coordinates as LatLng List but it never worked. I would be really happy if anybode can help me. Maybe there's also an idea why the lines aren't drawn as geodestic lines.


Solution

  • Your problem is in this loop:

    for(int i=0;i < coordinates.length;i++){
        String coordinate[] = coordinates[i].split(",");
        double x = Double.parseDouble(coordinate[i]);
        double y = Double.parseDouble(coordinate[i]);
        latlng[i] = new LatLng(x,y);    
    }
    

    You split the coordinates by a comma (which is alright) but you are reading the wrong index. Use this instead:

    double x = Double.parseDouble(coordinate[0]);
    double y = Double.parseDouble(coordinate[1]);