Skip to content

Instantly share code, notes, and snippets.

@afshin-hoseini
Last active May 30, 2017 04:32
Show Gist options
  • Save afshin-hoseini/2badbfef908defddd3adbf301b422fbc to your computer and use it in GitHub Desktop.
Save afshin-hoseini/2badbfef908defddd3adbf301b422fbc to your computer and use it in GitHub Desktop.
Geometry calculations
///Polygon decoder
public func decodePoly(encoded: String) -> [Location]? {
var poly = [Location]()
var index = 0
let len = encoded.length
var lat = 0.0, lng = 0.0
var encodedData = encoded.unicodeScalars
while (index < len) {
var b = 0
var shift = 0
var result = 0
repeat {
b = Int(encodedData[encodedData.index(encodedData.startIndex, offsetBy: index)].value) - 63
result |= (b & 0x1f) << shift
shift += 5
index = index + 1
} while (b >= 0x20);
let dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1))
lat = lat + Double(dlat)
shift = 0
result = 0
repeat {
b = Int(encodedData[encodedData.index(encodedData.startIndex, offsetBy: index)].value) - 63
result |= (b & 0x1f) << shift
shift += 5
index = index + 1
} while (b >= 0x20)
let dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1))
lng = lng + Double(dlng)
let location = Location.init(lat / 1E5, lng / 1E5)
poly.append(location)
}
return poly;
}
public func isPointInPolygon(point: Location, polygon: [Location]) -> Bool {
var j = polygon.count - 1
var result = false
for i in 0 ..< polygon.count {
if (polygon[i].latitude > point.latitude) != (polygon[j].latitude > point.latitude) &&
(point.longitude < (polygon[j].longitude - polygon[i].longitude) * (point.latitude - polygon[i].latitude) / (polygon[j].latitude - polygon[i].latitude) + polygon[i].longitude) {
result = !result
}
j = i
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment