JQuery

Google maps api-Get current location of our website’s user

Google maps api-Get current location of our website’s user, someone asked me to explain?

In this article, I will show you how to find current location using google maps api geolocation. The Html5 geolocation api supports for HTML5, is used to determine the get latitude and longitude from google maps, using these coordinates you can display user’s current location on google maps.

To get started working with google maps location API click the link which will guide you the process of activating it.

Create an html page and create a div element and name id as “divmap” and load the maps using JavaScript API and display location on google map.

<script src="https://maps.googleapis.com/maps/api/js?v=3&key=YOUR-KEY" type="text/javascript"></script>

The URL contained in the script tag of the source will load all the symbols and definition of the goolge maps API.  You just pass the parameter API key to the URL.

HTML Code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&key=AIzaSyBRdtF6wK0hiNKlvpe92fT67mNg2Z9Ae5M"></script>
    <script type="text/javascript">
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (p) {
                var LatLng = new google.maps.LatLng(p.coords.latitude,p.coords.longitude);
                var mapOptions = {
                    center: LatLng,
                    zoom: 15,
                    mapTypeId:google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(document.getElementById("divMap"),mapOptions);
                var marker = new google.maps.Marker({
                    position: LatLng,
                    map: map,
                    title: "<div style ='height:60px;width:200px'><b>Your location:</b><br/>Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude
                });
               google.maps.event.addListener(marker, "click", function (e) {
                    var infoWindow = new google.maps.InfoWindow();
                   infoWindow.setContent(marker.title);
                    infoWindow.open(map,marker);
                });
            });
        } else {
            alert('GeoLocation feature is not supported in this browser.');
        }
    </script>
</head>
<body>
    <div id="divMap" style="width: 500px; height: 500px">
    </div>
</body>
</html> 

Output:

google maps directions from current location

Post your comments / questions