Is Long/Lat within Polygon from GeoJson

· 339 words · 2 minutes read

This is an example of checking if a pair of long/lat coordinates lie within a polygon or multipolygon when working with geojson. It’s often useful when working with geo-special data and maps to determine if the point your looking is within an area - or which area it’s within.

We use the paulmach/orb package (see on github), which is deep and precise library for dealing with all sorts of spacial and geometric data. To begin with we load in our geojson file, we’re using an example file, into a feature collection. Then we’re looping through each polygon to check if the point exists within it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main

import (
    "fmt"
    "io/ioutil"

    "github.com/paulmach/orb"
    "github.com/paulmach/orb/geojson"
    "github.com/paulmach/orb/planar"
)

const (
    GEO_FILE = "points.geojson"
)

func main() {

    // Load in our geojson file into a feature collection
    b, _ := ioutil.ReadFile(GEO_FILE)
    featureCollection, _ := geojson.UnmarshalFeatureCollection(b)

    // Pass in the feature collection + a point of Long/Lat
    if isPointInsidePolygon(featureCollection, orb.Point{100.5, 0.5}) {
        fmt.Println("Point 1 is inside a Polygon")
    } else {
        fmt.Println("Point 1 is not found inside Polygon")
    }

    if isPointInsidePolygon(featureCollection, orb.Point{105.5, 2.5}) {
        fmt.Println("Point 2 is inside a Polygon")
    } else {
        fmt.Println("Point 2 is not found inside Polygon")
    }
}

// isPointInsidePolygon runs through the MultiPolygon and Polygons within a 
// feature collection and checks if a point (long/lat) lies within it.
func isPointInsidePolygon(fc *geojson.FeatureCollection, point orb.Point) bool {
    for _, feature := range fc.Features {
        // Try on a MultiPolygon to begin
        multiPoly, isMulti := feature.Geometry.(orb.MultiPolygon)
        if isMulti {
            if planar.MultiPolygonContains(multiPoly, point) {
                return true
            }
        } else {
            // Fallback to Polygon
            polygon, isPoly := feature.Geometry.(orb.Polygon)
            if isPoly {
                if planar.PolygonContains(polygon, point) {
                    return true
                }
            }
        }
    }
    return false
}

is point within polygon

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!