All about programming in GNU/LINUX

Geolocation

Intro to HTML 5 Geolocation :Find the locational data and getting it on the Map

HTML 5 brings in lot of powerful features along with it , one of such fascinating feature is the capability to code locational based applications using the `Geolocation and Goolge MAPS API’s `

In this post i’ll be briefing you folks on obtaining your locational reference in terms of latitude and longitude and using the same to get the MAP on the webpage centred around your current location

There are 3 parts to be coded to achieve the objective.The HTML5 code where the execution starts and links to the Java Script file and the CSS stylesheet

Here is the HTML5 code which is pretty much straigh forward

<!doctype html>
<html>
<head>
	<meta charset = "utf-8">
	<title>Location</title>
	<script src="http://maps.google.com/maps/api/js?sensor=true"></script> 
        <!-- To link to the google map API's -->
	<script src="loc.js"></script>          
	<link rel = "stylesheet" href="myLoc.css">
</head>
<body>
	<div id="Location">
		Here comes the location              <!-- Place Holder for the locational data -->
	</div>
	
	<div id="map">				     <!-- Place holder for the Map -->	
	</div>

</body>
</html>	

The Java script part is the most important snippet to get this working , here goes the Java Script Code 😀

var map=null;


window.onload = getLocation ;

function showMap(coords) {
	var googleLatAndLong = new google.maps.LatLng(coords.latitude,coords.longitude);
	var mapOptions	= {
		zoom: 10, 
		center: googleLatAndLong ,
		mapTypeId: google.maps.MapTypeId.ROADMAP	
	};//The option object specifying the options for the map
	var mapDiv = document.getElementById("map");
	map = new google.maps.Map(mapDiv,mapOptions);//API which gets the map
}




function getLocation() {
	if(navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(displayLocation); 
//The API calls the display location function with position object containing the positional parameters
	}
	else {
		alert("Doesnt support Geolocation");
	}
}
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;
	showMap(position.coords); 
	//showMap function takes in the positional parameters and displays the map
}


Here the CSS code for the map id

div#map {
	margin: 5px;
	width: 400px;
	height: 400px;
	border: 1px solid black;
}

Advertisements