Last active
November 9, 2020 14:15
-
-
Save kernelshreyak/9b29f9a43041df8873d160d76b8585fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Algorithm implementation to check whether a given location (specified by an address) is within boundaries of a geographical region | |
(region name is also provided as input). | |
This uses Point In Polygon (PIP) algorithm[https://www.npmjs.com/package/@turf/boolean-point-in-polygon] | |
to check coordinate is inside our outside the polygon represented by the GeoJSON data. | |
Author: Shreyak Chakraborty | |
*/ | |
const axios = require('axios'); | |
const pointInPolygon = require('@turf/boolean-point-in-polygon').default; | |
var inputs = { | |
region: "Downers Grove IL", | |
address: "1903 Elmore Ave Downers Grove, IL 60515", //inside boundary | |
// address: "1903 Elmore Ave Downers Grove, IL 60515", //outside boundary | |
} | |
var region = inputs.region; | |
var address =inputs.address; | |
if (region != "") { | |
// get polygon shape data of the region | |
var geojson_url = `https://nominatim.openstreetmap.org/search.php?q=${encodeURI(region)}&polygon_geojson=1&format=json`; | |
axios(geojson_url,{ | |
headers: { | |
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240' | |
} | |
} | |
) | |
.then(result2 => { | |
// console.log(result2); | |
var geodata = result2.data[0]; | |
var polygon = geodata.geojson; | |
// console.log(polygon); | |
//geocode the address to get point | |
var geojson_url2 = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURI(address)}&key=<APIKEY>`; | |
axios(geojson_url2,{ | |
headers: { | |
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240' | |
} | |
} | |
) | |
.then(result3 => { | |
// console.log(result3); | |
var geodata2 = result3.data.results[0]; | |
const point = { | |
type:"Point", | |
coordinates: [geodata2.geometry.location.lng,geodata2.geometry.location.lat] | |
}; | |
// console.log(point); | |
if (pointInPolygon(point, polygon)) { | |
console.log(`${address} is within boundaries of ${region}`); | |
} | |
else{ | |
console.log(`${address} is outside boundaries of ${region}`); | |
} | |
}) | |
}) | |
} | |
else{ | |
console.log(`No data for ${address}`); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment