HTML 5 TutorialsHow to use Location API and Google maps in HTML5

How to use Location API and Google maps in HTML5

In our blog today we will write a small little program to invoke the location API of HTML5.
The HTML5 uses Geolocation API to provide the current location of the user. But before providing this access our program will have to request to grant access to the privacy settings and user will have to approve this for the API to work.

Step 1

We will create a HTML page and will create a button there. The user’s location will be displayed on Google MAP once the user presses the button.

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Maps</title>
</head>

Step 2

Create a button to call the Geolocation API

<body>
<p id="demo"  style="font-size:larger">Want to know your location,Just click me..!!</p>
<button onclick="getlocation()">Click me</button>

//Here a button is defined with an onclick() event, when this operate it fires the getlocation() function defined later.
<div id="map"></div>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>

This line of code is used the google APIs in our application.User can use it directly or they can generate their own key.To generate their own key go for the following link :

https://developers.google.com/maps/documentation/javascript/tutorial#api_key

<script>
var x = document.getElementById("demo");
function getlocation(){
	if(navigator.geolocation){
		navigator.geolocation.getCurrentPosition(showposition);
	}
	else{
		x.innerHTML="This feature is unavailable";
		}	
}

This is the geolocation() function defined.This Api first take permission from the user.If user approve then the location is showed otherwise it shows an error that “This feature is not available”.

Step 3

Get and Display the position

function showposition(position){
	x.innerHTML="latitude" + position.coords.lattitude + "longitude" + position.coords.longitude;//In this line of code the innerHTML property is set to their respective latitude and longitude.User can see their location attributes by using that single line of code.

	var latilongi=position.coords.latitude + "," + position.coords.longitude;
	var img="http://maps.googleapis.com/maps/api/staticmap?center="
  +latilongi+"&zoom=8&size=500x500&sensor=false";
  document.getElementById("map").innerHTML="<img src='"+img+"'>";
	
	}

</script>
</body>
</html>

To define the location on google maps we take another variable which stores the location of the user.An link to the image of google maps is provided in the link.We get the element by using the id and set its inner html property.

You will have to put this code in a webserver for it to work properly.

Output

output1

output2

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -