Search code examples
javacomputational-geometrypolygonsjts

Find neighbouring Polygons Java


I have a series of Polygons, created using the JTS Topology Suite. Each polygon is a set of points, longitudes and latitudes that form a shape, as shown below.

((lat1,lon1),(lat2,lon2),....(lat1,lon1))

I want to find each of these polygons neighbours, the other shapes that are physically next to them. I have thought of looking for matching points, but obviously that won't work in all cases. I was wondering if there is any package that will check to see if polygons share the same edge that I could use in this situation? Or if not then another way to do this in Java.

Thanks.


Solution

  • There was in fact a very simple way to do this. I created an arraylist containing an array of objects. The object referenced the name/id of the polygon, the actual polygon coordinates and then a string that would contain ids of any neighbours.

    In JTS Topology suite there is a method that you can call on polygons called touches that returns a boolean; so I had a double for loop, going through my arraylist twice and calling the method touches on polygon(i) so:

    arraylist<object[]>..
    //where in the array the objects are
    object[0] = id
    object[1] = polygon
    object[2] = neighbours
    
    for (int i=0;i<arraylist;i++)
      for (int j=0;j<arraylist;j++)
        if (i)[1].touches(j)[1]
          update i[2]..
    

    It's probably not the best method but it seems to work.