How to calculate distance from different markers in a map and then pick up the least one

后端 未结 9 1026
野趣味
野趣味 2020-12-05 08:53

I have to get distance from different markers on the map to the current location of the device and the pick up the shortest one. I have the lat and long for the markers and

9条回答
  •  日久生厌
    2020-12-05 09:15

    from your comment I see that you expect a maximum of 70-80 locations. This is not much.

    You can simply do a brute force search over all markers and take the minimum.

    Iterate over all markers, and search min distance:

        List markers = createMarkers(); // returns an ArrayList from your data source
        int minIndex = -1;
        double minDist = 1E38; // initialize with a huge value that will be overwritten
        int size = markers.size();
        for (int i = 0; i < size; i++) {
            Marker marker = markers.get(i);
            double curDistance = calcDistance(curLatitude, curLongitude, marker.latitude, marker.longitude);
          if (curDistance < minDist) {
             minDist = curDistance;  // update neares
             minIndex = i;           // store index of nearest marker in minIndex
          }
        }
    
        if (minIndex >= 0) {
           // now nearest maker found:
           Marker nearestMarker = markers.get(minIndex);
           // TODO do something with nearesr marker
        } else {
          // list of markers was empty
        }
    

    For calcDistance, use the distance calculation method provided by android. (e.g Location.distanceTo() )
    For 70-80 markers there is no need to make it faster and much more complex. If you have some thousands points then it is worth to invest in a faster solution (using a spatial index, and an own distance calculation which avoids the sqrt calc).

    Just print out the current time in milli seconds at the begin and at the end of the nearest maker search, and you will see, that it is fast enough.

提交回复
热议问题