Wednesday 5 October 2011

Find GPS location (latitude and longitude) is within given radius

In a project, I need to determine whether a given GPS location (latitude and longitude) is within a pre-set radius area, for example, within a 2 kilometres circle of a target place - Vancouver Convention Centre. It's not a rocket science to do it but it would be helpful for those who need to implement the similar logic.

Here is code snippet in javascript, and could be easily ported to other languages, like C#.

 
// center: the center goelocation of the radius
// radius: radius in meter
// loc: the geolocation that you want to check
function isInArea(center, radius, loc) {
        var R = 6371;
        var lat1 = loc.lat();
        var lon1 = loc.lng();
        var lat2 = center.lat();
        var lon2 = center.lng();
        var dLat = (lat2 - lat1) * Math.PI / 180;
        var dLon = (lon2 - lon1) * Math.PI / 180;
        var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
		Math.sin(dLon / 2) * Math.sin(dLon / 2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        var d = R * c;
        return (d * 1000 <= radius)
    };
 

No comments:

Post a Comment