SlideShare une entreprise Scribd logo
1  sur  3
Télécharger pour lire hors ligne
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.

Contenu connexe

Dernier

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 

Dernier (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 

En vedette

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
 

En vedette (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.