Skip to content

Instantly share code, notes, and snippets.

@madr
Created May 30, 2014 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madr/7a187e5c1c5c2888759c to your computer and use it in GitHub Desktop.
Save madr/7a187e5c1c5c2888759c to your computer and use it in GitHub Desktop.
HTML5 geolocation
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body { margin: 0; }
div { position: absolute; width: 20px; height: 20px; border-radius: 50%; background: red; }
</style>
<img src="mupp2.png" alt="" width="2500" height="2500">
<div hidden></div>
<script>
/*jslint browser: true */
(function () {
"use strict";
if (navigator.geolocation !== undefined) {
var Map,
map,
mapImg,
upperLeftBound = { lat: 63.184472, lng: 14.616544 },
lowerRightBound = { lat: 63.171043, lng: 14.646316 };
window.scrollTo(0, 0);
Map = function (x, y, upperLeftBounds, lowerRightBounds) {
this.dims = {x: x, y: y};
this.bounds = [upperLeftBounds, lowerRightBounds];
this.spot = document.getElementsByTagName("div")[0];
};
Map.prototype.convert = function (lat, lng) {
var MAP_WIDTH, MAP_HEIGHT, e, w, n, s, nsspan, ewspan, nspix, ewpix, x, y;
MAP_WIDTH = this.dims.x;
MAP_HEIGHT = this.dims.y;
e = this.bounds[1].lat;
w = this.bounds[0].lat;
n = this.bounds[0].lng;
s = this.bounds[1].lng;
nsspan = Math.abs(n - s);
ewspan = Math.abs(w - e);
nspix = MAP_HEIGHT / nsspan;
ewpix = MAP_WIDTH / ewspan;
x = (Math.abs(w - lat)) * ewpix;
y = (Math.abs(n - lng)) * nspix;
return {
top: parseInt(x, 10),
left: parseInt(y, 10)
};
};
Map.prototype.center = function (lat, lng) {
var lt,
tl = this.convert(lat, lng),
w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
lt = {
left: tl.left - (w / 2),
top: tl.top - (h / 2)
};
if (lt.left < 0) { lt.left = 0; }
if (lt.top < 0) { lt.top = 0; }
window.scrollTo(lt.left, lt.top);
};
Map.prototype.showPos = function (lat, lng) {
var pos = this.convert(lat, lng);
this.spot.hidden = false;
this.spot.style.top = pos.top - 10 + "px";
this.spot.style.left = pos.left - 10 + "px";
};
mapImg = document.getElementsByTagName("img")[0];
map = new Map(mapImg.width, mapImg.height, upperLeftBound, lowerRightBound);
// initial scroll for the map
navigator.geolocation.getCurrentPosition(function (position) {
map.center(position.coords.latitude, position.coords.longitude);
});
// update position on map
var watchID = navigator.geolocation.watchPosition(function (position) {
map.showPos(position.coords.latitude, position.coords.longitude);
});
}
}());
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment