Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PolyUtil.containsLocation doesn't work as expected

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:

  1. I created a particular point (city), which I want to test if it is inside a polygon,
  2. I declared a polygon as 4 points and bounds as 2 points (northeast and southwest).

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'

like image 288
Makalele Avatar asked Jun 13 '17 13:06

Makalele


1 Answers

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

enter image description here

If you try to draw the 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 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!

like image 122
xomena Avatar answered Nov 03 '22 00:11

xomena