Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Last active August 29, 2015 14:15
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 joyrexus/77c71873845ad274af7f to your computer and use it in GitHub Desktop.
Save joyrexus/77c71873845ad274af7f to your computer and use it in GitHub Desktop.
map and watch location

Initialize a map with the user's current location and update marker position if user's location changes.

See also the Geolocation Marker utility.

<!doctype html>
<html lang="en">
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script>
<script>
var map,
marker, // marker showing user's current location
coords = new google.maps.LatLng(35.21, -85.936); // default coords
function setMarker(pos) {
var lat = pos.coords.latitude,
lng = pos.coords.longitude;
coords = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
map: map,
position: coords,
title: "Current Position"
});
map.panTo(coords);
}
function error(err) {
alert('ERROR(' + err.code + '): ' + err.message);
}
// initialize map with user's current position and watch if position changes
function init() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: coords,
mapTypeId: google.maps.MapTypeId.TERRAIN
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setMarker, error);
} else {
alert("Your browser does not support the Geolocation API");
}
navigator.geolocation.watchPosition(function (pos) {
var lat = pos.coords.latitude,
lng = pos.coords.longitude;
coords = new google.maps.LatLng(lat, lng);
marker.setPosition(coords);
map.panTo(coords);
}, error);
}
google.maps.event.addDomListener(window, 'load', init);
</script>
<body>
<div id="map" style="height:600px;"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment