in ,

HTML5 Geolocation: Start Up With Geolocation HTML5 Tutorial

Basically, The W3C Geolocation API is referred as an effort made by World Wide Web Consortium in context of standardize an interface to fetch the geographical location information for a device from client-side. It designate an array of some specific objects like ECMA Script standard compliant which executes in the client application. However, reveals location in account of Location Information Servers which are supposed to be transparent for Application Programming Interface (API). The regularly employed source of location information are Wi-Fi and Bluetooth, IP address, Wi-Fi connection location, device GPS (Global Positioning System), GSM/CDMA cell IDs etc.

The W3C Geolocation API employ scripted access to alliance geographical location information with the browser of a device. However, in coming section of this post we will attempt to discuss about what we can accomplish in account of this data employing Google Maps as well as other third-party libraries followed by knowing how to access this API.

The examples employed in this tutorial post HTML5 Geolocation: Start Up With Geolocation HTML5 Tutorial is concerned with jQuery that can be easily incorporated by a script tag. However, it eliminates the need to download jquery.js file; Your web page is capable to employ the version hosted on Google’s CDN (Content Delivery Network).

1. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>

Therefore, when a call to file is not available over the internet, the local copy of jQuery file come forward after fallback and look for the earlier copy’s successful inclusion.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
  <script>window.jQuery || document.write("<script
    src='js/libs/jquery-1.6.4.min.js'>\x3C/script>")</script>

Getting basic Geolocation data

How to Find the location of the User’s Internet Device

You can implement the new HTML5 Geolocation API to trace the location of users. When you are supposed to click a button the output values to the webpage will appear like this.

HTML5 Geolocation

Now, initiate to include an input button in the page.

1. <input type="button" id="go" value="Click Me To View Your Location" />

Next, you are supposed to include this JavaScript in order to manage the event of this button click, access the Geolocation API and output the result.

1. <script>
2. $(document).ready(function () {
3.     // wire up button click
4.     $('#go').click(function () {
5.         // test for presence of geolocation
6.         if (navigator && navigator.geolocation) {
7.             navigator.geolocation.getCurrentPosition(geo_success, geo_error);
8.         } else {
9.             error('Geolocation is not supported.');
10.         }
11.     });
12. });
13.
14. function geo_success(position) {
15.     printLatLong(position.coords.latitude, position.coords.longitude);
16. }
17.
18. // The PositionError object returned contains the following attributes:
19. // code: a numeric response code
20. // PERMISSION_DENIED = 1
21. // POSITION_UNAVAILABLE = 2
22. // TIMEOUT = 3
23. // message: Primarily for debugging. It's recommended not to show this error
24. // to users.
25. function geo_error(err) {
26.     if (err.code == 1) {
27.         error('The user denied the request for location information.')
28.     } else if (err.code == 2) {
29.         error('Your location information is unavailable.')
30.     } else if (err.code == 3) {
31.         error('The request to get your location timed out.')
32.     } else {
33.         error('An unknown error occurred while requesting your location.')
34.     }
35. }
36.
37. // output lat and long
38. function printLatLong(lat, long) {
39.     $('body').append('<p>Lat: ' + lat + '</p>');
40.     $('body').append('<p>Long: ' + long + '</p>');
41. }
42.
43. function error(msg) {
44.     alert(msg);
45. }
46. </script>

In this JavaScript, the navigator object allows us to access new geolocation object. This geolocation object incorporates the following approach:

getCurrentPosition() reset to user’s current position.
watchPosition() displays the user’s current position and in the mean time monitor the position and adjure the accurate callback all time when designate changes in position.
clearWatch() checks the watchPositioin() method of monitoring current positon.

Before, call to getCurrentPosition() first of all ensure that either user’s location of the internet device and its browser is supported by Geolocation feature or not.

1. if (navigator && navigator.geolocation) {
2.     navigator.geolocation.getCurrentPosition(geo_success, geo_error);
3. } else {
4.     error('Geolocation is not supported.');
5. }

As, this method used to executes asynchronously, it passes two callback functionality: geo_error and geo_success. The error callback reveals an object of error in positions which constitute a code or a message property. The code may be concern with one among the following:

  • Unknown
  • Permission Denied
  • Position Unavailable
  • Timeout

The success callback deliver a position object which contains a coordinates object as well as a timestamp. The coordinates object incorporate following element:
latitude, it is defined in decimal degrees.
longitude, defined is decimal degrees.
altitude, is defined in meters above the mean sea level
accuracy, is defined in meters.
AltitudeAccuracy, is defined in meters.
heading, is the travel’s direction defined in degrees
speed, is measured in meters per second.

These elements are not guaranteed except three and i.e. longitude, latitude and accuracy. For instance, consider longitude and latitude as well as append to webpage body by employing jQuery.

1. function printLatLong(lat, long) {
2.     $('body').append('<p>Lat: ' + lat + '</p>');
3.     $('body').append('<p>Long: ' + long + '</p>');
4. }

How to Get Basic Geolocation Data with a Fallback

Do you wish to determine a user’s internet location when user’s browser is not supported by HTML5 Geolocation API natively. Take a look over this.

You are required to accomplish an IP-to-location lookup as fallback. Of course, it is not so specific latitude and longitude coordinates, but it will be good rather than comprising nothing about location data.

Google vs. MaxMind

Google used to offer google.loader.ClientLocation object in its Google Maps API V3 library, but it may not accessible with many US IP addresses.

The MaxMind GeoIP JavaScript Web Service referred as more accurate and updated. In addition MaxMind provide a JavaScript attribution free license at the cost of $250/year.

However, you can make prominent modification in our previous example to implement MaxMind as a fallback. So, simply go ahead and include the JavaScript library to the page.

1. <script src="https://j.maxmind.com/app/geoip.js"></script>

Then include MaxMind fallback

1. $(document).ready(function () {
2.     // wire up button click
3.     $('#go').click(function () {
4.         // test for presence of geolocation
5.         if (navigator && navigator.geolocation) {
6.             // make the request for the user's position
7.             navigator.geolocation.getCurrentPosition(geo_success, geo_error);
8.         } else {
9.             // use MaxMind IP to location API fallback
10.             printLatLong(geoip_latitude(), geoip_longitude(), true);
11.         }
12.     });
13. });
14.
15. // output lat and long
16. function printLatLong(latitude, longitude, isMaxMind) {
17.     $('body').append('<p>Lat: ' + latitude + '</p>');
18.     $('body').append('<p>Long: ' + longitude + '</p>');
19.     // if we used MaxMind for location, add attribution link
20.     if (isMaxMind) {
21.         $('body').append('<p><a href="http://www.maxmind.com" target="_blank">IP
22.            to Location Service Provided by MaxMind</a></p>');
23.     }
24. }
25.
26. function geo_error(err) {
27.     // instead of displaying an error, fall back to MaxMind IP to location library
28.     printLatLong(geoip_latitude(), geoip_longitude(), true);
29. }

When calling printLatLong() by employing Maxmind, transform this in an extra true parameter.

Rather than of displaying an error when navigator or navigator.geolocation is unspecified, implement the geoip_latitude() and geoip_longitude() functions which is provided by MaxMind JavaScript library to fetch the user’s longitude and latitude.

When you will scan the source of MaxMind geoip.js file, you will found that it has already transformed your IP address into location data. By going through the IP address which made the HTTP request, the MaxMind built a dynamic JavaScript, doing the IP-to-location transformation on the server side, an then revealing the results.

The below listed table incorporates the data location in addition to longitude and latitude.

HTML5 Geolocation2

You will be required to employ the attribution of free version of MaxMind in the form of a link back. So isMaxMind parameter has been included in the printLatLong() function in order to intimate the MaxMind was employed to retrieve the location.

1. function printLatLong(latitude, longitude, isMaxMind) {
2.          $('body').append('<p>Lat: ' + latitude + '</p>');
3.          $('body').append('<p>Long: ' + longitude + '</p>');
4.          // if we used MaxMind for location, add attribution link
5.          if (isMaxMind) {
6.              $('body').append('<p><a href="http://www.maxmind.com" target="_blank">IP to Location Service Provided by MaxMind</a></p>');
7.          }
8. }

Reverse Geocoding an address with latitude and longitude

Do you wish to transform longitude and latitude coordinates into user-friendly address. Then implement Google Maps JavaScript API to render latitude and longitude in a comprehending address, just like shown below:

HTML5 Geolocation3

The method of converting geographic data such as zip code, city name etc. into geographic coordinates like longitude and latitude is coined as term geocoding. However, performing the same thing in reverse, as converting coordinates into address, is known as reverse geocoding.

So, in order to initiate this include the required scripts into your web page

1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js">
2. </script>
3. <script src="https://j.maxmind.com/app/geoip.js"></script>
4. <script src="https://maps.google.com/maps/api/js?sensor=false"></script>

Next, include a button to provoke the users’s coordinates and determine the address.

1. <input type="button" id="go" value="Click Me To Find Your Address" />

and then you are required to include the JavaScript to manage the button click and getCurrentPosition() callback successfully.

1. $(document).ready(function () {
2.
3.     // wire up button click
4.     $('#go').click(function () {
5.         // test for presence of geolocation
6.         if (navigator && navigator.geolocation) {
7.             // make the request for the user's position
8.             navigator.geolocation.getCurrentPosition(geo_success, geo_error);
9.         } else {
10.             // use MaxMind IP to location API fallback
11.             printAddress(geoip_latitude(), geoip_longitude(), true);
12.         }
13.     });
14.
15.
16. function geo_success(position) {
17.     printAddress(position.coords.latitude, position.coords.longitude);
18. }
19.
20. function geo_error(err) {
21.     // instead of displaying an error, fall back to MaxMind IP to location library
22.     printAddress(geoip_latitude(), geoip_longitude(), true);
23. }
24.
25. // use Google Maps API to reverse geocode our location
26. function printAddress(latitude, longitude, isMaxMind) {
27.     // set up the Geocoder object
28.     var geocoder = new google.maps.Geocoder();
29.
30.     // turn coordinates into an object
31.     var yourLocation = new google.maps.LatLng(latitude, longitude);
32.
33.
34.     // find out info about our location
35.     geocoder.geocode({ 'latLng': yourLocation }, function (results, status) {
36.         if (status == google.maps.GeocoderStatus.OK) {
37.             if (results[0]) {
38.                 $('body').append('<p>Your Address:<br />' +
39.                     results[0].formatted_address + '</p>');
40.             } else {
41.                 error('Google did not return any results.');
42.             }
43.         } else {
44.             error("Reverse Geocoding failed due to: " + status);
45.         }
46.     });
47.
48.     // if we used MaxMind for location, add attribution link
49.     if (isMaxMind) {
50.         $('body').append('<p><a href="http://www.maxmind.com" target="_blank">IP
51.            to Location Service Provided by MaxMind</a></p>');
52.     }
53. }
54.
55. function error(msg) {
56.     alert(msg);
57. }

Now, you may determine the coordinates through getCurrentPosition() and deliver them to printAddress() function, that employs the Google Maps API to accomplished the reverse geocoding.

The printAddress() function starts by generating a new Google Geocoder object. The Geocoder object provide you access to the geocode() method, which incorporates distinct options as well as deliver information .
However, in this case, we are creating a new Google LatLng object which has been qualified into geocode() towards retrieving the address. Just like getCurrentPosition(), the geocode() method is also asynchronous, that’s why we feel need to specify an inline JavaScript function to cultivate the callback. The callback’s response comprises two distinct parameters, one belong to result and another status code. However, when the status is supposed to be OK, then it is secure to analyze the array of GeocoderResults object saved in the results variable. Furhter, the results variable is referred as an array since Geocoder is capable to provide more than one entry.

Next, you are required to analyze for a GeocoderResults object in first place of the array, and however in case it exists, append the formatted_address property for the webpage body.

Converting an address into latitude and longitude

So, if you ever wish to render an human-interface address into geographical address of longitude and latitude coordinates, then you can accomplish this through implementing Google Maps JavaScript API V3 as shown below and is termed as geocoding.
To start up add 1.6.4 and Google Maps JavaScript API V3 in your webpage.

1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js">
2. </script>
3. <script src="https://maps.google.com/maps/api/js?sensor=false"></script>

HTML5 Geolocation4

Now, tend the user input their address through an input text field, as the HTML5 Geolocation API can provide results only in coordinates.

1. <div>
2.     <label for="address">Enter an Address:</label>
3.     <input type="text" id="address" />
4. </div>
5. <div>
6.     <input type="button" id="go" value="Click Me To Find Latitude And Longitude"/>
7. </div>

The below specified JavaScript manage the button click and read the input assigned by users as well as calls the Google API to geocode the address:

1. $(document).ready(function () {
2.
3.     // wire up button click
4.     $('#go').click(function () {
5.         // get the address the user entered
6.         var address = $('#address').val();
7.         if (address) {
8.             // use Google Maps API to geocode the address
9.             // set up the Geocoder object
10.             var geocoder = new google.maps.Geocoder();
11.             // return the coordinates
12.             geocoder.geocode({ 'address': address }, function (results, status) {
13.                 if (status == google.maps.GeocoderStatus.OK) {
14.                     if (results[0]) {
15.                         // print results
16.                         printLatLong(results[0].geometry.location.lat(),
17.                             results[0].geometry.location.lng());
18.                     } else {
19.                         error('Google did not return any results.');
20.                     }
21.
22.                 } else {
23.                     error("Reverse Geocoding failed due to: " + status);
24.                 }
25.             });
26.         }
27.         else {
28.             error('Please enter an address');
29.         }
30.     });
31.
32. });
33.
34. // output lat and long
35. function printLatLong(lat, long) {
36.     $('body').append('<p>Lat: ' + lat + '</p>');
37.     $('body').append('<p>Long: ' + long + '</p>');
38. }
39.
40. function error(msg) {
41.     alert(msg);
42. }

When you will click the button, employ jQuery to analyze the value as well as authenticate that it’s not blank. Next, you are supposed to built an instance for Geocoder object. In context to achieve this, call geocode() method, but reveal an address option rather than of longitude and latitude.

1. // set up the Geocoder object
2. var geocoder = new google.maps.Geocoder();
3. // return the coordinates
4. geocoder.geocode({ 'address': address }, function (results, status) {
5. ...

Now, access the geometry property of GeocoderResults object. However, the geometry property incorporates a location property which can be employed to call the lat and lag method to retrieve your address’s coordinates, which are then implemented to web-page body in your printLatLong() function:

1. // print results
2. printLatLong(results[0].geometry.location.lat(), results[0].geometry.location.lng());

What do you think?

Written by Rinniee Ginsburg

Comments

Leave a Reply

Leave a Reply

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

Loading…

0

Comments

0 comments

Free PSD Template April 2012 – Download PSD Website template Free

Immersing Photoshop Texture Free Download