3

I plotted a polyline in a Google Map and I want a marker in the polyline when the polyline is clicked. Then only the marker should appear in the middle of the polyline.

@Override
public void onPolylineClick(Polyline polyline) {
    double latitude = polyline.getPoints().get(0).latitude;
    double longitude = polyline.getPoints().get(0).longitude;
    mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
    CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(new LatLng(latitude, longitude))
        .zoom(18).build();
}

With the code above the marker gets plotted only at the first point, but I need it in the middle of the polyline. How can I do that?

halfer
  • 19,824
  • 17
  • 99
  • 186
Atul Dhanuka
  • 1,453
  • 5
  • 20
  • 56

2 Answers2

1

You can find the center of a polyline by getting the bound's center.

I haven't executed the code but I hope it will work fine.

public LatLng getPolylineCentroid(Polyline p) {

    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for(int i = 0; i < p.getPoints().size(); i++){
        builder.include(p.getPoints().get(i));
    }

    LatLngBounds bounds = builder.build();

    return bounds.getCenter();
}
Hassan Jamil
  • 951
  • 1
  • 13
  • 33
0

You can use the extrapolate function that I propose in this solution: How can I extrapolate farther along a road?

double middleDistance = SphericalUtil.computeLength(polyline.getPoints());

LatLng markerPosition = extrapolate(polyline.getPoints(), polyline.getPoints().get(0), middleDistance);

mMap.addMarker(new MarkerOptions().position(markerPosition).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
CameraPosition cameraPosition = new CameraPosition.Builder()
    .target(markerPosition)
    .zoom(18).build();
Community
  • 1
  • 1
antonio
  • 18,044
  • 4
  • 45
  • 61
  • When I try this, the extrapolate method returns null with !PolyUtil.isLocationOnPath, which doesn't make sense to me, considering the inputs. – Elliptica Jul 24 '19 at 22:52