SlideShare una empresa de Scribd logo
1 de 3
Descargar para leer sin conexión
Articles from Jinal Desai .NET
HTML5 History API and Geolocation API
2012-12-30 15:12:35 Jinal Desai

HTML5 History API
It was very difficult to manipulate or control session history of particular browsing
context before HTML5. Some workarounds like location.hash or page reloads are
there which is not reliable.

HTML5 History API allows web developers to move forward and backward in
session history or adding/removing entries from session history easily. It is the
History object of DOM interface. The History object is uniquely defined for each tab,
which can be utilized for manipulating session history with some methods.

The History object contains comma separated session entries in which each entries
consists of a URL or a state object or both and in ddition can have title, a document
object, form data, a scroll position and many other information associated with it.

Let me list down some of the basic methods of it.

window.history.state: Returns the current state object.
window.history.replaceState(data, title [, url]): Updates the current entry in the
session history, with the given data, title and URL (the URL is optional).
window.history.forward(): Goes forwards by one step in the joint session history. If
there is no next page to go to, it does nothing.
window.history.go(n): Goes backwards or forwards by the specified number of
steps in the joint session history. If the value you specify is zero, it will reload the
current page. If it would cause the target position to be outside the available range of
the session history, then nothing happens.
window.history.back(): Goes backwards by one step in the joint session history. If
there is no previous page to go to, it does nothing.
window.history.pushState(data, title [, url]): Pushes the data specified in the
arguments onto the session history, with the given title and URL (the URL is
optional).
window.history.length: Returns the number of entries in the joint session history.

To add history entry.
window.history.pushState({name:"Jinal Desai"},"FirstName","jinaldesai.net");

To replace history entry.
window.history.replaceState({name:"Jinal Desai"},"Title",
"startshining.com");

To navigate forward by 3 entries.
history.go(3);

This is fully functional example of HTML5 History API.

HTML5 Geolocation API
HTML5 Geolocation API is mainly used to track user’s geographical position, but this
can compromise user’s privacy. Thus the position is not available unless the user
approves it. When the application is tracking user’s geographical location, browser
will ask for user’s consent and if user denies access then tracking will be disabled.
Once user gives consent by using geolocation api we can get user computer’s
latitude and longitude. That’s it, once we got latitude and longitude we can use
google map or bing map to plot it on the world map.

There is window.navigator object provided to play with geolocation. We check
whether browser is supporting the API or not in a similar manner we checked with
Storage API and AppCache API I explained in my previous article.

To get user’s location.
if(isGeolocationAPIAvailable) {
   window.navigator.geolocation.getCurrentPosition(displayPosition,
   displayError);
}
else {
   var result=document.getElementById("labelLocation");
   result.innerHTML = "Your browser is not supporting ";
   result.innerHTML = result.innerHTML + "HTML5 Geolocation API.";
}
function displayPosition(position) {
   var result=document.getElementById("labelLocation");
   result.innerHTML = "Latitude: " + position.coords.latitude +
                      "<br/>Longitude: " + position.coords.longitude;
}

How to handle Errors?
The second parameter I passed in previous example is displayError, which is the
function called if any error occured in calling getCurrentPosition.

function displayError(error) {
   var result=document.getElementById("labelLocation");
   switch(error.code) {
      case error.PERMISSION_DENIED:
           result.innerHTML="User denied the request for Geolocation.";
           break;
      case error.POSITION_UNAVAILABLE:
           result.innerHTML="Location information is unavailable.";
           break;
      case error.TIMEOUT:
           result.innerHTML="The request to get user location timed out.";
           break;
      case error.UNKNOWN_ERROR:
           result.innerHTML="An unknown error occurred.";
           break;
   }
}

How to display result in a map?
Once you got latitude and longitude, it is very easy to display those values in a map
using google map api or bing map api.
function displayPosition(position) {
   var result=document.getElementById("labelLocation");
   result.innerHTML = "Latitude: " + position.coords.latitude +
                      "<br/>Longitude: " + position.coords.longitude;
   var latitudeLongitude = position.coords.latitude + "," +
                           position.coords.longitude;
   var imageURL =
        "http://maps.googleapis.com/maps/api/staticmap?center=";
   imageURL = imageURL + latitudeLongitude;
   imageURL = imageURL + "&zoom=16&size=400x400&sensor=false";
document.getElementById("mapSpan").innerHTML =
         "<img src='"+imageURL+"'>";
}

The other properties returned by getCurrentPosition is
position.coords.latitude The latitude as a decimal number
position.coords.longitude The longitude as a decimal number
position.coords.accuracy The accuracy of position
position.coords.altitude The altitude in meters above the mean sea level
position.coords.altitudeAccuracy The altitude accuracy of position
position.coords.heading The heading as degrees clockwise from North
position.coords.speed The speed in meters per second
position.timestamp The date/time of the response

Geolocation API’s watchPosition() and clearWatch() methods
We can use watchPosition() for tracking moving objects like GPS in vehicle. The
clearWatch() stops calling watchPosition() method. The use of watchPosition() is
similar to getCurrentPosition() method.
if(isGeolocationAPIAvailable) {
   window.navigator.geolocation.watchPosition(displayPosition,
            displayError);
}
else {
   var result=document.getElementById("labelLocation");
   result.innerHTML =
    "Your browser is not supporting HTML5 Geolocation API.";
}
function displayPosition(position) {
   var result=document.getElementById("labelLocation");
   result.innerHTML = "Latitude: " + position.coords.latitude +
                      "<br/>Longitude: " + position.coords.longitude;
}

Conclusion
Using HTML5 it is now very handy tool for web developer to track user’s location or
to play with history entries of browser context.

Más contenido relacionado

Último

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Último (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Destacado

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

HTML5 History API and Geolocation API at Jinal Desai .NET

  • 1. Articles from Jinal Desai .NET HTML5 History API and Geolocation API 2012-12-30 15:12:35 Jinal Desai HTML5 History API It was very difficult to manipulate or control session history of particular browsing context before HTML5. Some workarounds like location.hash or page reloads are there which is not reliable. HTML5 History API allows web developers to move forward and backward in session history or adding/removing entries from session history easily. It is the History object of DOM interface. The History object is uniquely defined for each tab, which can be utilized for manipulating session history with some methods. The History object contains comma separated session entries in which each entries consists of a URL or a state object or both and in ddition can have title, a document object, form data, a scroll position and many other information associated with it. Let me list down some of the basic methods of it. window.history.state: Returns the current state object. window.history.replaceState(data, title [, url]): Updates the current entry in the session history, with the given data, title and URL (the URL is optional). window.history.forward(): Goes forwards by one step in the joint session history. If there is no next page to go to, it does nothing. window.history.go(n): Goes backwards or forwards by the specified number of steps in the joint session history. If the value you specify is zero, it will reload the current page. If it would cause the target position to be outside the available range of the session history, then nothing happens. window.history.back(): Goes backwards by one step in the joint session history. If there is no previous page to go to, it does nothing. window.history.pushState(data, title [, url]): Pushes the data specified in the arguments onto the session history, with the given title and URL (the URL is optional). window.history.length: Returns the number of entries in the joint session history. To add history entry. window.history.pushState({name:"Jinal Desai"},"FirstName","jinaldesai.net"); To replace history entry. window.history.replaceState({name:"Jinal Desai"},"Title", "startshining.com"); To navigate forward by 3 entries. history.go(3); This is fully functional example of HTML5 History API. HTML5 Geolocation API HTML5 Geolocation API is mainly used to track user’s geographical position, but this can compromise user’s privacy. Thus the position is not available unless the user approves it. When the application is tracking user’s geographical location, browser will ask for user’s consent and if user denies access then tracking will be disabled. Once user gives consent by using geolocation api we can get user computer’s latitude and longitude. That’s it, once we got latitude and longitude we can use
  • 2. google map or bing map to plot it on the world map. There is window.navigator object provided to play with geolocation. We check whether browser is supporting the API or not in a similar manner we checked with Storage API and AppCache API I explained in my previous article. To get user’s location. if(isGeolocationAPIAvailable) { window.navigator.geolocation.getCurrentPosition(displayPosition, displayError); } else { var result=document.getElementById("labelLocation"); result.innerHTML = "Your browser is not supporting "; result.innerHTML = result.innerHTML + "HTML5 Geolocation API."; } function displayPosition(position) { var result=document.getElementById("labelLocation"); result.innerHTML = "Latitude: " + position.coords.latitude + "<br/>Longitude: " + position.coords.longitude; } How to handle Errors? The second parameter I passed in previous example is displayError, which is the function called if any error occured in calling getCurrentPosition. function displayError(error) { var result=document.getElementById("labelLocation"); switch(error.code) { case error.PERMISSION_DENIED: result.innerHTML="User denied the request for Geolocation."; break; case error.POSITION_UNAVAILABLE: result.innerHTML="Location information is unavailable."; break; case error.TIMEOUT: result.innerHTML="The request to get user location timed out."; break; case error.UNKNOWN_ERROR: result.innerHTML="An unknown error occurred."; break; } } How to display result in a map? Once you got latitude and longitude, it is very easy to display those values in a map using google map api or bing map api. function displayPosition(position) { var result=document.getElementById("labelLocation"); result.innerHTML = "Latitude: " + position.coords.latitude + "<br/>Longitude: " + position.coords.longitude; var latitudeLongitude = position.coords.latitude + "," + position.coords.longitude; var imageURL = "http://maps.googleapis.com/maps/api/staticmap?center="; imageURL = imageURL + latitudeLongitude; imageURL = imageURL + "&zoom=16&size=400x400&sensor=false";
  • 3. document.getElementById("mapSpan").innerHTML = "<img src='"+imageURL+"'>"; } The other properties returned by getCurrentPosition is position.coords.latitude The latitude as a decimal number position.coords.longitude The longitude as a decimal number position.coords.accuracy The accuracy of position position.coords.altitude The altitude in meters above the mean sea level position.coords.altitudeAccuracy The altitude accuracy of position position.coords.heading The heading as degrees clockwise from North position.coords.speed The speed in meters per second position.timestamp The date/time of the response Geolocation API’s watchPosition() and clearWatch() methods We can use watchPosition() for tracking moving objects like GPS in vehicle. The clearWatch() stops calling watchPosition() method. The use of watchPosition() is similar to getCurrentPosition() method. if(isGeolocationAPIAvailable) { window.navigator.geolocation.watchPosition(displayPosition, displayError); } else { var result=document.getElementById("labelLocation"); result.innerHTML = "Your browser is not supporting HTML5 Geolocation API."; } function displayPosition(position) { var result=document.getElementById("labelLocation"); result.innerHTML = "Latitude: " + position.coords.latitude + "<br/>Longitude: " + position.coords.longitude; } Conclusion Using HTML5 it is now very handy tool for web developer to track user’s location or to play with history entries of browser context.