Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Geolocation example
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Geolocation with Javascript</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<h1 class="page-header">Geolocation example</h1>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="coordinates">Coordinates <button id="getMyPosition" class="btn btn-primary btn-xs">Get my position</button></label>
<input type="input" class="form-control" id="coordinates" readonly>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="radius">Radius: <span id="currentRadius">50</span>km</label>
<input type="range" value="50" min="0" max="8050" step="100" id="radiusRange">
</div>
</div>
</div>
<ul id="cities" class="list-group">
<li class="list-group-item">Nothing found</li>
</ul>
</div>
</div>
</div>
<script>
// small list of geolocated points
const points = [
{
name: 'Lausanne',
lat: 46.534271,
lng: 6.620206
},
{
name: 'Zürich',
lat: 47.381583,
lng: 8.531827
},
{
name: 'Le Mans',
lat: 48.001837,
lng: 0.194578
},
{
name: 'Montpellier',
lat: 43.624121,
lng: 3.871447
},
{
name: 'Münich',
lat: 48.140408,
lng: 11.586595
},
{
name: 'Mexico',
lat: 19.427701,
lng: -99.266023
},
{
name: 'Buenos Aires',
lat: -34.422808,
lng: -58.572664
},
{
name: 'Brasilia',
lat: -15.792772,
lng: -47.883031
},
{
name: 'Yaoundé',
lat: 3.875265,
lng: 11.487751
},
{
name: 'Oklahoma City',
lat: 35.509992,
lng: -97.539860
},
{
name: 'Québec',
lat: 45.502601,
lng: -73.589665
}
];
// this will receive the detected position
var myPosition = null;
// get needed DOM elements
const btnGetMyPosition = document.getElementById('getMyPosition');
const inputRadiusRange = document.getElementById('radiusRange');
const currentRadius = document.getElementById('currentRadius');
const inputCoordinates = document.getElementById('coordinates');
const citiesList = document.getElementById('cities');
// attach events
btnGetMyPosition.addEventListener('click', getLocation);
inputRadiusRange.addEventListener('input', (e) => {
// update range indicator
currentRadius.innerHTML = e.target.value;
// show points
filterPoints();
});
/**
* Get geolocation from browser API
*
* @return void
*/
function getLocation() {
navigator.geolocation.getCurrentPosition((position) => {
// save the position
myPosition = position;
// show points
filterPoints(myPosition);
// show coordinates in the input box
inputCoordinates.value = myPosition.coords.latitude+','+myPosition.coords.longitude;
}, (error) => {
// check if the user denied geolocation, or if there was any other problem
if (error.code == error.PERMISSION_DENIED) {
alert('Geolocation has been disabled on this page, please review your browser\'s parameters');
} else {
alert('Unable to find your position, try again later.');
}
});
}
/**
* Filter the city list and display them
*/
function filterPoints() {
// don't do anything else until we have a position
if (myPosition == null) {
return false;
}
// Reset cities list
citiesList.innerHTML = '';
// set a new empty fragment
var fragment = document.createDocumentFragment();
// loop through each points
points.map((point) => {
// if the point is in the radius distance, show it in the list
if (calculateDistance(myPosition.coords.latitude, myPosition.coords.longitude, point.lat, point.lng) <= inputRadiusRange.value) {
// create a new <li> and add it to the fragment
var li = document.createElement("li");
li.textContent = point.name;
li.className = 'list-group-item';
fragment.appendChild(li);
}
});
// add the fragment to the cities list
citiesList.appendChild(fragment);
}
/**
* Calculates a distance between two geolocated points
*
* @param float lat1 first point's latitude
* @param float long1 first point's longitude
* @param float lat2 second point's latitude
* @param float long2 second point's longitude
*
* @return float distance in meters
*/
function calculateDistance(lat1, long1, lat2, long2) {
var p = 0.017453292519943295; // Math.PI / 180
var c = Math.cos;
var a = 0.5 - c((lat2 - lat1) * p)/2 +
c(lat1 * p) * c(lat2 * p) *
(1 - c((long2 - long1) * p))/2;
return 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.