Initialize a map with the user's current location and update marker position if user's location changes.
See also the Geolocation Marker utility.
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> |