top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

JavaScript: How To Get GeoLocation In Your Browser?

+3 votes
420 views

Geolocation means recognizing or identifying the user’s location or any device’s location by the use of various data collection mechanisms. Most of time these type of services use GPS devices or network routing addresses. Geolocation varies in support with various devices. Some browsers support geolocation while some don’t. So it can’t be said confidently that geolocation is always possible for a web application.


Some browsers use IP addresses to determine user’s location. But using IP addresses to determine user’s location will just give a rough idea of the user position.


I totally disagree with this logic of using IP address to determine the geolocation. The word geolocation also means the latitude and longitude coordinates of a particular location.

In this article we we will see how geolocation works and the different capabilities it offers us. We will also see how easy it is to build an application to retrieve the user’s location.

 

Understand Geolocation Through A Diagram

Figure: Geolocation Diagram

What is the Geolocation API?


Geolocation API provides useful methods to fetch and use location data for web pages.

Applications of using Geolocation in your Browser/Apps

The various smartphones nowadays are using Geolocation functionalities in the form of GPS. This GPS functionality in different smartphones helps users to be connected with friends. Now each user is able to know the exact location of their near and dear ones. No doubt Geolocation is one of the most important features available in various smartphones, nowadays various companies are using this in their websites to enhance their business approach. By the use of geolocation in the websites, owners of particular business will now be concerned about the location of a visitor. Simultaneously users are also capable of knowing the exact location of the company which they are looking into.

If you are using web browsers then IP Address is responsible for determining anyone’s position, because GPS is not applicable on web. The other way is to ask Google for the location. In case of Smartphones the GPS hardware is put on and then you can find out the exact location and the distance.
 

In case of mobile phones it is very easy to determine the location as mobile devices directly access the position of the cell towers it’s talking to and finds your actual location.
 

In case of basic apps permission is always asked whether to allow fetching your location. This opt-in is often used in the native apps.

 

Taxi Booking: Cab Booking apps have made it easier for communicating from one place to another. It provides many mapping and geolocation features.

Such as: 

  1. The app identifies the Device Location
  2. It provides driving directions.
  3. Highlights the Direction Route.You can see how to reach tour destination.
  4. It works collaborately with various other mapping software.

By including Geolocation in your browser you can share your company's location in various map sharing apps to enhance your business.

Figure: Routes

Types of businesses which are most benefited by these geolocational features include Chain Retailers,Hotels and Restaurants. Any user can locate these businesses by specifying their interests according to their area of choice.


Figure: Asking Permission to share Location
 

Browsers Support:

  • Firefox 3.5+
  • Chrome 5.0+
  • Safari 5.0+
  • Opera 10.60+
  • Internet Explorer 9.0+
  • iPhone 3.0+
  • Android 2.0+

How to work with the Geolocation API?
 

It is very simple to use Geolocation API. First of all check which browsers support geolocation functionality.

If your browser supports Geolocation then you have to access navigator.geolocation object which provides the method and determines the user location. It depends on the method that you call on the geolocation object whether you need to just fetch the location data or you want to keep it monitoring continuously.

A callback function is also created to support the method which you call. A callback function is a function which you pass by reference into an object. The Geolocation API defines an interface used to get location information of the visitor. Using this API we will be returning Latitude and Longitude of the current user. In mobile devices, with the use of a GPS Chip, we can access information more easily now. Check If Browser Supports HTML5 GeoLocation API by writing the following lines of code. By using navigator.geolocation object, we can access the Geolocation API to call the method getCurrentPosition. You can say GPS/Geolocation is a Gold mine for Data Analysis. By the use of this you can track any place, person etc.

Demo Script

  1. <html>  
  2.     <head>  
  3.         <title>Geolocation</title>  
  4.         <script type = “text/javascript”>    
  5.             function init() {    
  6.                 alert(“Ready to be Loaded”);    
  7.             }    
  8.   
  9.             <script>  
  10.                 <body onload = “init() ;”>  
  11.                     <h1>Your current position</h1>  
  12.                     <p id = “mylocation”></p>  
  13.                 </body>  
  14.             </script>  
  15.         </script>  
  16.     </head>  
  17. </html>    



Figure: Output of the above written code in my localhost

Given below code is helpful in checking the support of the browser. If you include the below JavaScript code, then it will check the support of Geolocation Feature in your browser. Here I have simply used JavaScript.

  1. <script type = “text/javascript”>  
  2.    function init() {  
  3.       if(navigation.geolocation){  
  4.          document.getElementById(“mylocation”).innerHTML = “Ready to fetch Information”;  
  5.       }  
  6.       else{  
  7.          document.getElementById(“mylocation”).innerHTML = “Browser doesn’t support geolocation feature”;  
  8.       }  
  9.    }  

Note: In above code mylocation is the paragraph id.

This accepts three parameters:

  • Success callback function
  • Error Callback function
  • Position Options

Here we will be using success callback functions as we need something to happen only when the API successfully returns the position of the User.

The above code is written to find the longitude and latitude of the current user. After we have found the latitude and longitude of the user, we can apply co-ordinates to the Google Map API to display the location.

Now next step is to include Google Map’s JavaScript file to our page so that the longitude and latitude can be applied to the Google Map

 

Code:Position

  1. var cords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);  
  2. var options = {  
  3.     zoom: 15,  
  4.     center: coords,  
  5.     mapTypeControl: false,  
  6.     navigationControlOptions:  
  7.     {  
  8.         style: google.maps.NavigationControlStyle.SMALL  
  9.     },  
  10.     mapTypeId: google.maps.MapTypeId.ROADMAP  
  11. };  
  12. var map = new google.maps.Map(document.getElementById(“mapcontainer”), options);  
  13. Var marker = new google.maps.Marker(  
  14. {  
  15.     position: coords,  
  16.     map: map,  
  17.     title: ”you are here”  
  18. });  

Now as you are seeing in the above code, we have taken a variable named ‘coords’ and in this variable we have created a new method to find out the exact latitude and longitude position of the visitor.

Next to it we have written some functions to implement that method. The above lines of code display the co-ordinates of the user/visitor and will place a marker on this exact position.

We will place the above code snippet to our application so that the Google Map will be added to a div with an ID of ‘mapcontainer’.


Complete Code

  1. <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>  
  2.    function success(position) {  
  3.       var mapcanvas = document.createElement('div');  
  4.       mapcanvas.id = 'mapcontainer';  
  5.       mapcanvas.style.height = '400px';  
  6.       mapcanvas.style.width = '600px';  
  7.       document.querySelector('article').appendChild(mapcanvas);  
  8.       var cords = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);  
  9.       var options = {  
  10.          zoom: 15,  
  11.          center: coords,  
  12.          mapTypeControl: false,  
  13.          navigationControlOptions:{  
  14.          style: google.maps.NavigationControlStyle.SMALL  
  15.       },  
  16.       mapTypeId: google.maps.MapTypeId.ROADMAP  
  17.    };  
  18.    var map = new google.maps.Map(document.getElementById(“mapcontainer”),options);  
  19.    Var marker = new google.maps.Marker({  
  20.    position: coords,  
  21.    map: map,  
  22.    title: ”you are here”  
  23. });  
  24. if (navigator.geolocation) {  
  25.    navigator.geolocation.getCurrentPosition(success);  
  26. else {  
  27.       error('Geo Location is not supported');  
  28. }  
  29. </script>  


Figure: Geolocation

Conclusion

You can go through the above code and place it in your application.This geolocation functionality will be seen in your browser.

posted Jun 3, 2016 by Jdk

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

...