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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Step 2

Create a button to call the Geolocation API

<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=""></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 :

var x = document.getElementById("demo");
function getlocation(){
		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=""
  document.getElementById("map").innerHTML="<img src='"+img+"'>";


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.




Exclusive content

- Advertisement -Newspaper WordPress Theme

Latest article


More article

- Advertisement -Newspaper WordPress Theme