Search code examples
androidandroid-maps-v2polylineandroid-maps-utils

Google map Android API v2 - InfoWindow on polyline?


I am drawing polyline on my map,I need to show some data to user now.

How I can draw text or InfoWindow on each polyline ?

I add polyline like :

ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();

// Traversing through all the routes
for(int i=0;i<result.size();i++){
    points = new ArrayList<LatLng>();
    lineOptions = new PolylineOptions();
    String color = colors[i % colors.length];
    // Fetching i-th route
    List<HashMap<String, String>> path = result.get(i);

    // Fetching all the points in i-th route
    for(int j=0;j<path.size();j++){
        HashMap<String,String> point = path.get(j);

        double lat = Double.parseDouble(point.get("lat"));
        double lng = Double.parseDouble(point.get("lng"));
        LatLng position = new LatLng(lat, lng);

        points.add(position);
    }

    // Adding all the points in the route to LineOptions
    lineOptions.addAll(points);
    lineOptions.width(5);
    lineOptions.color(Color.parseColor(color));

    // Drawing polyline in the Google Map for the i-th route
    mMap.addPolyline(lineOptions);
}

For example I need to this :

enter image description here


Solution

  • I do this by creating an invisible marker on the polyline and then showing its info window. For example:

    //use a transparent 1px & 1px box as your marker
    BitmapDescriptor transparent = BitmapDescriptorFactory.fromResource(R.drawable.transparent);
    MarkerOptions options = new MarkerOptions()
                    .position(new LatLng(someLatitide, someLongitude))
                    .title(someTitle)
                    .snippet(someSnippet)
                    .icon(transparent)
                    .anchor((float) 0.5, (float) 0.5); //puts the info window on the polyline
    
    Marker marker = mMap.addMarker(options);
    
    //open the marker's info window
    marker.showInfoWindow();
    

    Update to include general approach to touching the polyline and opening an info window: 1. Implement an OnMapClickListener 2. On an onMapClick event, determine whether the user has touched the polyline. I do this by storing the polyline points in a quadtree and searching the quadtree for the closest point from where the user touched the screen. If the distance is within a certain threshold (i.e. close to the polyline), create the invisible marker referenced above and open its info window. If the touch is not within the threshold, ignore the onMapClick event. 3. On the next onMapClick event delete the previously created invisible marker so you do not have a bunch of invisible markers taking up memory. Hope that helps.