Checking whether a point is outside a circle using Turf.js
by Alex Azuero
HTML
<script src="//cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<link rel="stylesheet" href="//cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css">
<script src="//api.tiles.mapbox.com/mapbox.js/plugins/turf/v2.0.0/turf.min.js"></script>
<div id="map"></div>
CSS
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
JavaScript
/////////////////////////////////////////////////////////////////////////////////////////////
//setting up the map//
/////////////////////////////////////////////////////////////////////////////////////////////
var map = L.map('map').setView([17.4468, 78.3922], 15);
ATTR = '© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a> | ' +
'© <a href="http://cartodb.com/attributions">CartoDB</a>';
CDB_URL = 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';
L.tileLayer(CDB_URL, {
attribution: ATTR
}).addTo(map);
/////////////////////////////////////////////////////////////////////////////////////////////
//adding data//
/////////////////////////////////////////////////////////////////////////////////////////////
var fen = {
lat: "17.4468",
lng: "78.3922"
};
var radius = 450;
var region = L.circle(fen, radius, {
color: 'red',
fillColor: '#f03',
fillOpacity: 0
}).addTo(map);
map.on('click', function(e) {
var marker = new L.marker(e.latlng).addTo(map);
if (turf.distance(marker.toGeoJSON(), region.toGeoJSON()) * 1000 > radius) {
alert('You are outside the circle!');
}
});