Your Ad Here

Sunday, February 8, 2015

Get User Current location by google map API

Using the few classes described in google API , We can  able to write a simple, yet nice, application. The example isn’t very hard to understand, but still uses all of the classes and methods discussed. The example retrieves the user’s position, and shows it using a marker on the map. The Geocoder service is used to retrieve the user’s complete address, and display it on the page. We’ll also use the accuracy parameter of the retrieved position to draw a blue circle around the location.
The first step to using the Maps API is to actually include it. This is very simple and consists of just adding the following line to your web page.


Since Google Maps will still work without the key, and to avoid the long line in the example, simply write the following instead.
 
1

Notice that both lines contain a sensor parameter. It must be included in the URL and set to true if you’re using a sensor (like a GPS), or false otherwise. You can read more on this at Loading the Maps API.
To build the example we’ll use two functions. The first one uses the user’s position to create a map and draw a circle around the user. The second function queries Google to retrieve the address of the user based on its location. Let’s see the key points of both.
 
1
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

This simple line uses the latitude and longitude of a Position object to create the LatLng object. We’ll use this object in the rest of the function. In fact, it’ll be used in the MapOptions to set the center of the Map we’re building. As a container for the map, I’ll use a <div> element, with an id of map.
 
1
2
3
4
5
6
var myOptions = {
  zoom : 16,
  center : userLatLng,
  mapTypeId : google.maps.MapTypeId.ROADMAP
}
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);

Now it’s time to add the marker to the map to signal the user’s position. We’ll use the Google Maps default icon, but you can specify an image you like using the icon property or the setIcon() method.
1
new google.maps.Marker({map: mapObject, position: userLatLng });
At this point you could close the function and have a map displaying the user position with a simple marker. However, since in a desktop environment the accuracy could be very low, it would be nice to visualize it. We’ll accomplish this using the Circle class that, as you might guess, draws a circle on the map. It has a lot of properties to set the color, the opacity, the radius, and so on, but the most important property is the map object where it applies.
 
1
2
3
4
5
6
7
8
9
10
var circle = new google.maps.Circle({
  center: userLatLng,
  radius: position.coords.accuracy,
  map: mapObject,
  fillColor: '#0000FF',
  fillOpacity: 0.5,
  strokeColor: '#0000FF',
  strokeOpacity: 1.0
});
mapObject.fitBounds(circle.getBounds());

Please note that the last statement calls the fitBounds() method with the bounds taken from the circle. This is done to ensure that if the circle goes outside of the zoomed view, the map will be zoomed out accordingly to display the entire circle.
The second function, named writeAddressName(), takes a LatLng object and sets the location property to query the Geocoder service. In the callback function we’ll test if an error occurs. If an error does occur, it will be displayed. Otherwise, the formatted address is displayed.
 
1
2
3
4
5
6
7
8
9
10
11
12
function writeAddressName(latLng) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    "location": latLng
  },
  function(results, status) {
    if (status == google.maps.GeocoderStatus.OK)
      document.getElementById("address").innerHTML = results[0].formatted_address;
    else
      document.getElementById("error").innerHTML += "Unable to retrieve your address"  + "<br />";
  });
}

Putting it all Together

Given the code shown in the previous section, the final and completely working code is shown below.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Geolocation and Google Maps API</title>
    <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
    <script>
      function writeAddressName(latLng) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
          "location": latLng
        },
        function(results, status) {
          if (status == google.maps.GeocoderStatus.OK)
            document.getElementById("address").innerHTML = results[0].formatted_address;
          else
            document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br />";
        });
      }
 
      function geolocationSuccess(position) {
        var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        // Write the formatted address
        writeAddressName(userLatLng);
 
        var myOptions = {
          zoom : 16,
          center : userLatLng,
          mapTypeId : google.maps.MapTypeId.ROADMAP
        };
        // Draw the map
        var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
        // Place the marker
        new google.maps.Marker({
          map: mapObject,
          position: userLatLng
        });
        // Draw a circle around the user position to have an idea of the current localization accuracy
        var circle = new google.maps.Circle({
          center: userLatLng,
          radius: position.coords.accuracy,
          map: mapObject,
          fillColor: '#0000FF',
          fillOpacity: 0.5,
          strokeColor: '#0000FF',
          strokeOpacity: 1.0
        });
        mapObject.fitBounds(circle.getBounds());
      }
 
      function geolocationError(positionError) {
        document.getElementById("error").innerHTML += "Error: " + positionError.message + "<br />";
      }
 
      function geolocateUser() {
        // If the browser supports the Geolocation API
        if (navigator.geolocation)
        {
          var positionOptions = {
            enableHighAccuracy: true,
            timeout: 10 * 1000 // 10 seconds
          };
          navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError, positionOptions);
        }
        else
          document.getElementById("error").innerHTML += "Your browser doesn't support the Geolocation API";
      }
 
      window.onload = geolocateUser;
    </script>
    <style type="text/css">
      #map {
        width: 500px;
        height: 500px;
      }
    </style>
  </head>
  <body>
    <h1>Basic example</h1>
    <div id="map"></div>
    <p><b>Address</b>: <span id="address"></span></p>
    <p id="error"></p>
  </body>
</html>

Conclusions

This article has explained several methods and properties of the most important classes in the Google Maps API. Moreover, we’ve shown how you can use them together with the Geolocation API to built a complete and functional service to track your user’s position and locate them on a map. Of course, you can do more a lot more than that as you’ll see in the next article on this amazing API.