PolyUtil.containsLocation not working as expected

I made a simple test:

LatLng city = new LatLng(53.121896, 18.010110);

List<LatLng> pts = new ArrayList<>();
pts.add(new LatLng(53.520790, 17.404158));
pts.add(new LatLng(53.450445, 19.209022));
pts.add(new LatLng(52.659365, 17.656366));
pts.add(new LatLng(52.525305, 19.303601));

LatLngBounds bounds = new LatLngBounds(pts.get(2), pts.get(1));

boolean contains1 = PolyUtil.containsLocation(city.latitude, city.longitude, pts, true);
System.out.println("contains1: " + contains1);

boolean contains2 = bounds.contains(city);
System.out.println("contains2: " + contains2);

      

This is how it works:

  • I have created a specific point ( city

    ) which I want to check if it is inside a polygon,
  • I declared the polygon as 4 points and the borders as 2 points (northeast and southwest).

Output:

contains1: false
contains2: true

      

Why is it PolyUtil.containsLocation

returning false? What am I missing here? It's a simple thing, you can check these points on google maps.

PolyUtil is a class from the Android map utilities provided by Google: 'com.google.maps.android:android-maps-utils:0.5'

+3


source to share


1 answer


You must define the vertices of the polygon in the correct order. Let me explain the screenshots, because a picture is worth a thousand words. You currently have the following vertices for the polygon

enter image description here

If you try to draw a polygon for the array list from your example, you will see the following polygon.

enter image description here



As you can see, indeed the city is outside the polygon and PolyUtil gives the correct result. At the same time, you correctly define the boundaries with the southwest and northeast peaks, so the city is within the boundaries. To fix the problem, you have to swap 3 and 4 in your example.

LatLng city = new LatLng(53.121896, 18.010110);

List<LatLng> pts = new ArrayList<>();
pts.add(new LatLng(53.520790, 17.404158));
pts.add(new LatLng(53.450445, 19.209022));
pts.add(new LatLng(52.525305, 19.303601));
pts.add(new LatLng(52.659365, 17.656366));

bounds = new LatLngBounds(pts.get(3), pts.get(1));

boolean contains1 = PolyUtil.containsLocation(city.latitude, city.longitude, pts, true);
System.out.println("contains1: " + contains1);

boolean contains2 = bounds.contains(city);
System.out.println("contains2: " + contains2);

      

You can find the sample project I used to take screenshots at https://github.com/xomena-so/so44523611

Hope this helps!

+6


source







All Articles