检查路线是否包含特定坐标

时间:2018-05-26 20:10:34

标签: android google-maps location

我目前正在开发一个应用程序,我想知道路由是否包含一组lat长坐标。这是我的代码:

public class PathActivity extends FragmentActivity implements OnMapReadyCallback, RoutingListener {

    private GoogleMap mMap;
    FetchLocation fetchLocation;

    LatLng start;
    LatLng end;
    ProgressDialog pd;
    List<Polyline> polylines;
    private static final int[] COLORS = new int[]{R.color.gradient_dark_pink};

    FirebaseFirestore firestore;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_path);

        //Receiving Object From Intent
        Intent rcv = getIntent();
        fetchLocation = (FetchLocation) rcv.getSerializableExtra("keyFetchLocationObject2");

        pd = new ProgressDialog(this);
        pd.setMessage("Please Wait...");

        firestore = FirebaseFirestore.getInstance();

        fetchAllTrafficLights();

        polylines = new ArrayList<>();

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

       pd.show();

       //Making a Path
        start = new LatLng(fetchLocation.latitude, fetchLocation.longitude);
        end = new LatLng(fetchLocation.destinationLatitude, fetchLocation.destinationLongitude);
        Routing routing = new Routing.Builder()
                .travelMode(Routing.TravelMode.DRIVING)
                .withListener(this)
                .alternativeRoutes(false)
                .waypoints(start, end)
                .build();

        routing.execute();
    }

    @Override
    public void onRoutingFailure(RouteException e)
    {
        Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
        pd.dismiss();
    }

    @Override
    public void onRoutingStart() {

    }

    @Override
    public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex)
    {
        pd.dismiss();

        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(start, 16));

        if(polylines.size()>0) {
            for (Polyline poly : polylines) {
                poly.remove();
            }
        }

        polylines = new ArrayList<>();
        //add route(s) to the map.
        for (int i = 0; i <route.size(); i++)
        {
            //In case of more than 5 alternative routes
            int colorIndex = i % COLORS.length;

            PolylineOptions polyOptions = new PolylineOptions();
            polyOptions.color(getResources().getColor(COLORS[colorIndex]));
            polyOptions.width(10 + i * 3);
            polyOptions.addAll(route.get(i).getPoints());
            Polyline polyline = mMap.addPolyline(polyOptions);
            polylines.add(polyline);

            Toast.makeText(getApplicationContext(),"Route "+ (i+1) +": distance - "+ route.get(i).getDistanceValue()+": duration - "+ route.get(i).getDurationValue(),Toast.LENGTH_SHORT).show();

            // Start marker
            MarkerOptions options = new MarkerOptions();
            options.position(start);
            options.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_start_blue));
            mMap.addMarker(options);

            // End marker
            options = new MarkerOptions();
            options.position(end);
            options.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_end_green));
            mMap.addMarker(options);


        }

    }

    @Override
    public void onRoutingCancelled() {

    }

    public void fetchAllTrafficLights()
    {
        pd.show();
        firestore.collection("Controller").get().addOnCompleteListener(this, new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(Task<QuerySnapshot> task)
            {
                if(task.isSuccessful())
                {
                    for(QueryDocumentSnapshot documentSnapshot : task.getResult())
                    {
                        Log.i("Hello", documentSnapshot.get("controllerLatitude").toString() + "   " + documentSnapshot.get("controllerLongitude").toString());
                        pd.dismiss();
                    }
                }
            }
        })
                .addOnFailureListener(this, new OnFailureListener()
                {
                    @Override
                    public void onFailure(Exception e)
                    {
                        Toast.makeText(PathActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        pd.dismiss();
                    }
                });
    }
}

我正在使用github库:https://github.com/jd-alexander/Google-Directions-Android来绘制两点之间的路线。 协调已保存在firestore数据库中,并成功获取,如Log中所示。现在我想检查从数据库中获取的lat长点是否在路径中。例如。如果我们从A点移动到D,我想检查路线上是否存在B,C点。我也想知道google places api是否总是在两个位置之间给出相同的路线坐标。这是我的目标:

public class FetchLocation implements Serializable
{
    public double latitude;
    public double longitude;
    public double destinationLatitude;
    public double destinationLongitude;

    public FetchLocation()
    {

    }

    public FetchLocation(double latitude, double longitude, double destinationLatitude, double destinationLongitude) {
        this.latitude = latitude;
        this.longitude = longitude;
        this.destinationLatitude = destinationLatitude;
        this.destinationLongitude = destinationLongitude;
    }

    @Override
    public String toString() {
        return "FetchLocation{" +
                "latitude=" + latitude +
                ", longitude=" + longitude +
                ", destinationLatitude=" + destinationLatitude +
                ", destinationLongitude=" + destinationLongitude +
                '}';
    }
}

使用google place autocomplete- https://developers.google.com/places/android-sdk/autocomplete在上一个活动中获取用户来源lat long,并将其设置在传递给此活动的对象中。

任何人都请帮忙!!

1 个答案:

答案 0 :(得分:2)

查看PolyUtil.isLocationOnPath(LatLng point, java.util.List<LatLng> polyline, boolean geodesic, double tolerance)Google Maps Android API Utility Library方法。您需要从A到D获取折线路径,如果它位于A-D路径上,则使用isLocationOnPath()检查列表(B和C)中的每个点。这样的事情:

for (LatLng point : pointsBandCList) {
    if (PolyUtil.isLocationOnPath(point, polylineFromAtoD.getPoints(), true, 100)) {
        // "point" laying on A to D path

        ...
    }
}

其中100 - 是公差(以米为单位)。您可以根据自己的任务进行调整。