0

I've got geodesic polyline connecting two point on my map. I would also like to put marker in the midpoint between those points so it is displayed on the polyline. To calculate the midpoint I am using script from this link and when the map is zoomed out it is looking good, added marker is displayed above the line. But when I zoom it in then you can see that the marker goes slightly off to the side. Here is the screenshot:

enter image description here

How I am calculating midpoint:

fun midpoint(point1: LatLng, point2: LatLng): LatLng {
            val deltaLongitude = Math.toRadians(point2.longitude - point1.longitude)
            val latitude1 = Math.toRadians(point1.latitude)
            val latitude2 = Math.toRadians(point2.latitude)
            val longitude1 = Math.toRadians(point1.longitude)

            val Bx = Math.cos(latitude2) * Math.cos(deltaLongitude)
            val By = Math.cos(latitude2) * Math.sin(deltaLongitude)

            val latitude = Math.atan2(Math.sin(latitude1) + Math.sin(latitude2),
                    Math.sqrt((Math.cos(latitude1) + Bx) * (Math.cos(latitude1) + Bx) + By * By))
            val longitude = longitude1 + Math.atan2(By, Math.cos(latitude1) + Bx)

            return LatLng(Math.toDegrees(latitude), Math.toDegrees(longitude))
        }

And how I am adding the geodesic polyline:

val polylineOptions = PolylineOptions()
                .add(departurePosition, destinationPosition)
                .width(10)
                .color(ContextCompat.getColor(context, R.color.e_light_blue_70))
                .geodesic(true)
googleMap.addPolyline(polylineOptions)

I imagine that the difference comes inaccurate calculations either on my side or google maps api. How could I make sure that my calculated midpoint overlaps with the polyline?

EDIT: I know noticed that problem occurs on shorter distances between points. When one point is in Europe and second in USA for example then it works fine and my marker overlaps with polyline

matip
  • 794
  • 3
  • 7
  • 27
  • 2
    Have you tried the [Google Map SDK Utility Library](https://developers.google.com/maps/documentation/android-sdk/utility/) `SphericalUtil.interpolate(LatLng from, LatLng to, double fraction)` – Morrison Chang Aug 27 '19 at 14:29
  • @MorrisonChang I tried that library now but got same results – matip Aug 28 '19 at 07:52
  • Just noticed that `Polyline.html.isGeodesic()` uses the rule `the geodesic curve is constructed assuming the Earth is a sphere` so depending on your use case either use a spherical midpoint calculation or work out what a Polyline would look like in a WGS84 system. – Morrison Chang Aug 28 '19 at 08:18
  • @matip Anyway, you can snap your marker to polyline like in [this](https://stackoverflow.com/a/54950425/6950238) answer. – Andrii Omelchenko Aug 29 '19 at 19:17

0 Answers0