I've 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);
Here is how it works:
city
), which I want to test if it is inside a polygon,Output is:
contains1: false
contains2: true
Why PolyUtil.containsLocation
returns false? What am I missing here? It's a simple thing, you can test these points on google maps.
PolyUtil is a class from android maps utils provided by Google: 'com.google.maps.android:android-maps-utils:0.5'
You should define the vertices of the polygon in correct order. Let's explain with screenshots, because the picture is worth of thousand words. Currently you have the following vertices for polygon
If you try to draw the polygon for the array list from your example you will see the following polygon.
As you can see, indeed the city is outside of the polygon and the PolyUtil gives correct result. In the same time you define bounds correctly with southwest and northeast vertices, so the city is inside the bounds. To fix the issue you should swap points 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 sample project that I used to create screenshots at https://github.com/xomena-so/so44523611
I hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With