5 Website Development Tips To Boost Your Business Growth Exponentially

The geolocation functions in HTML5 were among the most anticipated for Web developers. With geolocation in your websites and Web applications, you can maximize on mobile resources and provide results that are tailored to the user. With a small amount of JavaScript working in conjunction with your HTML5 code, you can present website content that incorporates data about the user location. In this tutorial we will run through the basics of displaying the user location within the page, including the longitude and latitude. We will also build the longitude and latitude into a link to the user’s location on Google Maps.

Like many HTML5 facilities, geolocation is not available in all browsers. The page we build in this tutorial should function in recent versions of all of the major browsers, but will not function in older browsers. Additionally, the geolocation functions can be a little unpredictable, particularly in certain desktop browsers and depending on the type of Internet connection the user is accessing the page through. At this point it’s unwise to create pages and applications that are completely dependent on the geolocation functionality without creating alternative content for users whose browsers do not support the functions, as the level of both support and reliability remains relatively low at this time.

HTML5: Geolocation with HTML5 and JavaScript

Page Setup

Start by creating an HTML5 page using the following outline:

 <!DOCTYPE HTML> <html> <head> <script type="text/javascript">  </script> </head> <body>  </body> </html> 

We will be adding elements to the page body and code to the script section in the page head.

Page Content

Let’s fire the location functions when the user presses a button. Add one to the body section of your page as follows:

 <input type="button" value="show my location" onclick="show_user_location()"/> 

When the user clicks the button, we will attempt to retrieve their location in the specified function, which we will add to the script section soon. After the button, add an empty div element to the page:

 <div id="loc"> <!--location will appear here--> </div> 

We give the element an ID attribute so that we can refer to it in the script code. In it we will either display the user location information or an appropriate error message depending on what went wrong.

Location Function

Let’s now try to execute the location functionality. In the script section of your page head, add a variable declaration:

 var locElem; 

We will use this variable to refer to the div element we plan on writing location and error information into. Next inside the script section, add the outline for the function we specified as onclick attribute for the button:

 function show_user_location(){  //get location } 

This will execute when the button is clicked. When the geolocation code fires for the first time for a particular user on a particular site, their browser should prompt them for permission. The only exceptions to this are where the user has set their browser either to always allow geolocation requests or to always deny them. If they have their browser set to always deny, the geolocation function will not work for that user – we will output a relevant error message for this situation later. If the user has their browser set to always allow, the location functionality will execute straight away. In many cases, the user will have their browser set to prompt them for permission each time location access is requested. Typically, the browser will remember the user’s preference if they visit the same site again in future, so they will only be prompted the first time unless they later alter their settings.

Add the following inside the new function:

 locElem = document.getElementById("loc"); 

Now we have a reference to the empty div and can write to it throughout the script section. Next, still inside the function, attempt to retrieve the location:

 navigator.geolocation.getCurrentPosition(display_user_location, error_response); 

We use the navigator object to retrieve the location. The two parameters to the getCurrentPosition method represent two functions. The first function should execute if the location is retrieved successfully, with the second executing if an error occurs.

Show the Location

After the function we already added, add another function to your script section:

 function display_user_location(user_position){  //show position } 

Notice that this is the first parameter we included to the getCurrentPosition method so will execute when the position retrieval has been successful. This method receives a parameter representing information about the user position. Inside this method, read the latitude and longitude into variables:

 var lat = user_position.coords.latitude; var lon = user_position.coords.longitude; 

Now write these into the page along with some informative text and a link to Google Maps:

 locElem.innerHTML="<p>Your latitude is: "+lat+", your longitude is: "+lon+"</p>"+ 	"<p><a href='http://maps.google.com/?q="+lat+","+lon+"'>View your location on Google Maps</a></p>"; 

This writes a couple of paragraphs into the empty div. The first paragraph simply displays the latitude and longitude within some informative text. The second includes a link to the location on Google Maps.

Deal with Errors

The reality of using geolocation is that you will encounter errors, so let’s deal with them next. After the display_user_location function, add a final function to the script section of the page:

 function error_response(geo_error){ //deal with error } 

As you can see, this is the function we listed as second parameter to the getCurrentPosition method, to execute when an error occurs. The method parameter includes information about the nature of the error. Inside the function, add a switch statement tailoring the response to the type of error:

 switch(geo_error.code) { 	case geo_error.PERMISSION_DENIED: locElem.innerHTML="User permission denied!"; 	break; 	case geo_error.POSITION_UNAVAILABLE: locElem.innerHTML="Position not available!"; 	break; 	case geo_error.TIMEOUT: locElem.innerHTML="Location retrieval timed out!"; 	break; 	case geo_error.UNKNOWN_ERROR: locElem.innerHTML="Unknown error"; 	break; 	default: locElem.innerHTML="Unknown error"; 	break;   	} 

The code writes a specific error message into the empty div for the particular type of error that has occurred. Here is the page code in its entirety:

 <!DOCTYPE HTML> <html> <head> <script type="text/javascript"> var locElem; function show_user_location(){  	locElem = document.getElementById("loc"); 	navigator.geolocation.getCurrentPosition(display_user_location, error_response);  } function display_user_location(user_position){  	var lat = user_position.coords.latitude; 	var lon = user_position.coords.longitude; 	locElem.innerHTML="<p>Your latitude is: "+lat+", your longitude is: "+lon+"</p>"+ 		"<p><a href='http://maps.google.com/?q="+lat+","+lon+"'>View your location on Google Maps</a></p>"; } function error_response(geo_error){ 	switch(geo_error.code) { 	case geo_error.PERMISSION_DENIED: locElem.innerHTML="User permission denied!"; 	break; 	case geo_error.POSITION_UNAVAILABLE: locElem.innerHTML="Position not available!"; 	break; 	case geo_error.TIMEOUT: locElem.innerHTML="Location retrieval timed out!"; 	break; 	case geo_error.UNKNOWN_ERROR: locElem.innerHTML="Unknown error"; 	break; 	default: locElem.innerHTML="Unknown error"; 	break;   	} }   </script> </head> <body> <h1>Geolocation with HTML5 and JavaScript</h1> <input type="button" value="show my location" onclick="show_user_location()"/> <div id="loc"> <!--location will appear here--> </div> </body> </html> 

Conclusion

You can test your page now. Upload it to a browser to view it, as the geolocation functions must be used on a Web server. You can experiment by setting your location preferences in your browser and testing the error messages. Clicking on the link should take you to your current location on Google Maps. You can build the code into a Google Map within your own page if you use the JavaScript API in your HTML5 code. You can also use location data to present users with information relevant to their current area using other APIs, for example to link to nearby services.

Read more http://www.webdesign.org/html5-geolocation-with-html5-and-javascript.22301.html


Published on: Mar 03, 2021

Categories: Web Development

    No Comments yet! Be the first one to write.


    Leave a Reply

    Your email address will not be published. Required fields are marked *

    user IP : 44.201.97.0 | Server_IP: 135.148.43.245 | IP_Score: