Thursday, May 29, 2014

How to see your current location in Google map using HTML 5

HTML 5 is the latest  version of HTML it has capability to deliver rich internet applications without using any additional plugins.So we can make hi-end web applications using HTML 5. HTML 5 is cross-platform so that work with different devices.


This tutorial will teach you how to use geolocation feature in HTML 5 to get your current location on Google map.

Step 1:#createfile

create the html file.

Open notepad and type the codes as given below:


#source code:


<!DOCTYPE html>
<html>
<body onload="myLocation()">
<div id="mymap"></div>
<script>
var x=document.getElementById("demo");
function myLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
  else{x.innerHTML="change location setting of your browser";}
  }
function showPosition(position)
  {
  var latitude_longitude=position.coords.latitude+","+position.coords.longitude;
  var image="http://maps.googleapis.com/maps/api/staticmap?center="
  +latitude_longitude+"&zoom=15&size=500x500&sensor=false";
  document.getElementById("mymap").innerHTML="<img src='"+image+"'>";
  }
function showError(error)
  {
  switch(error.code) 
     {
    case error.PERMISSION_DENIED:
      x.innerHTML="change location setting of your browser"
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML="Location not available."
      break;
     }
   }
</script>
</body> 
</html>


Step 2:#save

Save your notepad file in .html format

Step  3:#execution

Note: HTML 5 doesn't support older browsers.Execute this file on any latest browsers.I here use the latest version of Firefox. You need a working internet to fetch your location and load the map by the help of Google map services.


Your browser may ask you permission to share your location data.

Give permission so that we can see the real fun 

Your current location map will get loaded as above.

#fun

You can change the  map size as well as the zoom level of the map by changing attributes for Zoom and size


 function showPosition(position)
         {
  varlatitude_longitude=position.coords.latitude+","+position.coords.longitude;
  var image="http://maps.googleapis.com/maps/api/staticmap?center="
  +latitude_longitude+"&zoom=20&size=500x500&sensor=false";
  document.getElementById("mymap").innerHTML="<img src='"+image+"'>";
  }

Here I have changed zoom level to 20 and size 500X500 so that you can see large sized extra zoom map. Have fun..

Note: Google™ and Google™ maps are the trademarks of Google Inc.


No comments:

Post a Comment