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

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Dernier (20)

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

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.