HTML5 Geolocation to show current location with Google Maps API

Geolocation allows you to give your current location information to the browser. Google use Geolocation a lot, especially for things like Google Maps, you’re bound to have seen the popups ‘This page would like to use your current location’. If so, you’ve experienced HTML5 Geolocation.


Sourec Code :-
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>HTML5 Geolocation to show current location with Google Maps API</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <style>
        html,
        body,
        #google_canvas {
            height: 100%;
        }

            #google_canvas h1 {
                font-size: 16px;
            }

            #google_canvas h2 {
                font-size: 14px;
                font-weight: 300;
            }
    </style>
</head>
<body>




    <div id="google_canvas"></div>

    <script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>

    <script>
        (function () {

            if (!!navigator.geolocation) {

                var map;

                var mapOptions = {
                    zoom: 15,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                map = new google.maps.Map(document.getElementById('google_canvas'), mapOptions);

                navigator.geolocation.getCurrentPosition(function (position) {

                    var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

                    var infowindow = new google.maps.InfoWindow({
                        map: map,
                        position: geolocate,
                        content:
                                                         '<h1>Location pinned from HTML5 Geolocation!</h1>' +
                                                         '<h2>Latitude: ' + position.coords.latitude + '</h2>' +
                                                         '<h2>Longitude: ' + position.coords.longitude + '</h2>'
                    });

                    map.setCenter(geolocate);

                });

            } else {
                document.getElementById('google_canvas').innerHTML = 'No Geolocation Support.';
            }

        })();
    </script>


</body>

</html>

Out-put:-



Note :On page load browser asks you for access your location so once you need to allow it.


HTML5 Geolocation to show current location with Google Maps API HTML5 Geolocation to show current location with Google Maps API Reviewed by NEERAJ SRIVASTAVA on 3:39:00 PM Rating: 5

No comments:

Powered by Blogger.