How to locate users position in map using html5 geolocation

Topics focus on Web Developments, Programming, Database, Digital Marketing Tutorials, Code Snippets, SEO, Social Media Marketing and Inspirational articles.

How to locate users position in map using html5 geolocation

How to locate users position in map using html5 geolocation

Html5 geolocation API enables you to identify the user’s position. The common sources of geolocation are Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs, as well as user input. There is no guarantee for approximate position.

Using getCurrentPosition() method, you can get the users position in the form of JavaScript Object. This object contains coordinates of the user’s position on the map.

Privacy:

Due to users privacy, User’s position will not be available unless the user approves it.

The basic usage of HTML5 geolocation is:

1
2
3
4
5
6
function showMap(position) {
 	alert(position.coords.latitude,position.coords.longitude);
}
 
// basic position request.
navigator.geolocation.getCurrentPosition(showMap);

Note: Run it with you browser, you get an alert with your coordinates..
Use watchPosition() To locate the user’s positions on move,

1
2
3
4
5
6
7
8
9
10
11
function scrollMap(position) {
      // Scrolls the map so that it is centered at (position.coords.latitude, position.coords.longitude).
    }
 
    // Request repeated updates.
    var watchId = navigator.geolocation.watchPosition(scrollMap);
 
    function buttonClickHandler() {
      // Cancel the updates when the user clicks a button.
      navigator.geolocation.clearWatch(watchId);
    }

Extended usage:

1
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);

Example:

1
2
3
var timeoutVal = 10 * 1000 * 1000;
 
navigator.geolocation.getCurrentPosition( showinmap, showerror, {enableHighAccuracy: true, timeout

How to locate user’s position in the map.

We use Google maps API to generate a map with user coordinates, take a look at the complete code.

Watch demo : http://w3easystep.info/geolocation/

With Google reverse geocoding, you can get the address with the latitude and longitude.
The complete code:

1
2
3
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
<!DOCTYPE html>
<html>
    <head>
        <title>HTML 5 | geolocation</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            #my_loc{
                width: 500px;
                height: 500px;
            }
        </style>
    </head>
    <body>
        <div id="my_loc"></div>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
        <script type="text/javascript">
            var mapoption = {
                zoom: 10,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById('my_loc'), mapoption);
            var geocoder = new google.maps.Geocoder();
            if (navigator.geolocation) {
                var timeoutVal = 10 * 1000 * 1000;
                navigator.geolocation.getCurrentPosition(
                        showinmap,
                        showerror,
                        {enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0}
                );
            }
            else {
                alert("Geolocation is not supported by this browser");
            }
 
            function showinmap(position) {
                var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                geocoder.geocode({'latLng': geolocate}, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[1]) {
                            var marker = new google.maps.Marker({
                                position: geolocate,
                                map: map,
                                icon: 'http://google-maps-icons.googlecode.com/files/market-farm.png',
                                title: 'Your approximate location'
                            });
 
                            var infowindow = new google.maps.InfoWindow({
                                map: map,
                                position: geolocate,
                                content: results[1].formatted_address
                            });
                            infowindow.open(map, marker);
                            map.setCenter(geolocate);
                        } else {
                            alert('No results found');
                        }
                    } else {
                        alert('Geocoder failed due to: ' + status);
                    }
                });
            }
            function showerror(error) {
                alert(error);
            }
        </script>
    </body>
</html>

Add comment


 

Pin It on Pinterest

Share This