<!doctype html >
<html lang="en" >
<head>
<title>HTML5 Geolocation? </title>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
<script type="text/javascript" >
window.onload = getLocation;
/* Here we will check the browser supports the Geolocation API; if exists, then we will display the location */
var geo = navigator.geolocation;
function getLocation() {
if( geo ) {
geo.getCurrentPosition( displayLocation );
} else {
alert( "Oops, Geolocation API is not supported" );
}
}
/* This function displays the latitude and longitude when the browser has a location. */
function displayLocation( position ) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById( 'location' );
div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
// Call showMap function once we've updated other div's on the page
displayMap( position.coords );
}
// Global Variable that will hold Google Map
var map;
/*This method is used to display Google Map. */
function displayMap( coords ) {
var googleLatAndLong = new google.maps.LatLng( coords.latitude, coords.longitude );
var mapOptions = {
zoom: 10,
center: googleLatAndLong,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var mapDiv = document.getElementById( 'map' );
map = new google.maps.Map( mapDiv, mapOptions );
}
</script>
<style type="text/css">
* {margin: 0 auto;padding: 0;}
body {background-color: #F2F2F2;}
.container {margin: 0 auto;width: 920px;padding: 50px 20px; background-color: #fff;}
h3 {text-align: center; margin-bottom: 50px;}
p {margin: 20px;}
#location {margin-bottom: 30px;}
#map {width: 100%; height: 300px;}
</style>
</head>
<body>
<div class="container" align="center">
<h2> HTML5 Geolocation - This is Your Location </h2><br>
<div id="location">
You are at Latitude: _________, Longitude: _________
</div>
<div id="map" > </div>
</div>
</body>
</html>